Click here to Skip to main content
13,355,538 members (72,140 online)
Click here to Skip to main content
Add your own
alternative version


4 bookmarked
Posted 23 Jul 2012

Open/Closed Principle (OCP)

, 23 Jul 2012
Rate this:
Please Sign up or sign in to vote.
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:

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)

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 {
  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.


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


About the Author

Software Developer (Senior)
Russian Federation Russian Federation
No Biography provided

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180111.1 | Last Updated 23 Jul 2012
Article Copyright 2012 by loki2302
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid