I've been trying to follow the SRP, but I've encountered a problem. For example, when I add or remove a variable in a class I have to edit multiple other classes that access the changed class. I understand that this makes sense, but surely there are other ways add variables to a class without having to change many other classes?
Below is a simple example with only one class that needs changing, but it illustrates what I mean:
class Person {
private String name;
private int age; //New variable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
class PersonDataStorage {
public void store(Person person){
write(person.getName());
//Needing to add line below to multiple classes:
write(person.getAge());
}
}
The only thing I've come up with is to do these things in the same class, but that does not follow the SRP, and I've noticed that those classes become "God-classes". Any help is appreciated.
In your example writing a Person
somewhere is usually not the responsibility of Person
itself. There could be a PersonWriter
which has the write
functionality/responsibility and if you add a new field to Persons own API has changed and if you want to write the new thing also, you have to change the PersonWriter
. This would not break the SRP.
If you change the interface of a class then you change how it can be interacted with so places that interact with it may also need changing. So all you can do is hide as much implementation details as possible in the classes internals and change the public interface rarely.
Thing with patterns like SRP is you should take them seriously but not overdo them. It's always finding the right balance to keep your code well structured and easy to read/build on top of.