Private Class Data

Private class data design pattern is basically class encapsulation at its finest form: having a private class for the class data instead of using large volumes of private attributes. This encapsulation allows a separate growth for class private data OR to facilitate Class type shared private data similar to Python class definition. The design pattern is as follow:

When to Use (Problem)

  • When the problem requires a unification for private class data across different classes definitions.
  • When the problem requires special encapsulation, where it wants to maximize its encapsulation capabilities by greatly minimizing the visibility of attributes accessibility.

Example (Solution)

Here is an example in Go:

package main

import (
        "fmt"
)

type privateClass struct {
        sharedData string
}

type PublicClass1 struct {
        ID   uint
        data *privateClass
}

func (p *PublicClass1) Init() {
        p.data = &privateClass{}
}

func (p *PublicClass1) SaveData(data string) {
        p.data.sharedData = data
}

func (p *PublicClass1) ReadData() string {
        return p.data.sharedData
}

func main() {
        p := PublicClass1{}
        p.Init()
        p.SaveData("core1")
        p.ID = 5

        fmt.Printf("Access to id: %v\n", p.ID)
        fmt.Printf("Get data: %v\n", p.ReadData())
}
// Output:
// Access to id: 5
// Get data: core1

Notice that the client is not able to access the private class's sharedData directly. Only the PublicClass1 is able to access the private class data. If we use singleton creational design pattern for the private class, we can unify all private data for all public classes.

Expected Outcome (Consequences)

  • Private data is unified under a single private class.
  • All classes using the private data class shares the same shared data if singleton design pattern is used.
  • Client is not able to directly access private data but limited to the public versions.