lundi 13 mars 2023

How to avoid having a change in one class resulting in needing to change multiple other classes?

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.

Aucun commentaire:

Enregistrer un commentaire