Junior — Middle
Can you give an example illustrating the Single Responsibility Principle in SOLID principles?
sobes.tech AI
Answer from AI
The Single Responsibility Principle (SRP) states that a class should have only one reason to change, meaning it should be responsible for a single specific task.
Example in Android: suppose you have a class UserManager that is responsible for both fetching user data from the network and saving that data to a database.
This violates SRP because the class is responsible for two different tasks — network interaction and database operations.
A better approach is to separate these responsibilities:
class UserNetworkService {
fun fetchUserData(userId: String): User {
// code to fetch data from network
}
}
class UserRepository {
fun saveUser(user: User) {
// code to save user to database
}
}
class UserManager(
private val networkService: UserNetworkService,
private val repository: UserRepository
) {
fun updateUser(userId: String) {
val user = networkService.fetchUserData(userId)
repository.saveUser(user)
}
}
This approach simplifies maintenance and testing, as each part is responsible for its own area of concern.