As Jeff Bay wrote: “Every programmer understands the if/else construct.” This is the simplest conditional logic, avalilable in nearly every programming language. But it also make possible to turns your code into a nasty nested conditional logic that’s impossible to follow or very dificult to read, understand and mantain. Conditionals are also a frequent source of duplication.

But don’t worry. It’s not only your fault :-)
Due to ease of simply add another branch to an conditional logic, rather than factoring to a better solution, it is a very common problem that we can see.

Tip from the book

Status flags, for example, frequently lead to this kind of trouble:

public static void endMe() {
if (status == DONE) {
doSomething();
} else {
<other code>
}
}

You have several options for rewriting this without the else. Form simple cases, use this:

public static void endMe() {
if (status == DONE) {
doSomething();
return;
}
<other code>
}

Another tip is make use of ternary operator:

public static Node head() {
if (isAdvancing()) {
return first;
}
else {
return last;
}
}

public static Node head() {
return isAdvancing() ? first : last;
}

Cutting down else keyword

Look the early return used at first example. Was used to collapse down the lines where else keyword were used. Also take care to not overuse early returns in your code. This can easily reduce clarity and turn the code into a mess again.

Simple cases can be replaced with guard clauses and early returns. Look at those sites for more information about guard clauses:

From Coding Horror I’ve taken this nice picture :-) :

Code Arrow Formation

In Object-Oriented languages we have polymorphism. It is a powerful tool for handling complex conditional cases, making the design easier to read and maintain, expressing their intent more clearly. Take a look at the Design Patterns book, and find the Strategy pattern. It can be useful to avoid duplicated branchings, and it is a good example of polymorphism. Also see the Null Object pattern, it may help in some situations.

And keep in mind that some of others rules, like the first one can help here!

Good luck in your exercise!

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Category

OO, patterns, programming, rules of thumb

Tags

, , ,