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.
Related
Last week in high school my IT teacher gave us a programm, where one part she wrote interested me a lot.
In an if-statement, she checked if an element of an array was not null, so the programm could proceed with this element, therefore she wrote:
if (!(array[i] == null), which confused me, because with this method you are just using a bracket more, which makes it less easy to read. I changed it to ìf (array[i] != null) and it worked just fine. But now I am confused, because as a teacher I assume you know a lot of your subject, so could there be a good reason why she used her method over mine? Is there some detail I don't know about?
There is no difference in the semantics of the two expressions. I would say there is no good reason to ever write the former.
But now I am confused, because as a teacher I assume you know a lot of your subject, so could there be a good reason why she used her method over mine?
The best thing to do is to ask your teacher. The most important thing to remember about teachers - as human beings - is that they have experiences, prejudices and are fallible.
In other words, she might have been bitten by some problem in the past which was solved by writing it like this - ask her about it, you might learn something.
Or, she perhaps thinks it's better, and can't articulate a strong benefit over personal preference; or that was the way she learnt, and hasn't seen a strong need to change - you learn something from that, insofar as there is more than one way to articulate the same semantics.
(I have a strong preference for != because it's neater - fewer parentheses; and why would the language designers bother providing != if you weren't intended to use it - but these are my personal preferences).
Or, she maybe meant to use !=, and forgot to go back to fix it. It's easy to forget to clean things up.
In Java, there is no difference between a!=b and !(a==b). Choosing the later form is a stylistic choice, which, to be honest, most static analysis tools/IDEs will issue a warning about.
Your teacher is using other ways to write the if-statement.
It doesn't matter if you write
if(array[i] != null)
or
if(!(array[i] == null))
because ! defines as not in most programming language. In this situation both of them are equal.
In conclusion, you can choose whatever style you like.
Hope you understood and good luck!
Always ask your teacher when you wonder about something :)
The other answers are correct. For your example there is no difference - chose what you like the most. But I'd like to give some more reasons to chose one way over the others.
My advice would be not to go for if (! (...)) in general because:
Most people wouldn't do it like this. You will have to read and understand code written by others and others will have to read and understand your code. Quirks like that greatly reduce the redability and collegues will frown upon you.
Some projects might follow a coding standard that doesn't allow this.
Think about the execution. For more complex statements the different style might have an impact. Think of !(A || B || C || D) vs !A && !B && !C && !D. It might happen that in the former A-D have to be evaluated and then the resulting boolean is flipped wheras in the latter it might be enough to see that !A evaluates to false and you can already stop there (because any conjunction with a false member will be false).
But also think about readability again. Actually it might be easier to grasp writing NOT(is_a_digit OR is_a_letter OR is_a_dot) instead of
NOT(is_a_digit) AND NOT(is_a_letter) AND NOT(is_a_dot).
That being said, it's also good to know about Yoda-style writing which is kinda related. Imagine you have String someString; that might contain a string or might be null. Now imagine you'd like to check if its equal to "some specific string": someString.equals("some specific string") - yikes, this might produce a NPE because when someString is null there is no method equals to call on it. Instead you'd have to do someString != null && someString.equals("...") or the Yoda-way of "some specific string".equals(someString). There's also other helpers like Objects.equals().
Sometimes extra parenthesis can make things easier to grasp and sometimes they don't.
While I don't agree that "there are no stupid question" I'd say that sometimes it's better to ask a dumb question than falling behind in the lessons because something nags at you or you missed some important bit. In this case I'd consider this a good question (unless she just told you why).
There is a difference between a!=b and !(a==b), it depends on personal preference and what code you're using. In python a!=b is faster, as other answers have stated.
Actually there is no difference between if (!(array[i] == null) and ìf (array[i] != null)
In this case we can imagine a scenario. Lets say array[i] is not null, then for the first expression inside if(!(false)) , eventually !(false) will be true.
And for the second expression the return result will be directly true.
So seconnd expression is recommended always.
The former is not a good idea in some languages like python,
In python, for former the better way is
if not something==somethingElse
although for latter its perfect, if something != somethingElse,
So learning the former might get you in some situations where the bug is so subtle that debugging gets really hard, especially when you use this condition in while loop
!= is more efficient than !(). I ran a test in python, and it speaks for itself.
(not a and not b and not c and not d) 10.07692837715149
(not (a and b and c and d)) 11.208963394165039
Currently working on modifying big mapping classes and some new rules have appeared making me wonder what is the best option here.
Imagine a classic mapping function like so:
yyy.setType(xxx.getType);
yyy.setSomething(xxx.getSomethigElse);
yyy.setThisAsWell(xxx.getThatAsWell);
And I now have a condition to check, what would be better? (knowing that I won't have future similar condition checking to do):
final Boolean isRuleApplying = xxx.getRule == RULE;
yyy.setType(
isRuleApplying ? RULE_STUFF : xxx.getType
);
yyy.setSomething(
isRuleApplying ? RULE_STUFF_OTHER : xxx.getSomethigElse
);
yyy.setThisAsWell(
isRuleApplying ? RULE_STUFF_AGAIN : xxx.getThatAsWell
);
Or is it better to use the old if else?
if (xxx.getRule == RULE) {
yyy.setType(RULE_STUFF);
yyy.setSomething(RULE_STUFF_OTHER);
yyy.setThisAsWell(RULE_STUFF_AGAIN);
} else {
yyy.setType(xxx.getType);
yyy.setSomething(xxx.getSomethigElse);
yyy.setThisAsWell(xxx.getThatAsWell);
}
I feel that using ternary operation make it less maintainable and adds more complexity (checks everytime). But I wanted to get some other opinions.
Note: I have a bunch of try..catch so using if means duplicating those try blocks or adding an if in every block which kind of kills readability.
There's no absolute answer to this question. It depends.
With the ternary operator, you immediately see:
Three properties are always set to some value, and it's always the same properties, independent of the condition.
You see the two alternative values close to one another, so for a reader it's easy to compare them.
But there are some (many?) developers who arent't used to that operator (is that their fault or ours?), so using it might force them to look up its meaning instead of immediately understanding the code (to me, having a LISP background, the ternary operator always was as least natural as the if statement).
And it's true, with the ternary operator, you end up with three conditionals instead of one (but you should ignore these minor performance effects unless you find out that it really hurts in your application).
On the other hand, with the if statement, you immediately see:
It's just one condition that influences all properties.
You see the properties combinations for the two situations close together.
And even Java beginners will understand your code.
So, it depends on:
the Java fluency of your co-workers
whether you want to stress the different values for the single properties or the value-sets for the three properties.
And of course, all this isn't very object-oriented. If code structure and budget allow, maybe you could come up with a solution using polymorphism instead of the conditionals.
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.
Response execute(String para1,String para2){
String xmlRequest = buildRequest(para1, para2);
String xmlResponse = getXmlResponse(xmlRequest);
Response response = parseResponse(xmlResponse);
return response;
}
Or the concatenated version? Why is that?
Response execute(String para1,String para2){
return parseResponse(getXmlResponse(buildRequest(para1, para2)));
}
Thanks,
Sarah
In contrast to what others have written, I find the second version much easier to read.
First, there's about half as many symbols for me to parse (12 vs 21). There's no way for me to glance at the first one and understand what it's doing, even though what it's doing is just as simple as the second method.
Second, in the second example, the data flow is obvious: you can just read down the line. In the first one, I had to look carefully to make sure the variable in one is used in the next, for each pair of lines (especially since 2 of the temp variables start with the exact same 5 characters). This is exactly the sort of case that somebody is going to update later, leave an extra variable assignment around by mistake -- I've seen it a million times.
Third, the second one is written in a more functional style, and reasoning about functional code tends to be easier. In this case the benefit is minimal, since the first 2 lines are assignments to an immutable object, but declaring 3 variables shifts me into "something complex is happening here" mode, which really isn't the case here.
Of course, this method is so small you can't go far wrong either way, but I find it useful to apply good habits at any scale.
I like the first version better because it's easier to read, not so many nested parameters. Other than readability there shouldn't be a difference in performance.
First one is better. Because it is more readable.
Any programmer can write code that a computer can understand.
Good programmers write code that humans can understand.
They are the same, but as mentioned, the first one is more readble, so that would tip the scales in favor for the first one.
When you nest methods like in the second one, the compiler simply does what you do in the first one for you. So there is no win in terms of speed memory use.
I would say it depends. If it's a static utility method that is extremely unlikely to change, I might go with the second one just to keep the number of lines smaller. But it totally depends.
The first one has an advantage while debugging: when you step through this code in a debugger, you have a chance to view the return values of the different methods easily (i.e., with the debugger you can easily see what is in xmlRequest, xmlResponse and response).
However, I'd prefer the second notation, because the first version is overly verbose and I don't find the first version more readable than the second. But ofcourse it's a matter of opinion.
To validate user inputs, I am unsure of which of two alternatives is better
1
isNull( Object input )
2
notNull( Object input )
apache's commons lang library chose #2 but I am uncomfortable with double negatives. What do you say ?
To me, double negatives is always a bad thing.
I'd say stick to isNull. Checking for nullity then makes sense while reading.
The opposite would be
if (! isNull(o) )
// ...
which reads out "if not is null". Sure it sounds retarded read out loud, but it makes more sense than checking for nullity with option #1.
if (! isNotNull(o))
// ...
A statement which makes you rewind and say "hey, wait a minute... if not is not...".
But if there is a standard already with having negatives in method names, stick to it. Standards are good things, and should not be broken just because someone is "uncomfortable".
I am uncomfortable with functions which are longer than the code they replace.
I would use x == null or x != null. I agree that double negative isn't clear either.
A puzzle for you, when is (s != s) true? A good example of confusing behaviour. ;)
Honestly, I don't think it makes much difference.
If you are designing your own API, implement it the way you are most comfortable with. Indeed, there's no strong reason to not to implement both isNull and notNull if that makes you feel happier.
But I think it would be silly to abandon plans to use some third-party library solely because you are "uncomfortable with" double negatives. They really aren't that confusing.
The answer here depends on so many considerations, of which some are:
What does your programming environment support most naturally?
What does other similar code in the same project do?
What coding standards are you working to, if any?
Which approach is easier to understand for others reading your code?
If you want a more considered answer, do let us know some more of the details. In the meantime, my top tip would be to go for whatever enhances readability of the code: you want to give future maintainers as much help as you can.
I am a little confused by the question. If the methods in question are just returning a boolean depending upon whether the argument is null, then == null or != null are much better.
However, the reference to Apache Commons Lang seem to indicate that this is validity checking, and an appropriate exception should be thrown is the reference is null. In that case you can't invert the output easily.
FWIW, it looks as if JDK7 will introduce a notNull method, as discussed on an appropriate mailing list, something along the lines of:
public static <T> T notNull(T obj)
Used as:
import static java.util.Object.notNull;
public final MyClass {
private final Thing thing;
public MyClass(Thing thing) {
this.thing = notNull(thing);
}
...