Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
There seems to be two accepted variable declaration placements for Java variables, each with different raison d'être.
From the Sun's code conventions we can see:
Put declarations only at the beginning of blocks. (A block is any
code surrounded by curly braces "{" and "}".) Don't wait to declare
variables until their first use; it can confuse the unwary programmer
and hamper code portability within the scope.
However in the highly praised "Code Complete" and some other authors advocate for reducing the scope of a variable to a minimum. That is basically waiting to declare variables until their first use.
These two approaches are clearly contradictory although I can see the point for both of them.
Which should I follow? Is there any consensus on the matter?
Variables should be declared as close to their use as possible, for two reasons:
Vertical locality
Tool hinting
Vertical locality makes it easier to reason about chunks of code. The less scanning a reader has to do the easier it is to understand what code does, and what side-effects it
Reducing variable scope also allows better tool hinting for automated tools, like refactoring. The closer together related things are the more obvious they are.
That said: if a method is long enough that the above points come in to play, it's likely the method is already too long, and should be refactored anyway.
That is basically waiting to declare variables until their first use.
This is actually not true, and these two styes are not conflicting. Limiting the scope of the variable means that that variable, in fact, does not exist outside of that scope. E.g.
for(int i=0; i<10;i++){
int a = 5;
doSomething(a);
}
In this case, a is scope limited to the for block and this is what Code complete is referencing.
In any case I agree with sun, that variables within a scope (class, method, if block, etc.) should be declared at the beginning.
My personal opinion is that either way is fine. I think as long as the variable names are descriptive enough, it doesn't really matter. Again, this is only my opinion. I've had to go through lots of code which wasn't written by me, and the biggest frustration with variables I've faced, is that their names are not very descriptive. Most IDEs will have the option of 'go to definition' so it doesn't really matter where you declare them.
Those two statements do not need to be contradictory. Scope is decided by the curly brackets, so if you start a new set of brackets closer to where you use them, that is consistent with the Sun coding convention. Of course if you are just arbitrarily inserting scope limitations, that is a problem for reading the flow of the code.
However, I find it very important to declare fields at the top of the class, especially mutable fields. Understanding the state of an object can be the hardest part of a class over the long term, and putting the declarations at the beginning of the class clearly states what significant state the class holds.
I also recommend "Effective Java" by Joshua Bloch for more reasons why one should declare variables where they are first used.
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should one use final?
I tend to declare all variables final unless necessary. I consider this to be a good practice because it allows the compiler to check that the identifier is used as I expect (e.g. it is not mutated). On the other hand it clutters up the code, and perhaps this is not "the Java way".
I am wondering if there is a generally accepted best practice regarding the non-required use of final variables, and if there are other tradeoffs or aspects to this discussion that should be made aware of.
The "Java way" is inherently, intrinsically cluttery.
I say it's a good practice, but not one I follow.
Tests generally ensure I'm doing what I intend, and it's too cluttery for my aesthetics.
Some projects routinely apply final to all effectively final local variables. I personally find reading such code much easier, due to the lessened cognitive load. A non-final variable could be reassigned anywhere, and it's especially problematic in code with multiple levels of nested ifs and fors. You never know what code path may have reassigned it.
As for the concern of code clutter, when applied to local variables I don't find it damaging—in fact it makes me spot all declarations more easily due to syntax coloring.
Unfortunately, when final is used on parameters, catch blocks, enhanced-for loops and all other places except local variables in the narrow sense, the code does tend to become cluttered. This is quite unfortunate because a reassignment in these cases is even more confusing and they should really have been final by default.
There are code linting tools that will flag the reassignment of these variables, and that helps.
I consider it good practice, more for maintenance programmers (including me!) than for the compiler. It's easier to think about a method if I don't need to worry about which variables might be changing inside it.
Yes, it's a very good idea, because it clearly shows what fields must be provided at object construction.
I strongly disagree that it creates "code clutter"; it's a good and powerful aspect of the language.
As a design principle, you should make your classes immutable (all final fields) if you can, because they may be safely published (ie freely passed around without fear they will be corrupted). Although note that the fields themselves need to be immutable objects too.
It definitely gives you a better code, easy to see which all variables are going to be changed.
It also informs the compiler that it is not going to change which can result to better optimization.
Along side it allows your IDE to give you compile time notification if you tend to do any mistake.
Some good analysis tools, like PMD, advices to put always final unless necessary. So the convention in that tools says it's a good practice
But I think that so many final tokens in code may get it less human-friendly.
I would say yes, not so much for the compiler optimisation, but rather for readibility.
But personally I don't use it. Java is quite verbose by itself, and if we followed everything considered "good practice", the code would be unredable from all the boilerplate. It's a matter of preference, though.
You pretty much summed up the pros and cons...
I can just add another con:
the reader of the code need not to reason at all about the value of a final variable (except for rare bad-code cases).
So, yes, it's a good practice.
And the clutter isn't that bad, after you get used to it (like unix :-P). Plus, typical IDEs do it automatically for ya...
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 7 years ago.
Improve this question
There is an explanatory code of what I'm trying to ask. Sureley, the difference between the codes below is ignorable, yet it describes the point.
Which one is the most efficient in terms of memory usage and performance?
if( MathUtil.CalculateSin(angle) > Angles.ACUTE){
// Something is done
}
or
double angleSin = MathUtil.CalculateSin(angle);
if( angleSin > Angles.ACUTE){
// Something is done
}
It simply depends if you are going to re-use the variable.
If yes, use the second case.
If no use the first case.
There is no reason to store the value in a variable if you are not going to re-use it.
Edit :
As per your comment, it seems you are mostly asking this question for performance concern...
Actually my question is not about the algorithm nor the way I
implement it. I'm curious about the memory usage of the approaches,
therefore efficiency is the purpose.
Don't expect any difference in term of memory usage for both approaches, the JVM and JIT will optimize it as much as possible so that both case become the same.
To extend the other answers, you should also consider readability of your code. In this case, the meaning of MathUtil.CalculateSin(angle) is pretty obvious. However, if you have a more complex condition, it would be a good idea to precompute that condition, give the variable a meaningful name and then use the variable in the if-statement.
In your case it also depends on the context of the if-statement. Again, MathUtil.CalculateSin(angle) > Angles.ACUTE is quite easy to grasp at a glance. However,
final boolean angleIsAcute = (MathUtil.CalculateSin(angle) > Angles.ACUTE);
if(angleIsAcute) { ... }
would carry the meaning better. In this case, of course, both possibilities are quite similar, but I hope you see where I am going with this.
Do not worry about the overhead that is introduced by storing that extra variable. Even though the java-compiler does not optimize your code, any JVM worth its salt will optimize the bytecode and the performance overhead will be negligible.
I often use the first pattern even when I won't need the variable later in the code. The advantage is for debugging.
You can examine and change the value of the variable when stepping through the code in a debugger.
If an exception occurs in the call on the right-hand side of the statement, it is sometimes clearer what happened than if the call is embedded in an if or as an argument to another call.
If you're concerned about memory usage for the variable, don't be. Trust the compiler to optimize away variables that it knows aren't going to be used later. If you declare the variable final, it will be optimized aggressively as described in the JLS.
References do take memory. So if you are not going to use angleSin anywhere else then second option is what you should go for. Besides it does not pollute the namespace. That is one reason people make Comparator as an anonymous class instead of creating a new one. If they do not need to use somewhere else.
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
My computer science course wants me to start descriptively commenting out my code so that the teacher and other students can better understand it while reading it. Being 50% lazy and 50% elitist, I don't want to have to comment out every line just so that people can understand my code. I don't want to comment out every method unless that is really necessary either (the teacher only requires what is necessary for him to understand going on without having to try to interpret individual lines of code). What is accepted in the computer science universe as "enough commenting?"
Generally accepted guidelines for commenting are:
Non-trivial classes should have JavaDoc describing their usage / purpose. Documenting an object's thread safety is also frequently useful.
Non-trivial / non-obvious methods based on the method name should have JavaDoc. Ideally any requirements on the parameters should be noted (behaviour in regards to nulls etc), as well as any modifications to passed in Objects. Good rule of thumb is to answer:
What does this method require
What does it produce / guarantee (and when does it throw an exception)
What (if anything) does it modify
Any complicated or non-obvious lines of code should be commented
Where did this magic constant come from
Why is this being done (if not obvious)
Class variables can be commented when necessary. This is less standard, but it is sometimes useful to comment variables to indicate what it is to be used for.
Avoid comments that merely repeat what the code is doing. E.g.
// Set x to 4 before the loop
x = 4;
for (int i = 0; i < x; i++)
But, if appropriate, comment why it is being done:
// Set x to 4 since we are guaranteed to only have 4 threads
x = 4;
for ...
At a minimum, you should have good method comments (consider this the most important), and rough overview comments for your classes. I would consider anything less than this to be unprofessional and a reason for rejecting a code review.
In Java comments are used to generate a javadoc from the source code you have written. Format your comments according javadoc spec. That's enough for commenting in Java, other comments are optional and how someone mentioned comments are versus commented out code. If you keep such code in files you'd better leave a reasonable comment (i.e. referencing some issue, etc.). Note that using Java naming conventions and properly named Java elements greatly reduce needs for commenting inside the code. These comments are only intended for uses who will proof read or debug your code are optional as I mentioned above. Other optional comments are project related and tagged for example todo. You should concentrate more attention on javadoc comments, as general rule are placed on all public methods and classes including interfaces. if your class implements some interface method then you should not duplicate comment there, just reference a corresponding interface method comment.
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
Sorry for posting a rather vague question here - but I've been struggling to find a definitive answer to this one - maybe there is none, but just thought asking fellow developers.
Last week, a colleague of mine mentioned that the length of constructors (In Java and in OOP in general) should be kept to a minimum. While I do agree the approach in general, he went on to say that it should be only a few lines - 3-4 lines at maximum.
I'm not sure how he arrived at this number and I wonder how useful that approach is. If you have some complex initialisation to perform, your constructors will exceed that limit.
You can split and break and refactor your code into smaller functions till cows come home, I prefer to keep related code into one method and avoid un-necessary functions as it makes code more readable.
This at times does lead to situations where constructors are fairly moderate in size - 50-100 lines of code in worst scenarios, but then even if I break it up into functions, technically speaking, that code is still "called as part of initialisation". So, 100 lines of code might be replaced by a single function call, but that 100 lines still get called when you call the function?
I also looked at checks type default definitions and it has default constructor length set to 150, which sounds more reasonable "Than a few lines code".
Would love to know what you guys follow as rule of thumb or if there is, indeed, such a accepted upon limit.
Good rule of thumb is that any method (or constructor) should fit on one screen in your IDE so you don't have to scroll down when you are trying to read and understand what is this method doing (so it improves readability).
Nothing prevents you from making exception from time to time but you should generally split really long methods to smaller chunks because I've really seen methods few hundred lines long and it really made me cry when I had to change the code.
This is just a common practice but not anything. I have made classes that had a lot of code in constructors. I also had classes with no constructor. As mentioned above, there is no such thing that you should not contain a lot of code in constructors, and JVM loads them too.
So why this concept came up? It is because people think that constructors are for initializing variables in objects since they are called only when new instances are created. Also doing a lot of work in the constructors makes no point in using OOP principles. OOP itself means 'Object Oriented Programming' which is meant to structure code as objects. So I'm leaving the conclusion to you. See the both examples and think which one is better.
Example 1:
public Dog(String name)
{
System.out.println("Dog " + name + ": Bark!Bark!");
}
Example 2:
public Dog(String name)
{
this.name = name;
}
public void bark()
{
System.out.println("Dog " + name + ": Bark!Bark!");
}
In the first example, the dog barks only once, but in the second example, you can make the dog bark as many times as you want. And for this same reason, they say to use constructors only for initializing values.
Hope this helps.
I've been struggling to find a definitive answer to this one - maybe there is none
You are right. There isn't a definitive answer. It is subjective.
Would love to know what you guys follow as rule of thumb ...
I don't. I use my judgement on a case-by-case basis. Subjectively.
... or if there is, indeed, such a accepted upon limit.
There isn't. You won't find any specified limits in the main-stream Java coding standards. A decent coding standard won't be prescriptive about this because it is counter-productive.
On the other hand, this is the kind of situation where code reviews can be beneficial. If you see an "overly long" constructor or method, it is worth pointing out, especially if there is a good refactoring available; i.e. one that your colleagues would agree improves readability.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
In Java, you can qualify local variables and method parameters with the final keyword.
public static void foo(final int x) {
final String qwerty = "bar";
}
Doing so results in not being able to reassign x and qwerty in the body of the method.
This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?
You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler that can lead to better optimization of the class file. This is one of the points in the book, "Hardcore Java" by Robert Simmons, Jr. In fact, the book spends all of its second chapter on the use of final to promote optimizations and prevent logic errors. Static analysis tools such as PMD and the built-in SA of Eclipse flag these sorts of cases for this reason.
My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.
I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.
But, of course, it's all personal preference ;-)
Making a parameter final guarantees that the value used at any location in the method refers to the value passed. Otherwise you have to parse mentally all the code above a given location to know what value the parameter has at that point.
Hence, not using final makes your code less readable, and maintainable, all by itself :)
Final local variables depend on intent, and is less important in my point of view. Depends on what goes on.
In the case of local variables, I tend to avoid this. It causes visual clutter, and is generally unnecessary - a function should be short enough or focus on a single impact to let you quickly see that you are modify something that shouldn't be.
In the case of magic numbers, I would put them as a constant private field anyway rather than in the code.
I only use final in situations where it is necessary (e.g., passing values to anonymous classes).
Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.
Finalizing local var's seems somewhat overkill IMO.
Yes do it.
It's about readability. It's easier to reason about the possible states of the program when you know that variables are assigned once and only once.
A decent alternative is to turn on the IDE warning when a parameter is assigned, or when a variable (other than a loop variable) is assigned more than once.
final has three good reasons:
instance variables set by constructor only become immutable
methods not to be overridden become final, use this with real reasons, not by default
local variables or parameters to be used in anonimous classes inside a method need to be final
Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.
Although it creates a little clutter, it is worth putting final. Ides e.g eclipse can automatically put the final if you configure it to do so.
Making local variables and method parameters final is essential if you want to pass those parameters into anonymous classes - like you instantiate an anonymous Thread and want to access those params in the body of the run() method.
Apart from that I am not sure of the performance benefits w.r.t better performance through compiler optimization. It is up to the specific compiler implementation whether it wants to optimize it at all...
It will be good to know of any performance stats from using final ...
Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.
The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.
Edit
In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.
I let Eclipse do it for me when they are being used in an anonymous class, which is increasing due to my use of Google Collection API.
We do it here for the local variables if we think they will not be reassigned or should not be reassigned.
The parameters are not final since we have a Checkstyle-Check which checks for reassigning parameters. Of course nobody would ever want to reassign a parameter variable.