Click here to Skip to main content
15,886,422 members
Articles / Programming Languages / Java

Open/Closed Principle (OCP)

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
23 Jul 2012CPOL 8.9K   4  
Classes should be easy to extend and alter without changing their code.

SOLID principles:

Classes should be easy to extend and alter without changing their code.

Let's consider the calculator example once again:

Java
class CalculatingMachine {
  public static void add(int x, int y) {
    System.out.println(x + y);
  }
}

How do I change its behavior? What if want it to use something else but System.out for printing? Looks like OCP is violated here, there's no explicit way I can do it. One of the possible solutions here is to make this class abstract.

(not for production, illustrative purposes only)

Java
abstract class AbstractCalculatingMachine {
  public void add(int x, int y) { // cant use static anymore
    getPrintStream().print(x + y);
  }
  
  protected abstract PrintStream getPrintStream();
}

class ConsoleCalculatingMachine extends AbstractCalculatingMachine {
  @Override
  protected PrintStream getPrintStream() {
    return System.out;
  }
}

I have all the calculator machine-specific behavior implemented in abstract class AbstractCalculatingMachine. I also have ConsoleCalculatingMachine that uses System.out for printing the results. As soon as I need a way to print results to file, I'll just subclass AbstractCalculatingMachine once again and will return file-based PrintStream in getPrintStream(). This can be done without altering AbstractCalculatingMachine class' code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --