Good programming practices

Reduce usage of “if” statement, part 2

April 20th, 2011

Here are next ideas how to replace “if” statement by other patterns.

Improvement of loop

Each loop checks condition if the next iteration should be performed. You should use this construction instead of using if(..) break; inside the loop if it’s possible.

Old loop   
  1. boolean oldLoop() {
  2. List list = getList();
  3. Object wanted = getObject();
  4. boolean found = false;
  5. for (Object o : list) {
  6. if (wanted.equals(o)) {
  7. found = true;
  8. break;
  9. }
  10. }
  11. return found;
  12. }

New loop   
  1. boolean newLoop() {
  2. List list = getList();
  3. Object wanted = getObject();
  4. Iterator it = list.iterator();
  5. boolean found = false;
  6. while (it.hasNext() && !(found = wanted.equals(it.next())));
  7. return found;
  8. }

Switch

When you check whether variable is equals to some constant value, you can use switch. It works for integers (including char, see switch statement in JLS) and enum type.

If/else   
  1. int a = getInt();
  2. if (a == 1) {
  3. //first action
  4. } else if (a == 2) {
  5. //second action
  6. } else if (a == 3) {
  7. //third action
  8. } else {
  9. //something else
  10. }
  1. int a = getInt();
  2. switch (a) {
  3. case 1:
  4. //first action
  5. break;
  6. case 2:
  7. //second action
  8. break;
  9. case 3:
  10. //third action
  11. break;
  12. default:
  13. //something else
  14. }

Validation

This process may be implemented in different ways. Usually there are 3 steps:

check, if input data are valid,

show message in case of invalid data,

go to the next step only if all data are valid.

  1. boolean validateOld(String data1, String data2) {
  2. boolean result = true;
  3. if (!validator1(data1)) {
  4. log("Bad data1");
  5. result = false;
  6. }
  7. if (!validator2(data2)) {
  8. log("Bad data2");
  9. result = false;
  10. }
  11. return result;
  12. }
  1. boolean validateNew(String data1, String data2) {
  2. boolean result = true;
  3. result &= (validator1(data1) ? true : log("Bad data1"));
  4. result &= (validator2(data2) ? true : log("Bad data2"));
  5. return result;
  6. }

Note that validator1 and validator1 returns result of validation, and log always return false.

Leave a Response

You must be logged in to post a comment.