Search code examples
javadesign-patternsencapsulationdesign-principles

Structural design patterns: (Private class data) Is there a difference between these two examples


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


Solution

  • 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