Pawan
Pawan

Reputation: 32321

Java : Brackets within the if condition

if ((one.option != two.option) && (one.side == two.side))

I need to check the followng Business Logic above

so i written this way

if((data[0].getData.value()!=data[1].getData.value())
 &&(data[0].getAction().value()==data[1].getAction().value()))

Is this correct ??

Assuming data[0] in place of one getData.value() in place of option shown in the top if condition .

I am concerned about the brackets inside the if condition

Upvotes: 0

Views: 1243

Answers (4)

Chip McCormick
Chip McCormick

Reputation: 744

Two general comments.

First, consider using tests for this kind of thing, specifically test driven development, where you write the test first, fail it and then only write enough of a test to pass it. Then there will be no mystery whether the code is correct.

This is an exercise that will help you learn that approach.

Second, based on that snippet, it looks like your code could use some refactoring to make the intention clear, for example by putting them into a method with a clear name (in your case probably two) that gets called there. TDD tends to result in that kind of clean code, as long as you take the time to refactor once your tests pass.

Upvotes: 1

user1032276
user1032276

Reputation:

Your if statement is valid but it is difficult to read. I'd recommend following the advice of others about white-space and assigning the values to variables to improve readability. Well written code shouldn't require comments, it should be self evident what data your working with!

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500795

It's correct, but personally I wouldn't bother with the brackets in this particular case. I would, however, use more whitespace. I'd write that as:

if (data[0].getData.value() != data[1].getData.value()
    && data[0].getAction().value() == data[1].getAction().value())

If you really want the brackets, I'd write it as:

if ((data[0].getData.value() != data[1].getData.value())
    && (data[0].getAction().value() == data[1].getAction().value()))

I'd normally only include the brackets if I wanted to differentiate between, say,

if ((x && y) || z)

and

if (x && (y || z))

Of course, this is assuming that the values are ones which are appropriate to compare with == and !=. If they're strings or other objects, you should potentially be using equals instead.

Upvotes: 2

SLaks
SLaks

Reputation: 887469

Your parentheses are correct.

Upvotes: 0

Related Questions