Java/Guava convention for using 'get' prefix? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
On a project that I am working on, we are debating when to use get (getFoo) vs a normal name (foo) in java. When I look around in java core and guava, I see that there are many examples where get is omitted. Is there any doc that covers when guava or new java APIs will use the get prefix and when not to? Is there a convention these developers use here?
Thanks for taking the time to read this.
Examples:
ByteBuffer : http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#compact()
ForwardingObject : http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/ForwardingObject.html#delegate()
Stopwatch : http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Stopwatch.html#elapsed(java.util.concurrent.TimeUnit)
Ticker : http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Ticker.html#systemTicker()
EDIT:
As of http://download.oracle.com/otn-pub/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/beans.101.pdf, "A Java Bean is a reusable software component that can be manipulated visually
in a builder tool." In our code base, the issue of get vs no get comes when the code has nothing to do with value or data objects (objects that represent data). When the class represents data, we are fine doing get.
My main question is why both java and guava choose to use non get methods for non data objects and what are their conventions.

The get prefix comes from the JavaBeans Conventions, which states that if you have an accessor for a property, then the accessor method's name must start with get, unless it is a boolean (the primative type), in which case is should start with is. Note that you use the get prefix to return type Boolean.
Throughout most of Java's API this is the convention that is used, which would be my recommendation as well. Your decision is up to you, but whichever convention you pick, I would suggest to be consistent and not mix the two.

While the idea of dropping the "get" appeals to me, the problem comes when you also have a setter. You would have to do something like
public String name(); // getter
and
public void name(String newName); // setter, xor use the below **instead** but not both
public Foo name(String newName); // if you prefer fluent/builder style
Which "looks weird" to a Java programmer. And until 1 minute ago I thought it was illegal, and my original post mistakenly said so until I tested it. You learn something everyday...
Added in response to #DwB
One good reason to use get/set is that many 3rd party frameworks expect this convention, as they use reflection to reason about your class. However, a framework could be able to look for combinations like the above, or be configured to use these methods instead of the usual get/set. This was almost in my original post but I haven't used Spring, Hibernate etc. in a few years so I'm not up to speed on what some of them will on won't allow if you aren't using get/set.
For example, Jackson can use annotations and mixins to define mappings, no need to follow get/set convention. I would think that Spring, JSF etc. could do likewise, (somebody please edit this answer with details as needed) though with some extra work. Whether this extra work is worth the "conciseness" of eliminating get/set is unclear. I'd say no, but YMMV.

Related

