Junior — Middle
Can you give an example of how to implement the Open/Closed Principle from SOLID principles in practice?
sobes.tech AI
Answer from AI
The Open/Closed Principle states that software entities should be open for extension but closed for modification.
In Android development, this can be implemented, for example, through the use of abstractions and inheritance. Instead of changing an existing class, we create a new class that extends functionality.
Example:
// Base interface
interface NotificationSender {
fun send(message: String)
}
// Implementation for sending via Email
class EmailSender : NotificationSender {
override fun send(message: String) {
// email sending logic
}
}
// Later, to add SMS sending, without changing EmailSender, we add a new class
class SmsSender : NotificationSender {
override fun send(message: String) {
// SMS sending logic
}
}
// Usage
fun notifyUser(sender: NotificationSender, message: String) {
sender.send(message)
}
Thus, if you need to add a new notification sending method, you extend the system by creating new classes without changing the existing code.