Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the 'correct' way to do this (if statement)

Tags:

java

android

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?

like image 475
Richard Taylor Avatar asked Jun 03 '10 18:06

Richard Taylor


People also ask

What is the correct way to write the IF function?

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,"")

How do you write an if statement?

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 .

What is the correct way to use the IF statement in JavaScript?

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.

What is an example of an if statement?

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 .


2 Answers

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.

like image 172
VeeArr Avatar answered Sep 18 '22 18:09

VeeArr


Method A is fine - why clutter the code with unnecessary variables?

like image 36
Otávio Décio Avatar answered Sep 17 '22 18:09

Otávio Décio