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.
Related
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.
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
Some utility classes (think java.lang.Math) declares only a private constructor in order to prevent instantiation of the class.
Is there any particular reason for why such classes are not implemented in terms of a 0-instance enum? It seems to me like enums is a more direct way of controlling instantiation than access modifiers on constructors. It also prevents the class itself from creating instances which both prevent the programmer from shooting himself in the foot and convey a guarantee outwards of no instances.
Joshua Bloch advocates the use of enums for singletons. Shouldn't the same benefits apply to 0-instance utility classes?
My question: What are the pros/cons of 0-instance enums vs private constructors. (I personally see no drawbacks of using an enum, though private constructors seems to be the more prevalent approach.)
(I know java.lang.Math predates enum. I'm talking 1.5+ code here.)
The fact that enums cannot be instantiated is a side-effect. When you declare something as an enum, people would expect it to be an enum; it will appear as enum in the IDE, code analysis tools, whatever.
Following the principle of least astonishment, and given that the user doesn't care of how you internally achieve that, I think it's better to use a private constructor, and also throw an Error from that constructor, provided someone tries to instantiate it with reflection.
So, to summarize the answers and comments so far:
Arguments supporting 0-instance enums:
Enum solves the problem of controlling instantiation of classes which is precisely what a 0-instance utility class needs.
Weekday has 7 instances, Month have 12, MySingleton has 1 (and should according to Joshua Bloch be implemented by means of an enum) and MyUtilityClass has 0 instances. There is no conceptual difference between the last case and the former ones.
A 0-instance enum guarantees that no instance will be created, not even from within the class itself.
Arguments against 0-instance enums:
Does not follow the principle of least astonishment; when people see an enum, they expect it to follow the text-book examples of non-empty enums such as weekdays, status codes etc.
The 0-instance enum is an idiom not widely used and thus not something other programmers recognize easily. I.e. it's less readable than using private constructors.
Enums are cluttered with implicit synthetic methods, which means that those names are not allowed for custom-defined methods. Furthermore, the fact that a public API exposes methods which should not be used can range from awkward to broken.
Other notes
Related question and answer.
Blog post on the subject by Peter Lawrey.
I don't know of any technical drawbacks with either approach.
As for elegance, that is a matter of opinion, and (IMO) not particularly relevant to the real purpose(s) of most computer programs.
By contrast, readability, maintainability and correctness are properties that are relevant to purpose. And one aspect that helps to make a program readable is the use of idioms that other programmers can readily recognize. Zero-instance enum types are an interesting idea ... but private constructors are the established idiom for preventing instantiation.
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)
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.
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 5 years ago.
Improve this question
First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me:
a: why it sucks
b: how language x has had that for years
c: how my mind sucks
d: all of the above
The idea would give composition the same ease of code reuse that extends does.
So if you had a class like this:
public interface A {
public void methodInA();
}
And then you had a class like this:
public class B {
private composed A;
public B() {
// construct A within constructor
}
}
You would then be able to do this:
B myB = new B();
myB.methodInA();
Without having to add in the delegation in B's class. But you could also do the same as with inheritance, ie:
#Overrides
public void methodInA(){
// B's own delegation method
}
Disadvantages include:
methods are hidden in the source code, making it less obvious where the call is coming from, but this is also the case with extends
if composed fields share the same method signature there needs to be a conflict resolved (how do conflicting interfaces solve this?)
if you wanted to have several composed fields of the same type, there would be an obvious conflict for which field to delegate to
probably 100 other things I've not thought of
Like I say, I'm obviously no language theorist, and I haven't spent ages thinking about it, the idea just popped in my head and I wanted to know how wrong I am. I just think it would be kind of cool.
It sounds cool but I think it makes for some horrible language constructs. Obviously there is a problem if you declare more than one 'composition' of the same class, but even if you forbid that what about the case where a call matches a method in more than one of the (different) composed classes? You would have to specify which one was called in the main class, and you would need extra syntax for that. The situation becomes even worse if there are public members in the classes.
Composition is used to prevent problems with multiple inheritance. Allowing composition like this is effectively permitting multiple inheritance, at least in terms of resolving which method to call. Since a key design decision with Java was to disallow multiple inheritance (for good reasons) I think it unlikely that this would ever be introduced to Java.
I think if you restricted it such that a class could only use this feature to compose a single class it would be somewhat useful and would avoid a lot of the headaches that are being discussed.
Personally I hate inheritance of concrete classes. I'm a big proponent of Item 14 from Bloch's Effective Java, Favor composition over inheritence. I think that something like this would make it a little easier to implement the idiom he recommends in that item.
Honestly, if you really knew what you were doing I'll bet you could write a compiler annotation that would handle this. So assuming you had a class Bar that implemented the interface IBar, your class would look like this:
public class Foo {
#Delegate(IBar.class)
private Bar bar;
// initialize bar via constructor or setter
}
Then during compilation Foo could be made to implement IBar and any of the methods on that interface that weren't already implemented by Foo would end up being generated to look like this:
public Baz method1(Qux val) {
return bar.method1(val);
}
As mentioned above you would want to make the restriction that only one field per class could use this annotation. If multiple fields had this annotation you'd probably want to throw a compilation error. Alternatively you could figure out a way to encode some sort of precedence model into the parameters passed to it.
Now that I've written this out that seems kinda cool. Maybe I'll play around with it next week. I'll update this if I manage to figure anything out.
I'm not sure that I see a clear advantage to doing this though. I understand the point you are making. At the moment to call a method on A you have to myB.getAInstance().methodInA(), but you want to make that myB.methodInA().
But, what happens if you have multiple instances of A? How would the method call be resolved? Many times composition implies a one to many association so B has many A instances. What happens then?
I agree with your disadvantages listed. It may simply cause too much confusion than it is worth.
Check out what is called "Mixins" in some languages, and "Roles" in the Perl 5 Moose OO system.
There's also the difference between composition and aggregation to consider. How does the compiler know whether you mean 'is-a' or 'has-a' relationships?
Does the whole object graph become eligible for garbage collection or only the head of the graph?
A couple of the ORM mapping tools and frameworks over/around them provide for belongsTo or has-many relationships between persistent objects and some also provide for the cascading delete (for composition). I don't know of one off hand that provides the simple syntactic sugar you're looking for.
Actually, on second thought, Groovy's MetaClass and MetaProgramming idiom(s) may provide something very similar, with 'auto-magic' delegation.
Multiple inheritance is allowed in C++, I know that different but it is along the same thought process. Java was designed to not allow multiple inheritance so that there would be less confusion, therefore bugs and exploits.
What you have suggested is in direct conflict with the principles of java.
Having said that, it would be cool (not necessarily useful). I'm a java programmer who switched from C++. I like being able to make my own mistakes.