mercredi 1 mars 2017

Private class data design pattern in Java

I'm reading about private class data design pattern here and I'm trying to understand what it can really accomplish.

From what I understood private class data design pattern is a structural pattern aiming to reproduce "readonly" attributes even for the class itself: while "private" attributes are visible and editable only to the class itself, attributes in the "private class data" can't be changed at all (even by accident). The only solution is to provide a setter in the private class data, although (at least in my opinion) if the private class data has all the setters of the attributes, then we might have defeated the pattern very purpose.

Assuming my understanding is correct, this lead to a question: Even if the main class can't change any private class data attributes, it can set the reference of the private class data itself, populating it with the variables it wants to change.

In other words, an uncaring developer might do something like this:

public class MainData {
    int foo;
    int bar;
    public MainData(int foo, int bar) {
        this.foo = foo;
        this.bar = bar;
    } 
    public int getFoo() {return foo;}
    public int getBar() {return bar;}
}
public class Main {
    private MainData mainData;
    public Main(int foo, int bar) {
        this.mainData = new MainData(foo, bar);
    }
    public doSomeWork() {
        //correct behaviour
        this.mainData.getFoo() + this.mainData.getBar();
        //now I want to trick the pattern
        this.mainData = new MainData(this.mainData.getFoo(), this.mainData.getBar()+4);
        //I've changed bar :(
    }
}

Since the "readonly" attribute is not compile-enforced (unlike C# via readonly reserved word), in Java a lazy developer might do something like this. If it's true, then why should we use this design pattern at all? Unlike other patterns (like singleton) this pattern doesn't enforce anything, so why should we using it at all?

  • It would be great if you can provide example where you've used this pattern and it concretely helped you solving some software issue;
  • Let's stay on Java: I know in C# everything is much easier, but there the pattern is just plain silly because of readonly reserved word;

Thanks for any kind reply!

Aucun commentaire:

Enregistrer un commentaire