DEV Community

Aditya satrio nugroho
Aditya satrio nugroho

Posted on

Refactoring Global Variables in Go better encapsulation structure

Transforming a simple global variable into a more structured approach in Go.

The Initial State

var (
    ApplicationName = "application.name"
)
Enter fullscreen mode Exit fullscreen mode

This variable will be used on the cross-domain in the project.

Refactoring

type application struct {
    name string
}

var app *application

func init() {
    app = new(application)
    name := viper.GetString("application.name")
    if name == "" {
        name = "myApp"
    }

    app.name = name
}

func ApplicationName() string {
    return app.name
}
Enter fullscreen mode Exit fullscreen mode

Extendibility
If you need to add more properties or methods related to the application, the struct approach is suitable because it provides a clear structure to extend.

Immutability
With the refactored approach, the application name is encapsulated within the application struct, making it harder to accidentally modify from outside. This is a plus point for safety, especially in larger codebases.

Single Responsibility Principle
application struct and its methods are now only concerned with application-related properties and behavior.

Open/Closed Principle
The current design allows for extending the application struct without modifying existing code.

Instead of accessing the struct fields directly (which we can't do from outside the package since they're unexported), we provide package-level functions like ApplicationName() for controlled access.

With this refactor, the application name is well-encapsulated, ensuring that it remains immutable throughout the application's lifecycle.

Top comments (0)