Java Coding standard: variable declaration - java

Which of the following is best practice according to Java coding standards
public void function1(){
boolean valid = false;
//many lines of code
valid = validateInputs();
//many lines of code
}
or
public void function1(){
//many lines of code
boolean valid = validateInputs();
//many lines of code
}
Here 'valid' will not be for returning. Its scope is internal to the function only. Sometimes only in one if condition
I usually code similar to the second case. It seems my superior does not like this and modifies the code when I put it for review. Is there some specific reason that my approach is not correct?
The disadvantage I see for the first approach is that it is very difficult to refactor the method to multiple methods at a later point.

I would go for the second approach - not much a matter of Java coding standards here, but a matter of clean and readable code. Also, you assign the value false to valid in the first case, but that's not really correct as valid shouldn't have any value at that point.
On a side note, I won't expect a method called validateInputs() to return a boolean. There's no parameter passed, and the name is not giving an hint that the method would return something. What about refactoring your code to something like boolean validInput = isValid(input)?

I would prefer to only declare variables within the scope they are used. This avoid accidentally using it when you shouldn't and means you can see both the declaration and the usage together, instead of having to jump to the start of your code to find it.
In the C days, you had to use the first form, because the compilers were not very smart. But the second form was added as it made the code easier to understand AFAIK.

Whichever is better is a matter of personal taste. Every place has its own standards, so you should follow it at work.
That's one more reason I think every programmer should have their own personal projects. That way you can also code in your own style at home, so you don't get your mind stuck with just one style.

There should always be reasoning behind a decision.
The second example is better because it is good to initialize values in the declaration.
Google has a good set of standards that is applicable to many C-type languages. The example you are referring to is shown in the 'local variables' section.

Related

Is it safe to use Kotlin property access syntax to set a Java field

This is a hypothetical question.
The situation is the following:
I am calling a setter of a Java class from a Kotlin file to change the value of the private field x
javaFoo.setX(420)
The IDE suggests to change it to
javaFoo.x = 420
It works normally.
Now suppose the setter has some complicated functionality inside of it and later on the x field in the Java class is changed to public instead of private. There will be no compile error but the Kotlin call will change the value of x skipping the other stuff that happens in the setter, and it can go unnoticed causing logical errors. Therefore I am wondering: Is it safe to use Kotlin property access syntax to set a java field?
Your analysis of the language semantics is correct. The change on the target class you describe would indeed change the semantics of Kotlin's property access syntax. However, that fact is not the only one to consider when answering your question, which asks whether using that syntax is safe.
When discussing hypothetical scenarios without any real-life constraints, pretty much anything is possible and no language construct is "safe" under that view. What if, one day, the Kotlin team decided to change the semantics of x++ to mean "return x squared, not changing x"? Theoretically, that's possible. Is it likely, though?
Applying the same common-sense logic to your question, the scenario where the maintainer of a class decides to break the encapsulation of a field that has so far been hidden behind a setter with custom logic is extremely unlikely. In fact, if you make a historical analysis of all the Java library projects, you probably won't find a single instance of this having ever happened.
That said, your hypothetical scenario could be seen as a distraction from an actual problem with the shortcut syntax. It can be awkward and misleading to use it to call a setter with custom logic because it breaks our intuition.
On Android, one such example is ImageView.get/setImageMatrix. You can write
imageMatrix.rotate = 30
and expect that to have an effect, but actually, the code you wrote is broken. You should actually have written
val tmpMatrix = Matrix()
tmpMatrix.set(imageMatrix)
tmpMatrix.rotate = 30
imageMatrix = tmpMatrix
By our Java intuition, it is actually this version that looks broken, wasting an object allocation for seemingly no purpose. But if you read the contract of setImageMatrix, you'll realize it does quite a bit more than just assign your object to a field, it actually applies the transformation to the image view. Similarly, the contract of the getter disallows mutating the returned object.
I haven't seen much argument over this feature of Kotlin, but I see it as a potential source of bugs for folks migrating from Java. The way to go is to re-train your intuition, sensitizing yourself to the fact that any property access in Kotlin may mean a lot more than meets the eye.

Is it bad practice to embed method parameter expressions?

