2

The following is an example of this pattern from sourcemaking.com:

https://sourcemaking.com/design_patterns/private_class_data

There are two examples, the crossed out main class and the main class that contains the data class.

My question is simply what is the difference between the following and the given correct implementation at the link:

public class MainClass {

    private final <Type> attribute1;
    private final <Type> attribute2;
    private final <Type> attribute3;

    public MainClass(<Type> attribute1, <Type> attribute2, <Type> attribute3 {
        this.attribute1 = attribute1;
        this.attribute2 = attribute2;
        this.attribute3 = attribute3;
    }
}

Cheers

Marcel
  • 1,443
  • 2
  • 14
  • 24
Seanra
  • 23
  • 2
  • 1
    You're missing the generic type definition in your question – OneCricketeer Dec 05 '17 at 09:06
  • I think the benefits of externalizing data class from business logic becomes more evident with larger classes. This small class doesn't really serves the example. – Joel Dec 05 '17 at 15:15
  • Note that pattern is not from the GoF. It looks more like an anti-pattern to me. – jaco0646 Dec 11 '17 at 01:13

1 Answers1

1

Your code here is not an example of that pattern. The crossed out model is what not to do.

You need a separate Java object to hold the attributes, and that page lists exactly why the pattern exists - to limit exposure of fields

And since this point

Main class must initialize data class through the data class's constructor

The data object can be declared as final

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I think OP understood that point, but in his example declared fields as final to make sure they're not modified after. That's his point I think. – Joel Dec 05 '17 at 14:30
  • The difference is still that there's a separate object. And that object can act as a façade for other business logic that does not need exposure from the top level class – OneCricketeer Dec 05 '17 at 14:54
  • The facade angle is interesting, thanks for the responses guys – Seanra Dec 06 '17 at 08:42