SOLID Principles : Guidelines for software development :: OCP
The SOLID principles provide five guidelines that, when followed, can dramatically enhance the maintainability of software.
- Open / Closed Principle Intro
- Download Examples
The OCP states that all classes and similar units of source code should be open for extension but closed for modification.
- The Open / Closed Principle (OCP) states that classes should be open for extension but closed for modification.
- “Open to extension” means that you should design your classes so that new functionality can be added as new requirements are generated.
- “Closed for modification” means that once you have developed a class you should never modify it, except to correct bugs.
- The two parts of the principle appear to be contradictory. However, if you correctly structure your classes and their dependencies you can add functionality without editing existing source code.
- Generally you achieve this by referring to abstractions for dependencies, such as interfaces or abstract classes, rather than using concrete classes.
- Such interfaces can be fixed once developed so the classes that depend upon them can rely upon unchanging abstractions. Functionality can be added by creating new classes that implement the interfaces.
Benefits
- Applying the OCP to your projects limits the need to change source code once it has been written, tested and debugged.
- This reduces the risk of introducing new bugs to existing code, leading to more robust software.
- Another side effect of the use of interfaces for dependencies is reduced coupling and increased flexibility.
Download Examples
Code Available Before OCP
LogType.java
package com.javaskool.before;
public enum LogType
{
Console,
File
}Logger.java
package com.javaskool.before;
import java.io.Console;
public class Logger
{
public void Log(String message, LogType logType)
{
switch (logType)
{
case Console:
System.out.println(message);
break;
case File:
// Code to send message to printer
break;
}
}
}Code Available After OCP
IMessageLogger.java
package com.javaskool.after;
public interface IMessageLogger {
void Log(String message);
}ConsoleLogger.java
package com.javaskool.after;
public class ConsoleLogger implements IMessageLogger{
public void Log(String message)
{
System.out.println(message);
}
}Logger.java
package com.javaskool.after;
public class Logger {
IMessageLogger messageLogger;
public Logger(IMessageLogger messageLogger)
{
this.messageLogger = messageLogger;
}
public void Log(String message)
{
messageLogger.Log(message);
}
}PrinterLogger.java
package com.javaskool.after;
public class PrinterLogger {
public void Log(String message)
{
// Code to send message to printer
}
}
Recent Comments