How to avoid IF statement

Here are some points I keep in my mind to avoid IF statement.

  1. Focus on the heaviest task
    For example, to calculate the area of a polygon, it's the base times the height divided by two if it's a triangle. it's the length times the width for a square. If it's a polygon more than square, a way to do it is dividing it into small triangles, and totalize all the areas of the triangles.

    But this way can be applicable for squares too, even triangles. So I will process every thing as a polygon. It might be faster doing it with multiplying the length and the width when it's a square. But I think it's meaningless if I could do it much faster when the task is light. Because speeding up is required when the task is heavy. So I believe in implementing method focusing on the heaviest task and make it single process. No branching for lighter cases.

  2. Make the compiler judge
    This is about polymorphism. It's a good chance to divide class when we think "When this case is happened .....". Once we divide it into inherited classes for different processes, The compiler will change the course of process properly. If there was some logical conflict, it would be easy to appear as a compile error. But if we did it with IF statement, it would be no error with compiling and hide as a bug.
    But we shouldn't do this too much by just slight differences, because it can be tougher with too many inherited classes.

In addition, SWITCH statement is just a syntax sugar of IF statement, so we should avoid it as well. It's better than multiple IF structure, though.

Home > Guideline

Copyright(C) Since 2007 DeepDigital Co.,Ltd. All Rights Reserved.