Tag Archives: pattern

Methods must be stupid

3se4um
Find small error in architecture sense.

Wrong realization is as following:

public class Login {

  private String username;

  public boolean isAuthenticated() {
    return username != null;
  }

  private void init() {
    if (username == null) {
      // Some actions to get data...
      username = "Johnny Depp";
    }
  }
}

As you see, method init() checks the value of username field. That’s not right.
Methods must perform some action regardless to any external state. But decision to call or not must be accepted by caller.

Here is right implementation:

public class Login {

  private String username;

  public boolean isAuthenticated() {
    if (username == null) {
      init();
    }
    return username != null;
  }

  private void init() {
    // Some actions to get data...
    username = "Johnny Depp";
  }
}

Decorator and Proxy patterns

Both Decorator and Proxy patterns and delegates some object method execution.

But the difference is Decorator doesn’t require a source object while creating and encapsulates object creating.

Other side, Proxy pattern which take an object as input parameter and exec method of it later.