Junior — Middle
What methods can ensure adherence to the open/closed principle in software modules?
sobes.tech AI
Answer from AI
To adhere to the Open/Closed Principle, modules should be open for extension but closed for modification. Ways to achieve this:
- Use of abstractions: Define interfaces or abstract classes, and create concrete implementations separately.
- Inheritance and polymorphism: Extend behavior through subclasses without changing the source code of the base class.
- Composition and delegation: Introduce new functionalities through components rather than modifying existing ones.
- Design patterns: For example, Strategy, Decorator, Factory allow adding new behaviors without changing existing code.
Example in C# using an interface:
public interface ILogger {
void Log(string message);
}
public class ConsoleLogger : ILogger {
public void Log(string message) {
Console.WriteLine(message);
}
}
public class FileLogger : ILogger {
public void Log(string message) {
// Write to file
}
}
// Class using ILogger does not change when new loggers are added
public class Processor {
private readonly ILogger _logger;
public Processor(ILogger logger) {
_logger = logger;
}
public void Process() {
_logger.Log("Processing started");
// ...
}
}
Thus, to add a new logger type, it is enough to create a new class implementing ILogger without changing Processor.