Junior — Middle
How can you ensure openness for extension and closedness for modification in software components?
sobes.tech AI
Answer from AI
The Open/Closed Principle from SOLID states that software entities should be open for extension but closed for modification. This is achieved through the use of abstractions and polymorphism.
In C#, this can be implemented via:
- Interfaces and abstract classes that define a contract.
- Inheritance and method overriding to extend functionality without changing existing code.
- Using design patterns, such as Strategy or Decorator, to add new behavior.
Example:
public abstract class Logger
{
public abstract void Log(string message);
}
public class FileLogger : Logger
{
public override void Log(string message)
{
// Logic to write to a file
}
}
public class DatabaseLogger : Logger
{
public override void Log(string message)
{
// Logic to write to a database
}
}
// To add a new type of logger, there is no need to change existing classes, just create a new class inheriting Logger.