I have a checkBox named as testCheck. When user check this the value becomes TRUE. I am able to implement the compare of the TRUE/FALSE with the following ways
1.
if (testCheck.getValue() == Boolean.TRUE) {
// Respective Code
}
2.
if (testCheck.getValue().equals(Boolean.TRUE)) {
//Respective Code
}
3.
if (testCheck.getValue()) {
//Respective Code
}
My questions:
Is there any difference ?
If yes, Which one is the best way of implementation ?
It depends....
if the return type of testCheck.getValue() is boolean, the 3rd one is ok.
But if it was Boolean (Big B), I would do:
Boolean.TRUE.equals(testCheck.getValue())
to avoid the NPE during autoboxing.
The answers:
There's no difference for compiler: a good optimizer will generate the same code. But there's difference for human beings (developers, testers, supporters etc): it's readability.
The 3d option is far more natural and that's why easier to read.
So the expected code (least surprise principle) is
if (testCheck.getValue()) {
...
//Respective Code
}
I prefer 3rd option. It's elegant. Since the testCheck.getValue() evaluated to boolean, you can use it inside the if condition
In java, with == operator, we are checking two reference are referring same object in memory.
To check two object are meaningfully equal, use .equals() method.
Is there any difference ?
There is only a difference in readability.
If yes, Which one is the best way of implementation ?
The last one is probably the way to go if you want your code to be read and understood fast.
Is there any difference ?
Yes, there is.
If yes, Which one is the best way of implementation ?
3rd one.
Related
Is Reassigning false to primitive boolean a good use of ternary operator?
boolean a = false;
Way 1 :
a = object.isAllowed() != null ? object.isAllowed() : false;
Way 2 :
if(object.isAllowed() != null) {
a = object.isAllowed();
}
Kindly suggest which is a better way and why?
No, the simple solution for this would be;
boolean a = object.isAllowed() != null && object.isAllowed();
This is assuming that object.isAllowed() returns a Boolean object that is nullable.
As per your question, object.isAllowed() returns either true or null. Since already you have assigned value of a as false, it's better not to assign the same value to the same variable (if you consider the efficiency of your code).
So way 2 is better in that case. Or you can also go with Jason's answer (it is more clear and readable).
Is Reassigning false to primitive boolean a good use of ternary operator?
In general, nothing wrong with reassigning value to a variable (if necessary), in fact variable's literal meaning is changeable.
One should just keep in mind that inefficient re-assigning of variable increases space complexity, ultimately affects program performance.
It does not related to ternary operator.
Kindly suggest which is a better way and why?
Both have minor pros and cons Like:
Way 1:
Pros
1) Compact syntax
2) More professional
Cons
1) Inefficient reassigning of variable every time. Takes a bit more memory than traditional if else.
2) If multiple conditions involved, readability of code gets affected.
3) You must have to implement else part (:) of ternary operator
Way 2:
Pros
1) Takes efficient amount of memory. (Depending on how you wrote condition)
2) More readable where multiple conditions involved.
3) else part not mandatory
Cons
1) Lengthy syntax
I have to compare objects of a custom class, say A.
Comparison is simple one based on a int member, say mem, of A.
So in comparator implementation, I can either do:
(A a1, A a2) -> {return (Integer)a1.getMem().compareTo(a2.getMem());}
Or, I can do comparison on my own:
(A a1, A a2) -> {
if(a1.getMem() > a2.getMem()){
return 1;
}else{
if(a1.getMem() < a2.getMem()) {
return -1;
}else{
return 0
}
}
}
Which one is a better approach?
First approach has far lesser lines of code, but internally compareTo does same what we are doing in second approach.
It's usually better not to re-invent the wheel. Therefore the first approach is better.
You can even write less code with Comparator.comparingInt:
Comparator.comparingInt(A::getMem)
Go for the first approach. It is more readable (how do we compare two As? compare their getMem) than a bunch of if statements and returning magic numbers. Also, using a method from the library like compareTo is less error prone than writing a bunch of comparison logic yourself. Imagine having mistyped a -1 as a 1 or a < as a >.
But, there is an even better approach:
Comparator.comparingInt(A::getMem)
One of the most basic rules to get to a "good" code base: avoid code duplication like the plague!
It is not only about writing the minimum amount of code to solve a problem. It is really about: not having the same logic in more than one place.
Why? Because when you decide to change that logic at some point, you have to remember to update all places that contain that logic.
There are studies that show that code duplication in larger project sooner or later leads to having multiple almost identical clones of some piece of logic. And guess what: that is where bugs are hiding. You copy 9 lines out of 10, and you make a subtle modification within that 9 lines. And either you just added a bug, or you fixed a problem in those 9 lines, but not in the original 10 lines. And now two places in your code do slightly different things. Rarely a good thing.
So follow the two other answers, but understand why you should do that.
And make no mistake: at some point, you might decide that this compareTo implementation is no longer what you need. Then it is perfectly fine to change it to something else, and write that down in this place in full length. But until that day: re-use that already existing code!
This question already has answers here:
object==null or null==object?
(11 answers)
Closed 2 years ago.
Consider the following two lines of code
if (test ! = null)
and
if (null != test)
Is there is any difference in above two statements, performance wise? I have seen many people using the later and when questioned they say its a best practice with no solid reason.
No difference.
Second one is merely because C/C++ where programmers always did assignment instead of comparing.
E.g.
// no compiler complaint at all for C/C++
// while in Java, this is illegal.
if(a = 2) {
}
// this is illegal in C/C++
// and thus become best practice, from C/C++ which is not applicable to Java at all.
if(2 = a) {
}
While java compiler will generate compilation error.
So I personally prefer first one because of readability, people tend to read from left to right, which read as if test is not equal to null instead of null is not equal to test.
They are exactly the same. The second one can make sense when using equals:
if("bla".equals(test))
can never throw a NullPointerException whereas:
if(test.equals("bla"))
can.
There is no performance difference but I personally find the second one being confusing.
Second one looks for me like "Yoda condition", i.e. if(2 == x) ... and is much less readable.
It's best practice to avoid some basic typo's that most modern IDE's will pick up, because sometimes you want to do comparisons between more complex types that are not null and end up doing accidental assignments. So the pattern remains the same, but I've never seen this linked to performance and have never seen it generate special byte code.
The idea is to have the static, known value first, so you can't throw any kind of weird exception when you perform the comparison.
Neither of the two methods are "more correct" though, so it's entirely up to you to decide what you wish to use.
there is no difference. But in second way you avoid the typo like test = null. Beacause in second way you'll get compiler error.
It's not a best practice to use the latter one. Both are equivalent, but the former is easier to read.
This "best practice" comes from C where boolean don't exist. Integers are used instead, and if (foo = 1) is not a syntax error, but is completely different from if (foo == 1).
In Java, only boolean expressions can be inside an if, and this practice doesn't make much sense.
There is no really different between two form. There is no performance issue but there are following notes:
First form is readable for code reader, because people usually read codes Left-To-Right.
Second form is better for code writer, because in java = operator is for assignment and == operator is for test equivalent, but people usually using in if statement = instead of ==, by second approch developer getting Compile-Time-Error because null can't use in Left-Side of a assignment statement.
I'm updating some code, and I have a void method (validateFile) that tests files and writes failures directly to some log files. I want to add a counter for each file that passes, but I don't want to lose the logging that's done in case of failure.
In terms strictly of the validateFile method running successfully, is this:
validateFile(filename);
functionally equivalent to this? (assuming I change the return type to boolean and put return statements in correctly)
if(validateFile(filename)){
passCount++;
}
If it is equivalent, is there a reason (best practices, etc.) that I shouldn't do this?
Yes, it is equivalent. No, there is no reason I can think of that you should not do this.
Just one possible caveat that comes to mind, take care when mixing this with conditional operators:
if (a() && b());
In that case, b() will be called if and only if a() returns true.
Yes, it is equivalent; there is no reason why this might be inferior to the original code.
You could also do the same thing on a single line, like this:
passCount += validateFile(filename) ? 1 : 0;
Yes, your code will work this way, it will compile. And it is actually the best way to go about it, most of the time.
EDIT: Assuming, that in the first case, you are binding it to a variable and placing that one in an if. Else, not so much, the first one wont work.
The latter one has better separation of concerns. I would prefer it.
Yes, if(validateFile(filename)) will run validateFile(filename) in exactly the normal way. Once it returns — assuming it returns normally (as opposed to throwing an exception) — its return value will be used exactly as you expect.
Yes, this will work.
Calling methods this way is pretty standard.
Yes, it is equivalent. It is just like:
boolean result = validateFile(filename);
if(result){
passCount++;
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
please see the below code:-
if(myVariable==5)
{
//some logic
}
one of my friends says that this is not a good way to write the code as its not per guidelines, however he dont have any reason to it. Is there is a chance of exception with above code or accidental modification?? According to him the better way would have been
if(5==myVariable)
{
//some logic
}
please let me know which is a better way and why??? Do provide links if u have any.
The only reason to write:
5 == variable
instead of
variable == 5
is that in the former case if you incorrectly put an assignment (single =) in place you will get a compile time error because you are trying to overwrite a constant.
However any decent compiler will give you a warning if you do:
if (variable = 5)
so IMHO it's not worth worrying about. I always use the latter if (var == num) form.
However in Java there is a common pattern that is worth using. When testing a string for equality, one should use:
if ("constant".equals(variable)) { ... }
instead of:
if (variable.equals("constant")) { ... }
since the latter can trigger a null pointer exception, and the former cannot.
The reversal is preferable in some languages like C, where
if (x = 5) {
...
}
would accidentally assign x to the value 5 if you mistype = instead of ==. By reversing the two arguments the compiler would rightfully object to you reassigning the value 5.
Unlike C/C++, for languages such as Java it's not such an issue since
if (x = 5) {
...
}
isn't a valid statement. I still follow the above practise however. I don't have to rethink when swapping between Java and C/C++.
Both are same. select which ever you find more readable.. I would go with first
For that specific case, it's technically safer to do 5 == variable because then if you accidentally say 5 = variable the compiler will complain. On the other hand, variable = 5 is perfectly legal.
This convention is to prevent you from accidentally writing if (myVariable=5) when you mean if (myVariable==5).
For ==, it doesn't matter a bit what order you do it in.
Your friend mentioned "guidelines"-- perhaps it's a business rule? Albeit an arbitrary and semi-pointless one...
It's immaterial. I prefer the first one, because it's more readable.
I hope you're aware that using == is not always correct for reference types. In those cases you should prefer equals. THEN it matters, because you want to avoid null pointer exceptions. It's best to dereference the instance that cannot be null in that case.
There is no such guildline I found.
First approach should be followed because it is more readable.
i think if you what to know if they are equals it's fine then.
but if you want to know about string, then i more appropriated use '.equals'.
e.g:
object.equals("something");
The only thing I can think of is to avoid possible syntax errors of the kind constant = expression, or to avoid mangled operator overload in C++. In Java both expressions are syntatically valid and picking one over the other is a matter of choice.