Finding the Java docs deprecated messages [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How do I navigate to the informative messages about a deprecated class in Java documentation?
I have seen something like this in other answers:
From StringTokenizer documentation:
StringTokenizer is a legacy class that is retained for compatibility
reasons although its use is discouraged in new code. It is recommended
that anyone seeking this functionality use the split method of String
or the java.util.regex package instead.
But how do I get to this informative message in the Java docs? All I can see is a DEPRECATED link at the top. I need the extra information so I can understand the reason for it being deprecated and use its alternative.
There won't be any reliable way to do that. The text you have found is an informal advice about the class. This class is NOT formally deprecated. Deprecated means something very specific in the Java context. It is much stronger than "use is discouraged in new code".
If a class or class member is really deprecated in Java, you will see a #Deprecated annotation in the source code. This is what the Java tool chain pays attention to. There may also be a #deprecated javadoc tag with an explanation and suggestions for alternatives, where appropriate. That is what is turned into the "Deprecated:" heading in the javadocs.
Finding informal advice like the example you have identified would probably require searching the Java library codebase or the javadoc tree for key phrases like "legacy" and "not recommended". You would then need to manually filter out the false positives.
Most of the time, the reason a class was deprecated is because a better alternative was found or because it's simply no longer required.
As for the deprecated link at the top you mentioned, I assume you mean the following: https://docs.oracle.com/javase/8/docs/api/deprecated-list.html
Well, like you said, those are all the information you'll find, and they're pretty descriptive too.
Let's take the constructor Date(int year, int month, int day) for example, if you scroll down to the deprecated constructor section, you can find the following:
java.sql.Date(int, int, int)
instead use the constructor Date(long date)
and it does the same thing for every classes/methods/interfaces marked with the #Deprecated annotation in the JDK.
Also, for StringTokenizer, if you read just below the line you quoted, it says the following:
The following example illustrates how the String.split method can be
used to break up a string into its basic tokens:
String[] result = "this is a test".split("\\s");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
Basically, StringTokenizer is no longer necessary because the String object now has a split method, which makes StringTokenizer useless.

Creating a class over a single variable in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
If you are creating a library to be re-used does it make sense (or in general usage), to create a class over a single dataype/variable. So for instance,
class DataSet
{
private HashMap<String,String> mapping;
public String getKey();
public String getValue(String key);
}
Let's say I have a method DataSet getDataSet(), Does it make sense to have this method in my API that returns HashMap or should it return DataSet?
Some benefits of returning DataSet over java collection type are -
Code is easy to very verbose and easy to read.
Writing unit tests at class level.
Finer control on internal storage structure - user cannot directly modify that collection.
Are there are disadvantages to this approach? Or is it always recommended especially when creating APIs/libraries to use own classes instead of known java datatypes?
Wrappers in general
As for the general question on whether to use wrappers or not that depends on the reasons and it may vary between use cases.
Some advantages of wrappers
Type safety: you could wrap a primitive to provide some sematic safety by the compiler. As an example you could use a class Key which contains a single string instead of just a String to point out that the string inside is meant to be a key. This might help you in cases where multiple strings might get confused.
Access control: like you described, allow read/write access etc.
"Manual" AOP: wrap setters/getters with logic.
Some disadvantages:
Code is more verbose and might get harder to understand/handle.
More effort is needed to write all those wrappers (and ideally documentation).
Existing/common datatypes like collections, strings etc. are more widely understood thus easing the learing curve.
Returning HashMap
If you'd return a map then I'd not return HashMap<String,String> but rather Map<String, String>.
Wrapper vs. Map
Besides that it depends on what you're trying to achieve. Of course using a wrapper object gives you more control of the API at the cost of more code to be maintained.
Delegation
Besides using DataSet as you described it delegation might be an option, i.e. a class that looks like a map but just delegates calls to an internal map. That way you could add functionality in the methods like preventing write access, validation in a transparent way (for read-only maps there are already delegate wrappers in the Collections class).
Unit tests
As for the "Writing unit tests at class level." point I'd say that also depends on what the wrapper would do. If it just resembles a map then creating a test for that wrapper only might be somewhat wasted time (you could just use an existing and already tested map implementation). Additionally you'd probably test the functionality that operates on/returns that wrapper/map and those tests would be mostly independent of whether you use a wrapper or a map.
That's just my 2 50 cents ;)

Java: Include "this" parameter or let it be implied [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is there a Java recommendation or industry best-practice suggestion for including, or not including, the this parameter when it isn't explicitly necessary?
For instance, assuming there are no naming clashes between instance variables and local variables, is it preferential to use
this.someParam
or simply
someParam
and when calling methods that are in the same class is it preferential to use
this.someMethod()
or
someMethod()
The argument in favor of the former is that it makes the code more explicit. The argument in favor of the latter is that it makes the code cleaner.
I'm curious if there is any documentation out there that recommends one way or another (I can't find any, google searches with the word this are obviously tricky) or if it is simply a matter of preference.
On the merits of explicit versus cleaner: Excluding "this." is no doubt less text character "noise" (albeit small) in source file. The "this." explicitness would be helpful for example if using a small text viewer when looking at a method with many lines of code (should that be the case anyway?). So at best the explicitness has limited usefulness - especially as modern IDEs highlight instance variables. I am of the opinion of excluding "this." as code style.
I don't know that there is a "wrong" answer here. However, in my 15+ years writing Java, the convention that I have seen is to NOT include "this" unless it is necessary.
You can minimize confusion by naming variables in a consistent way. There are several good convention documents out there. Pick one and follow it. Some examples:
http://google-styleguide.googlecode.com/svn/trunk/javaguide.html
https://source.android.com/source/code-style.html
http://www.javaranch.com/style.jsp
There is no reason to prefer one or the other. It's a matter of opinion.
My opinion is that you should only use this if needed. There are some situations when you have to use this, such as if a local variable has the same name as an instance variable. It happens a lot in my constructors:
public MyClass(String s, int i) {
this.s = s;
this.i = i;
}
If you are working on a team, I recommend coming up with a strategy you all agree with, so you don't waste too much time reformatting each others code. Also, for me, it's pretty annoying to look at code that uses this too much (such as that generated by JD).
As for:
parameters/attributes - I always suggest using consistent approach throughout the code. In most cases all automatically generated getters and setters of Java classes need to use this to distinguish parameter name from actual object attribute. Consistency is then a good reason to use this for instance variables throughout the code. Sample setter which uses this to avoid ambiguity:
public void setName(String name) {
this.name = name;
}
methods - this.someMethod() is just longer than someMethod() and does not provide any benefit over the shorter someMethod(). If we call the latter, it is already known that we are in fact calling this.someMethod(). There is no ambiguity in calling just someMethod() like it is for parameters, so I would discourage the use of this.someMethod().
In my opinion, there is no common guidelines for all Java developers in the world defining good practices for using this. I'd rather follow the guidelines used in your company/project, or, if there are none, your own ways of writing well-read code.
There isn't a best-practice suggestion. Most teams simply have their own coding style.
Personally, I try to use use this for all my instance variables, but tend to avoid it for methods.

In Java, when should we use a single, comprehensive getter method that can return many objects rather than a bunch of smaller getter methods? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
To clarify, this is what I mean:
public Image getRespectiveImage(int temp) {
switch(temp){
case 1:return one;
case 2:return two;
case 3:return three;
case 4:return four;
case 5:return five;
}
return null;
}
compared to
public Image getOne(){return one;}
public Image getTwo(){return two;}
public Image getThree(){return three;}
public Image getFour(){return four;}
public Image getFive(){return five;}
I tend to prefer the former because it just seems simpler for some reason, but everyone seems to use the latter. Is there a reason why someone would use the bunch of getter methods?
It's not really about "which is better or worse" -- If the properties you are writing getters for are not, by nature, indexed, then it would make no sense to write an indexed getter for them. If your properties are not of the same type, that is a good clue that an indexed representation isn't generally going to be helpful.
If the properties you are using do make sense to store as an indexed list, then sure, by all means -- but then I would also use an array for the field (consider: If an array type is not appropriate for that field, then perhaps an indexed getter is not actually appropriate either).
You generally want your getters and setters to reflect the fields you have declared. You would use a getter/setter that takes an int index parameter when your field is an array type (which conforms to the JavaBeans spec, section 8.3.3).
You want to do this for two reasons. First, on a conceptual level, if your fields are significantly different from your getters/setters, while there are tons of valid reasons for this, you may want to take a look at how you've organized your fields to see if you can refactor to something that more accurately represents the purpose of your object (it is assumed that public getters/setters are good representations of this purpose). It may be an indication of bigger design issues.
Secondly, and this is more just about being aware of what you are doing, your getters and setters will affect interaction with APIs that operate on beans, and will also affect interaction with APIs that use reflection. For example, Hibernate can be configured to persist objects to a database using getter/setter properties, or direct field access. So depending on the configuration there, you have to at least be aware of your getter/setter vs. field setup.
The take home point here is: Don't try to come at this with the idea that there is a set of rules defining when one way is better or worse. Just consider the nature of the objects you are working with, and what their properties actually mean (semantics), and write a public interface that makes sense.
It's good practice to have getters and setters for all private variables that you want the user to interact with.
While your above solution simplifies, it will confuse other people that work with your code because it is not common practice.
It depends on the problem you're facing. There's nothing wrong with the first approach, even more if you use an "enum" to restrict and document the options:
enum ImageCategory {
Unchecked,
Checked,
Disabled;
}
Image getRespectiveImage(ImageCategory category);
Just be sure that every "category" represents an instance of the same nature.
On the other side, it's clearly not a good thing to have a method like this:
Object get(String property);
Unless you're writing your own Dictionary/Map class.
Using a bunch of getter methods has two noticable advantages over the first approach.
The getter methods, when named properly, self document what it is that you're getting from the object.
In the first case, you would need to provide the user with some kind of documentation that tells them which input corresponds to return. This is not necessary when you have separate getters. (It places a greater burden on the clients)

Interface or Class for a list of static finals? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I am maintaining some Java code that utilizes an interface (let's call it BunchOfConstants) to simply store an abundance of public static final Strings. Occasionally these string names change or string names are added / removed. (which causes a bit of a headache for maintanance)
The only current use for this interface is to compare to input later in a big ugly if/then construct like this:
if(BunchOfConstants.CONSTANT1.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}else if(BunchOfConstants.CONSTANT2.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}else if(BunchOfConstants.CONSTANT3.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}
...
I thought it would be more elegant to create a class that implements Iterable or even a class that stores this data in a hashMap.
I can not figure out why the original developers decided to use an interface for this design as the interface is never actually implemented anywhere. Does anyone have any input?
Would you agree that an iterable class with these members as constants would be more appropriate?
Use enums. Then get myenum.values() and then apply a for-each loop over the values.
I would consider using enums instead as constants are not type safe (e.g., they are just ints, or strings, etc.).
This (having dedicated interface for storing constants) was a fairly common way of storing constants before the era of enums. (Pre Java 5 times.) It saved you the hassle of prefixing your constants with the containing class name. I personally never really liked this practice, but this is the reason people did it.
As for what it can be replaced with:
An enum and a switch/case construct. This requires the least modification but only has modest benefits in readability. It does give you type and value safety, plus you can get warnings out of your IDE if you forget to handle a possible value (no case for it and no default block either).
A properties file. This obviously only works if you don't want to branch based on your constant values. (I.e. if your constants don't have to appear in your source code.) This is important, otherwise you'd end up with a secondary set of constants and a properties file, which is as bad as it gets.
A doSomeStuff() factory. For this you have to wrap your doSomeStuff() implementations in separate operation classes and you can configure your factory either statically or from a properties file. (via a constant value->operation class mapping). This is the most "enterprisey" solution, which means that although it looks nice and is very flexible, a lot of the time it is an overkill.
I think this is a good candidate for enum
Well, this looks like the Constant Interface antipattern and maybe should not be used. Using an enum might be a way as suggested, or at least using a final class with private constructor.
If you want to have different implementations for doSomeStuff based on the input string, you might also consider using the strategy pattern, i.e. have a Map<String, Strategy> and then lookup the strategy for whatImLookingFor. If you found the strategy, execute its doSomeStuff, otherwise handle the "not found" case.
I would suggest you to use a property file to store all your constants. This way you can load your properties into a HashMap as you suggest in your question.
Note that property support is brought natively with java: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Properties.html
Well, enums are the way to go ... but if the 'dosomestuff' is semantically dependent upon the specific value then why not add a 'dosomestuff' method to the enum itself. That is one that this is really great about Java enums - they are not merely data but as all good objects they have semantics. Then you just loop over the enums invoking dosomestuff(whatIamLookingFor) and whatever happens happens.
Hard to say.
Yes, I agree, that it will be more elegant - at least for you. But think, what the next programmer will think about it. It will be even more complicated.
Previously mentioned strategy pattern and java's enum are definitely better solution, but since you are maintaining this code, I'm not sure if your boss will be happy with time consuming refactoring. My advice would be to use enums - not so big code change.

Categories

Resources