N
nicolas.raoul
Hello all,
I am defining the guidelines for the readability of a Java project,
and I am hesitating between two ways of implementing imbricated if-
else in the case of checking conditions before doing something.
Let's say I have to check two conditions before doing something.
Here are the two kinds of implementations I have seen around in open
source projects:
=============== Implementation 1 ===============
if ( foo != null ) {
if ( bar != null ) {
doSomething ( foo, bar );
} else {
throw new NullBarException();
}
} else {
throw new NullFooException();
}
=============== Implementation 2 ===============
if ( foo == null ) {
throw new NullFooException();
}
if ( bar == null ) {
throw new NullBarException();
}
doSomething ( foo, bar );
================================================
Some drawbacks of Implementation 1:
- As the number of checks grows, the indentation becomes a problem.
- It is harder for the reader to see the cause-exception couples.
Some drawbacks of Implementation 2:
- Three blocks instead of one, so it does not look as a code entity.
Which implementation do you think is better for readability and
maintenance ?
Cheers,
Nicolas (http://nrw.free.fr)
I am defining the guidelines for the readability of a Java project,
and I am hesitating between two ways of implementing imbricated if-
else in the case of checking conditions before doing something.
Let's say I have to check two conditions before doing something.
Here are the two kinds of implementations I have seen around in open
source projects:
=============== Implementation 1 ===============
if ( foo != null ) {
if ( bar != null ) {
doSomething ( foo, bar );
} else {
throw new NullBarException();
}
} else {
throw new NullFooException();
}
=============== Implementation 2 ===============
if ( foo == null ) {
throw new NullFooException();
}
if ( bar == null ) {
throw new NullBarException();
}
doSomething ( foo, bar );
================================================
Some drawbacks of Implementation 1:
- As the number of checks grows, the indentation becomes a problem.
- It is harder for the reader to see the cause-exception couples.
Some drawbacks of Implementation 2:
- Three blocks instead of one, so it does not look as a code entity.
Which implementation do you think is better for readability and
maintenance ?
Cheers,
Nicolas (http://nrw.free.fr)