Engineering Blog

Overusing getters and setters

Encapsulation is used to hide the values or state of a structured data object, preventing unauthorized parties’ direct access to them. In Golang there is no by default support of getters and setters, so it is optional.

There are few advantage of using getters and setters event in golang and they are mentaion below :-

  • They hide the internal representation, giving us more flexibility in what we expose.
  • They provide a debugging interception point for when the property changes at runtime, making debugging easier.

For example, if we use them with a field called Age, we should follow these naming conventions:

  • The getter method should be named Age (not GetAge).
  • The setter method should be named SetAge.
package main

import "fmt"

type Foo struct {
    name string

// SetName receives a pointer to Foo so it can modify it.
func (f *Foo) SetName(name string) { = name

// Name receives a copy of Foo since it doesn't need to modify it.
func (f Foo) Name() string {

func main() {
    // Notice the Foo{}. The new(Foo) was just a syntactic sugar for &Foo{}
    // and we don't need a pointer to the Foo, so I replaced it.
    // Not relevant to the problem, though.
    p := Foo{}
    name := p.Name()

Previous Post