Is it bad practice to embed method parameter expressions? - java

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.

Related

Java Coding standard: variable declaration

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.

Java syntax - what does this code mean?

I am starting to learn Android programming with Java, mainly from online Android documentation. I also looked through several books but they don't seem to address this issue: a feature of Java syntax which I have come across several times and which is a mystery to me. Here is just one example from about half-way through the Contacts Provider documentation at
http://developer.android.com/guide/topics/providers/contacts-provider.html
I have removed the comments to unclutter the code snippet:
op =
ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType);
This is all one statement, I think. What is confusing me is all those "dot operators" that look as though they belong in a Visual Basic "with clause". Where can I find out what all this means?
youre looking at a builder pattern, where the return value of each such with* method is the builder itself (or the object, if its not a builder exactly). theyre handly when you want to chain a lot of setters, or when there are a lot of constructors for the underlying object and you dont want people using it to get confused. or, as fge stated below, when you want the returned object to be immutable (so it cant have setters).
more specifically to your case, the return value of ContentProviderOperation.newInsert() is a ContentProviderOperation.Builder, all of who's methods return itself. usually such a chain of configuration calls will end in a call to build(), which will produce an operation.
This is an instance of so called fluent interfaces (link to wikipedia). There is noting special about it: the value returned from the previous call is being used as the target of the subsequent call.
API like this present a useful alternative to methods with lots of optional parameters, because the resulting code is much easier to read and understand. The code is somewhat more verbose, but in this case it is a good thing, because the parameters passed to constructors get better "tagging". This style is also preferable when you have multiple parameters of the same type (say, strings) next to each other, because it lets the readers avoid parameter counting.
each of those methods returns an ContentProviderOperation.Builder object that has been modified by the method. So you can chain together calls to methods like that and do everything in a more compact way. It's similar to how jQuery works in the javascript world.
It may clear things up a bit to look at the newInsert method on the Android documentation, then look at the documentation for the ContentProviderOperation.Builder class. note that all of the methods on that object also return ContentProviderOperation.Builder objects.

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.

How can I write code without "needing" comments for readability? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Is it possible to write good and understandable code without any comments?
When coding often I hear that if comments are needed then it means that the code is too hard to understand. I agree that code should be readable but often the language itself makes the code hard to follow, because of "plumbing" and strange syntax. The languages I use most often are:
Java
Mootools
Ruby
Erlang
Any tips would be appreciated?
Thanks
Recommended reading: Clean Code by Robert C. Martin.
In brief, you should
use meaningful variable/method/class names,
keep your functions/methods short,
have each class and method do only one thing,
have the code in each method be on the same level of abstraction.
Don't fear of extracting even moderately complex expressions from if statements; which one is clearer to read, this
if (i >= 0 && (v.size() < u || d == e)) ...
or
if (foundNewLocalMaximum()) ...
(Don't try to find any meaning in the first code snippet, I just made it up :-)
Comments in clean code are almost never needed. The only exceptions I can think of is if you are using some obscure language feature (e.g. C++ template metaprogramming) or algorithm, and you give a reference to the source of the method/algorithm and its implementation details in a comment.
The main reason why any other kind of comments is not very useful in the long run is that code changes, and comments tend to not be updated alongside the changes in the corresponding code. So after a while the comment is not simply useless, but it is misleading: it tells you something (implementation notes, reasoning about design choices, bug fixes etc.) which refers to a version of the code which is long gone, and you have no idea whether it is relevant anymore for the current version of the code.
Another reason why I think that "why I chose this solution" is most often not worth documenting in the code, is that the brief version of such a comment would almost always be like either "because I think this is the best way", or a reference to e.g. "The C++ Programming Language, ch. 5.2.1", and the long version would be a three-page essay. I think that an experienced programmer most often sees and understands why the code is written like this without much explanation, and a beginner may not understand even the explanation itself - it's not worth trying to cover everyone.
Last but not least, IMO unit tests are almost always a better way of documentation than code comments: your unit tests do document your understanding, assumptions and reasoning about the code quite efficiently, moreover you are automatically reminded to keep them in sync with the code whenever you break them (well, provided you actually run them with your build...).
I don't think you can normally write code without comments.
Briefly, the code documents how. The comments document why.
I would expect the comments to indicate the conditions why the code has been written like that, limitations imposed by requirements or externalities, the impact that would result from changing the code, and other gotchas. The comments contain information that isn't contained within the code itself.
Comments along the code are supposed to tell you why you initially did something a certain way. It shouldn't mean the code is too hard to understand.
The most important things to follow are:
give your variables, methods, classes... meaningful names
write classes/ modules with a clean responsibility
don't mix up different levels of code (don't do bit shifting and high level logic inside of one method)
I think it is useful to write comments for USERS of your code - what the classes/methods/functions do, when an how to call it etc. In other words document the API.
If you need to comment how a method works for the benefit of maintainers then I think the code is probably too complex. In that case refactor it into simpler functions, as others have said.
I personally feel that having no comments at all is about as bad as having excessive commenting. You just need to find the right balance. About using long descriptive names for things this about sums it up for me: read this Also read Kernighan & Pike on long names.
You need to follow certain rules.
Give the entities (variable, classes, etc) readable and meaningful names.
Use design patterns extensively and name them accordingly, e.g. if it is a Factory name it FooFactory.
Have the code formatted properly, etc.

Categories