N
N
Nikita2020-12-21 17:19:06
go
Nikita, 2020-12-21 17:19:06

How is encapsulation used in golang?

Hello!

Most of the time I program in PHP, now I'm learning go.
In PHP, it's normal practice to make fields private and give them the appropriate setters and getters.
Interested in how common this is in go and how it is usually implemented?

When looking at existing libraries and teaching materials, fields in structures are left public.
How would I do:

package domain

import "fmt"

type Customer struct {
  firstName string
  lastName  string
  phone     string
}

func NewCustomer(firstName string, lastName string) *Customer {
  return &Customer{firstName: firstName, lastName: lastName}
}

func (c *Customer) SetPhone(phone string) {
  c.phone = phone
}

func (c Customer) Phone() string {
  return c.phone
}

func (c Customer) FullName() string {
  return fmt.Sprintf("%s %s", c.lastName, c.firstName)
}


Does the code above have the right to life?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2020-12-21
@deliro

From the point of view of opposing one language to another, this is normal. From a design point of view, getters and setters are evil and a violation of encapsulation, except for a narrow subgroup of objects - DTOs.
https://www.yegor256.com/2014/09/16/getters-and-se...
https://stackoverflow.com/questions/2747721/getter...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question