Good programming practices

Reduce usage of “if” statement, part 1

April 17th, 2011

The if statement is often used in almost every code. Unfortunately it reduces readability of source code and may influences of performance (but rather in low level programming languages). Below I show examples of if and propositions of improvements.

Conditional operator

Often there’s need to change variable or return value depending on some condition. Instead of if/else it’s better to use conditional operator:

Old   
  1. String result;
  2. if (isOk()) {
  3. result = "True";
  4. } else {
  5. result = "False";
  6. }

New   
  1. String result = isOk() ? "True" : "False";

Lazy/early initialization

When you create new, big object, check whether lazy initialization really improve performance. If not, early initialization is simpler.

  1. Object instance;
  2.  
  3. Object lazyInit() {
  4. if (instance == null) {
  5. instance = new Object();
  6. }
  7. return instance;
  8. }

  1. Object lazyInit() {
  2. return instance = instance == null ? new Object() : instance;
  3. }
  1. Object instance = new Object();
  2.  
  3. Object earlyInit() {
  4. return instance;
  5. }

Empty collection instead of null

When a method return a collection you must chcek if it’s not null before iterate unless you are sure it return empty collection instead.

Null   
  1. void nullChecking() {
  2. Object[] array = nullArray();
  3. if (array != null) {
  4. for (Object o : array) {
  5. //do something
  6. }
  7. }
  8. }
  1. void withoutNullChecking() {
  2. Object[] array = emptyArray();
  3. for (Object o : array) {
  4. //do something
  5. }
  6. }

Leave a Response

You must be logged in to post a comment.