I've got plenty of these lying around, and I'm wondering if I'm going to face any trouble - or performance problems.
I have method A:
MyClass monkey;
...
if(monkey != null) {
...
}
Or method B:
boolean hasMonkey; //This is set to TRUE when monkey is not null
MyClass monkey;
...
if(hasMonkey) {
...
}
On a functional level, they both do the same thing. Right now, I'm using method A. Is that a bad way of doing things? Which is going to perform better?
Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK") =IF(A2=B2,B4-A4,"")
To write an if statement, write the keyword if , then inside parentheses () insert a boolean value, and then in curly brackets {} write the code that should only execute when that value is true .
In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
if (score >= 90) grade = 'A'; The following example displays Number is positive if the value of number is greater than or equal to 0 . If the value of number is less than 0 , it displays Number is negative .
Method A is what I have seen as the "common" case. Method B introduces a problem of data consistency (what is hasMonkey
does not get set correctly?), while Method A relies on only the object itself to determine its validity. In my opinion, Method A is far superior.
Method A is fine - why clutter the code with unnecessary variables?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With