Junior — Middle
Can you show an example of applying the 'Single Responsibility' principle from SOLID in a real situation?
sobes.tech AI
Answer from AI
The Single Responsibility Principle states that a class should have only one reason to change, meaning it should be responsible for a single specific task.
Example in Kotlin for Android:
// Bad: the class handles both data logic and display
class UserManager {
fun loadUser() { /* load user */ }
fun displayUser() { /* display user */ }
}
// Good: responsibilities are separated
class UserRepository {
fun loadUser() { /* load user from DB or network */ }
}
class UserView {
fun displayUser(user: User) { /* display user on screen */ }
}
This approach simplifies code maintenance and testing, as each part is responsible for its specific task.