Is it generally considered bad practice to structure code with embedded expressions in method parameters? Should variables be declared instead?
(Android code snippet for an example)
((EditText)view.findViewById(R.id.fooEditText))
.setText(
someExpression
? getResources().getString(R.string.true_expression_text)
: getResources().getString(R.string.false_expression_text)
);
Personally I think it looks fine, but am just wondering if this is considered repulsing :)
I would almost certainly simplify that, in a number of ways:
EditText editText = (EditText) view.findViewById(R.id.fooEditText);
String resourceName = someExpression ? R.string.true_expression_text
: R.string.false_expression_text;
editText.setText(getResources().getString(resourceName));
Doing it all in one statement makes it harder to read and harder to debug, IMO. Note that I've also removed duplication here, but using the fact that you were calling getResources().getString(...) in both operands of the conditional operator, just with different resource names.
My main beef with the original code is calling a method on the result of a cast - aside from anything else, it introduces more brackets than you need, which is generally confusing.
I'd say this depends on the situation, for instance.
player.setName(User.getName());
Would be fine, however, train wrecking such as below...
player.setName(getGroup().getUsers().get(0).getName());
I'd say is bad practice and is mentioned in Clean Code by Bob Martin regarding the dangers of train wrecks. Also duplicate calls as mentioned by #Jon Skeet is another reason to use a variable rather than a method call.
The word "repulsing" was yours, but it certainly describes my reaction. I can't focus on what this statement is doing because it has an if statement, a search, and at least 5 dereferences happening before it gets started.
I find the trinary operator particularly pernicious, since I have to hold two disjoint sets of state in my mind while I parse everything else. Some folks prefer brevity to local variables (I'm not one of them) but trinary operators (or any other branch) embedded in other statements are especially unloveable. If you ignore the rest of Clean Code or similar works because you enjoy complex statements, at least separate the conditionals out.

Java performance vs. code-style: Making multiple method calls from the same line of code

I am curious whether packing multiple and/or nested method calls within the same line of code is better for performance and that is why some developers do it, at the cost of making their code less readable.
E.g.
//like
Set<String> jobParamKeySet = jobParams.keySet();
Iterator<String> jobParamItrtr = jobParamKeySet.iterator();
Could be also written as
//dislike
Iterator<String> jobParamItrtr = jobParams.keySet().iterator();
Personally, I hate the latter because it does multiple evaluations in the same line and is hard for me to read the code. That is why I try to avoid by all means to have more than one evaluation per line of code. I also don't know that jobParams.keySet() returns a Set and that bugs me.
Another example would be:
//dislike
Bar.processParameter(Foo.getParameter());
vs
//like
Parameter param = Foo.getParameter();
Bar.processParameter(param);
The former makes me noxious and dizzy as I like to consume simple and clean evaluations in every line of code and I just hate it when I see other people's code written like that.
But are there any (performance) benefits to packing multiple method calls in the same line?
EDIT: Single liners are also more difficult to debug, thanks to #stemm for reminding
Micro optimization is killer. If the code references you are showing are either instance scope (or) method scope, I would go with second approach.
Method scope variables will be eligible for GC as soon as method execution done, so even you declare another variable, it's ok because scope is limited and the advantage you get will be readable and main-table code.
I tend to disagree with most others on this list. I actually find the first way cleaner and easier to read.
In your example:
//like
Set<String> jobParamKeySet = jobParams.keySet();
Iterator<String> jobParamItrtr = jobParamKeySet.iterator();
Could be also written as
//dislike
Iterator<String> jobParamItrtr = jobParams.keySet().iterator();
the first method (the one you like) has a lot of irrelevant information. The whole point of the iterator interface, for example, is to give you a standard interface that you can use to loop over whatever backing implementation there is. So the fact that it is a keyset has no bearing on the code itself. All you are looking for is the iterator to loop over the implemented object.
Secondly, the second implementation actually gives you more information. It tells you that the code will be ignoring the implementation of jobParams and that it will only be looping through the keys. In the first code, you must first trace back what jobParamKeySet is (as a variable) to figure out what you are iterating over. Additionally, you do not know if/where jobParamKeySet is used elsewhere in the scope.
Finally, as a last comment, the second way makes it easier to switch implementations if necessary; in the first case, you might need to recode two lines (the first variable assignment if it changes from a set to something else), whereas the second case you only need to change out one line.
That being said, there are limits to everything. Chaining 10 calls within a single line can be complicated to read and debug. However 3 or 4 levels is usually clear. Sometimes, especially if an intermediary variable is required several times, it makes more sense to declare it explicitly.
In your second example:
//dislike
Bar.processParameter(Foo.getParameter());
vs
//like
Parameter param = Foo.getParameter();
Bar.processParameter(param);
I find it actually more difficult to understand exactly which parameters are being processed by Bar.processParameter(param). It will take me longer to match param to the variable instantiation to see that it is Foo.getParameter(). Whereas the first case, the information is very clear and presented very well - you are processing Foo.getParameter() params. Personally, I find the first method is less prone to error as well - it is unlikely that you accidentally use Foo2.getParamter() when it is within the same call as opposed to a separate line.
There is one less variable assignment, but even the compiler can optimize it in some cases.
I would not do it for performance, it is kind of an early optimization. Write the code that is easier to maintain.
In my case, I find:
Iterator<String> jobParamItrtr = jobParams.keySet().iterator();
easier to be read than:
Set<String> jobParamKeySet = jobParams.keySet();
Iterator<String> jobParamItrtr = jobParamKeySet.iterator();
But I guess it is a matter of personal taste.
Code is never developed by same user. I would choose second way. Also it is easier to understand and maintain.
Also This is beneficial when two different teams are working on the code at different locations.
Many times we take an hour or more time to understand what other developer has done, if he uses first option. Personally I had this situation many times.
But are there any (performance) benefits to packing multiple method calls in the same line?
I seriously doubt the difference is measurable but even if there were I would consider
is hard for me to read the code.
to be so much more important it cannot be over stated.
Even if the it were half the speed, I would still write the simplest, cleanest and easiest to understand code and only when you have profiled the application and identified that you have an issue would I consider optimising it.
BTW: I prefer the more dense, chained code, but I would suggest you use what you prefer.
The omission of an extra local variable probably has a neglible performance advantage (although the JIT may be able to optimize this).
Personally I don't mind call chaining when its pretty clear whats done and the intermediate object is very unlikely to be null (like your first 'dislike'-example). When it gets complex (multiple .'s in the expression), I prefer explicit local variables, because its so much simpler to debug.
So I decide case by case what I prefer :)
I don't see where a().b().c().d is that much harder to read than a.b.c.d which people don't seem to mind too much. (Though I would break it up.)
If you don't like that it's all on one line, you could say
a()
.b()
.c()
.d
(I don't like that either.)
I prefer to break it up, using a couple extra variables.
It makes it easier to debug.
If performance is your concern (as it should be), the first thing to understand is not to sweat the small stuff.
If adding extra local variables costs anything at all, the rest of the code has to be rippin' fat-free before it even begins to matter.

What is the preferred way to write boolean expressions in Java

I have always written my boolean expressions like this:
if (!isValid) {
// code
}
But my new employer insists on the following style:
if (false == isValid) {
// code
}
Is one style preferred, or standard?
I prefer the first style because it is more natural for me to read. It's very unusual to see the second style.
One reason why some people might prefer the second over another alternative:
if (isValid == false) { ... }
is that with the latter you accidentally write a single = instead of == then you are assigning to isValid instead of testing it but with the constant first you will get a compile error.
But with your first suggestion this issue isn't even a problem, so this is another reason to prefer the first.
Absolutely the first. The second betrays a lack of understanding of the nature of expressions and values, and as part of the coding standard, it implies that the employer expects to hire very incompetent programmers - not a good omen.
Everybody recognizes this snippet:
if (isValid.toString().lenght() > 4) {
//code
}
I think your second example looks at the same direction.
It was discussed for C# several hours ago.
The false == isValid construct is a leftover from C-world, where compiler would allow you to do assignments in if statement. I believe Java compilers will warn you in such case.
Overall, second option is too verbose.
IMO the first one is much more readable while the second one more verbose.
I would surely go for the 1st one
You are evaluating the variable, not false so the latter is not correct from a readability perspective. So I would personally stick with the first option.
I'm going to attempt a comprehensive answer here that incorporates all the above answers.
The first style is definitely to be preferred for the following reasons:
it's shorter
it is more readable, and hence easier to understand
it is more widely used, which means that readers will recognize the pattern more quickly
"false==..." rather than "...==false" is yet another violation of natural order,which makes the reader think "is there something strange going on that I need to pay attention to", when there isn't.
The only exception to this is when the variable is a Boolean rather than a boolean. In that case the second is a different expression from the first, evaluating to false when isValid is null as well as when it is Boolean.FALSE. If this is the case there are good arguments for using the second.
The second style doesn't require you to negate the expression yourself (which might be far more complicated than just "isValid"). But writing "isValid == false" may lead to an unintended assignment if you forget to type two ='s, hence the idiom is to put on the right side what can't be an rvalue.
The first style seems to be preferred among people who know what they're doing.
I just want to say I learned C twenty years ago in school and have moving onto Perl and Java and now C# which all have the same syntax and...
I think (!myvar) is the most popular
I think (myvar==false) is just fine too
in 20 years i have NEVER EVEN SEEN
(false==myvar)
I think your boss is smoking something-- I'm sorry but I'd take this as a sign your boss is some kind of control freak or numbskull.

Do you use Javadoc for every method you write? [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 4 years ago.
Improve this question
Should I be writing Doc Comments for all of my java methods?
#Claudiu
When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a javadoc at least stating its obvious purpose.
#Daniel Spiewak
I thoroughly document every public method in every API class. Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc. I also document every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.
Finally, I will occasionally document private and package private methods for my own benefit. Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.
#Paul de Vrieze
For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter
/**
* Get the current value of the foo property.
* The foo property controls the initial guess used by the bla algorithm in
* {#link #bla}
* #return The initial guess used by {#link #bla}
*/
int getFoo() {
return foo;
}
And yes, this is more work.
#VonC
When you break a huge complex method (because of high cyclomatic complexity reason) into:
one public method calling
several private methods which represent internal steps of the public one
, it is very useful to javadoc the private methods as well, even though that documentation will not be visible in the javadoc API files.
Still, it allows you to remember more easily the precise nature of the different steps of your complex algorithm.
And remember: limit values or boundary conditions should be part of your javadoc as well.
Plus, javadoc is way better than simple "//comment":
It is recognized by IDE and used to display a pop-up when you move your cursor on top of one of your - javadoc-ed - function. For instance, a constant - that is private static final variable -, should have a javadoc, especially when its value is not trivial. Case in point: regexp (its javadoc should includes the regexp in its non-escaped form, what is purpose is and a literal example matched by the regexp)
It can be parsed by external tools (like xdoclet)
#Domci
For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. [...]
In short, comment logic, not syntax, and do it only once, on a proper place.
#Miguel Ping
In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.
If the method is, obviously self evident, I might skip a javadoc comment.
Comments like
/** Does Foo */
void doFoo();
Really aren't that useful. (Overly simplistic example, but you get the idea)
I thoroughly document every public method in every API class. Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc. I also document every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.
Finally, I will occasionally document private and package private methods for my own benefit. Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.
All bases covered by others already; one additional note:
If you find yourself doing this:
/**
* This method currently launches the blaardh into the bleeyrg.
*/
void execute() { ... }
Consider changing it into this:
void launchBlaardhIntoBleeyrg() { ... }
This may seem a bit obvious, but in many cases the opportunity is easy to miss in your own code.
Finally keep in mind that the change is not always wanted; for instance the behaviour of the method may be expected to evolve over time (note the word "currently" in the JavaDoc).
For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter.
/**
* Get foo
* #return The value of the foo property
*/
int getFoo() {
return foo;
}
Is not useful. Better do something like:
/**
* Get the current value of the foo property.
* The foo property controls the initial guess used by the bla algorithm in
* {#link #bla}
* #return The initial guess used by {#link #bla}
*/
int getFoo() {
return foo;
}
And yes, this is more work.
No, do not comment every method, variable, class, etc..
Here's a quote from "Clean Code: A Handbook of Agile Software Craftsmanship":
It is just plain silly to have a rule that says that every function must have a
javadoc, or every variable must have a comment. Comments like this just clutter
up the code, popagate lies, and lend to general confusion and disorganization.
A comment should exist if, and only if, it adds important information for the intended user of the method, variable, class, etc.. What constitutes "important" is worth consideration and could be a reminder to myself when/if I come back to this method/class/etc., a consequence/side effect of the method, motivation for why the thing even exists (in the case where some code is overcoming a shortcoming/bug of some library or system), important information about the performance or when it is appropriate to call, etc..
What is not a good comment but indicates the code itself should be rewritten/modified is a comment explaining the details of a complex and obscure method or function. Instead, prefer shorter clearer code.
When I write code for myself - NO. In this case, java doccing is a waste of my time.
When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a java doc at least stating its obvious purpose. For a good test - run the javadoc creation utility on your code (I forget the exact command line now). Browse through the webpage it generates. If you would be satisfied using a library with that level of documentation, you're golden. If not, Write more javadocs in your code.
There is another reason you should use javadocs. In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.
simply put: YES
The time you need to think about whether you should write a doc,
is better invested in writing a doc.
Writing a one-liner is better than spending time for not documenting the method at all in the end.
For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. There are a few guidelines:
APIs, framework classes, and internal reusable static methods should be commented thoroughly.
Logic in every complicated piece of code should be explained on two places - general logic in javadoc, and logic for each meaningful part of code in it's own comment.
Model properties should be commented if they're not obvious. For example, no point in commenting username and password, but type should at least have a comment which says what are possible values for type.
I don't document getters, setters, or anything done "by the book". If the team has a standard way of creating forms, adapters, controllers, facades... I don't document them, since there's no point if all adapters are the same and have a set of standard methods. Anyone familiar with framework will know what they're for - assuming that the framework philosophy and way of working with it is documented somewhere. In this cases, comments mean additional clutter and have no purpose. There are exceptions to this when class does something non-standard - then short comment is useful. Also, even if I'm creating form in a standard way, I like to divide parts of the form with short comments which divide the code into several parts, for example "billing address starts here".
In short, comment logic, not syntax, and do it only once, on a proper place.
Java doc should not be relied on, as it places a burden on developers making changes to maintain the java doc as well as the code.
Class names and function names should be explicit enough to explain what is going on.
If to explain what a class or method does makes its name too long to deal with, the class or method is not focused enough, and should be refactored into smaller units.
I feel there should at least be comments regarding the parameters accepted and return types in term of what they are.
One can skip the implementation details in case the function names describes it completely, for eg, sendEmail(..);
I make it a point to write javadoc comments whenever it is non-trivial, Writing javadoc comments when using an IDE like eclipse or netbeans isn't that troublesome. Besides, when you write a javadoc comment, you are being forced to think about not just what the method does, but what the method does exactly, and the assumptions you've made.
Another reason is that once you've understood your code and refactored it, the javadoc allows you to forget about what it does since you can always refer to it. I'm not advocating purposely forgetting what your methods do but it's just that I prefer to remember other things which are more important.
You should probably be documenting all of your methods really. Most important are public API methods (especially published API methods). Private methods are sometimes not documented, although I think they should be, just for clarity - same goes with protected methods. Your comments should be informative, and not just reiterate what the code does.
If a method is particularly complex, it is advised that you document it. Some people believe that code should be written clearly so that it doesn't require comments. However, this is not always possible, so comments should be used in these cases.
You can automate the generation of Javadoc comments for getters/setters from Eclipse via the code templates to save on the amount of documentation you have to write. another tip is to use the #{$inheritDoc} to prevent duplication of code comments between interfaces and implementation classes.
Javadoc can be really useful for libraries and reusable components. But let's be more practical. It is more important to have self explaining code than javadoc.
If you imagine a huge legacy project with Javadocs - would you rely on that? I do not think so... Someone has added Javadoc, then the implementation has changed, new feature was added (removed), so the Javadoc got obsolete.
As I mentioned I like to have javadocs for libraries, but for active projects I would prefer
small functions/classes with names which describe what they do
clear unit test cases which give explanation what the
function/classes do
at a previous company, we used to use the jalopy code formatter with eclipse. That would add javadoc to all the methods including private.
It made life difficult to document setters and getters. But what the heck. You have to do it -- you do it. That made me learn some macro functionality with XEmacs :-) You can automate it even further by writing a java parser and commenter like ANTLR creator did several years ago :-)
currently, I document all public methods and anything more than 10 lines.
You can run javadoc against code that does not have javadoc comments and it will produce fairly useable javadocs if you give thoughtful names to your methods and parameters.
I try to at the very least document every public and interface property and method, so that people calling into my code know what things are. I also try to comment as much as possible in line as well for maintenance sake. Even 'personal' projects I do on my own time just for myself, I try to javadoc just because I might shelf it for a year and come back to it later.
Assumed in all the answers so far is that the comments will be good comments. As we all know that is not always the case, sometimes they are even incorrect. If you have to read the code to determine its intent, boundaries, and expected error behavior then the comment is lacking. For example, is the method thread safe, can any arg be null, can it return null, etc. Comments should be part of any code reviews.
This may be even more important for private methods since a maintainer of the code base will have to contend with issues that an API user will not.
Perhaps IDEs should have a feature that allows the use of a documenting form so that the developer can check off various properties that are important and applicable for the current method.

Categories