Boas Práticas & Clean Code com Go

BIANCA ROSA

Agenda

  • Nomenclaturas e convenções
    • Nomes de variáveis
    • Nomes de pacotes
    • Nomes de funções
    • Nomes de interfaces
    • Comentários
  • Conceitos de Clean Code
    • Regra do Escoteiro
    • SRP
    • DRY
  • O cinto de ferramentas do desenvolvedor Go
  • O que não fazer
  • Referências

Nomenclaturas e convenções

There are only two hard things in Computer Science: cache invalidation and naming things.

Phil Karlton

Nomes de variáveis

  • Lower case, se necessário utilize mixedCaps.
     
  • Regra básica: crescem e se tornam mais descritivos de acordo com o tamanho do escopo.
     
  • Pequenos e abreviados quando usados em blocos de escopo menores.
     
  • Podem ser mais descritivos em blocos de escopo maiores.

Exemplos

  • req vs request
  • res vs response
  • c vs counter
  • n vs number
  • s vs string
  • i vs loopIndex
  • addr vs address

Como assim "tamanho do escopo"?

O escopo de uma variável é definido pelo momento da sua declaração até o último momento em que ela pode ser utilizada.

 

Um pacote é um escopo MUITO grande para variáveis com nomes muito pequenos.

Cuidado!

Escreva código para humanos.

 

A idéia de encurtar nomes é para facilitar e não para gerar complexidade.

Nomes de pacotes

  • Lower case, uma única palavra: sem underscore ou mixedCaps.
     
  • Use nomes de pacotes que vão fazer sentido na chamada da sua função.

Colisão de nome de pacotes

Pode acontecer.

Quem nunca acabou parando com dois pacotes utils e quando foi importar, se viu com um problema?

Dica: deixe o pacote com o nome que faz sentido pra ele e delegue a responsabilidade de nomear o pacote no momento da importação.

Exemplo

import "io"
import "bufio"
import "ring"

ring := ring.New()
var reader *io.Reader
var bufreader *bufio.Reader

Nomes de funções

  • Seguem a mesma regra de variáveis: mixedCaps ou MixedCaps.
     
  • Seja descritivo.
     
  • Seja conciso.

Exemplo

obj.Owner()

obj.SetOwner(owner)

Nomes de interfaces

  • Em interfaces de um único método, o nome, por convenção, é adotado como o nome do método + o sufixo -er (exemplo: Reader, Writter, Formatter, Notifier)

Exemplo

type Caller interface {
	Call()
}

type Notifier interface {
	Notify()
}

Escrevendo comentários

  • Evite escrever comentários para explicar lógica e código. Ao invés disso, invista em nomes de funções que façam sentido.
     
  • A grande utilidade de comentários é a geração de doc automáticas através do go doc.

Echo - Context

type (
	// Context represents the context of the current HTTP request. It holds request and
	// response objects, path, path parameters, data and registered handler.
	Context interface {
		// Request returns `*http.Request`.
		Request() *http.Request

		// SetRequest sets `*http.Request`.
		SetRequest(r *http.Request)

		// SetResponse sets `*Response`.
		SetResponse(r *Response)

		// Response returns `*Response`.
		Response() *Response

		// IsTLS returns true if HTTP connection is TLS otherwise false.
		IsTLS() bool

		// IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
		IsWebSocket() bool

		// Scheme returns the HTTP protocol scheme, `http` or `https`.
		Scheme() string

		// RealIP returns the client's network address based on `X-Forwarded-For`
		// or `X-Real-IP` request header.
		RealIP() string

		// Path returns the registered path for the handler.
		Path() string

		// SetPath sets the registered path for the handler.
		SetPath(p string)

		// Param returns path parameter by name.
		Param(name string) string

		// ParamNames returns path parameter names.
		ParamNames() []string

		// SetParamNames sets path parameter names.
		SetParamNames(names ...string)

		// ParamValues returns path parameter values.
		ParamValues() []string

		// SetParamValues sets path parameter values.
		SetParamValues(values ...string)

		// QueryParam returns the query param for the provided name.
		QueryParam(name string) string

		// QueryParams returns the query parameters as `url.Values`.
		QueryParams() url.Values

		// QueryString returns the URL query string.
		QueryString() string

		// FormValue returns the form field value for the provided name.
		FormValue(name string) string

		// FormParams returns the form parameters as `url.Values`.
		FormParams() (url.Values, error)

		// FormFile returns the multipart form file for the provided name.
		FormFile(name string) (*multipart.FileHeader, error)

		// MultipartForm returns the multipart form.
		MultipartForm() (*multipart.Form, error)

		// Cookie returns the named cookie provided in the request.
		Cookie(name string) (*http.Cookie, error)

		// SetCookie adds a `Set-Cookie` header in HTTP response.
		SetCookie(cookie *http.Cookie)

		// Cookies returns the HTTP cookies sent with the request.
		Cookies() []*http.Cookie

		// Get retrieves data from the context.
		Get(key string) interface{}

		// Set saves data in the context.
		Set(key string, val interface{})

		// Bind binds the request body into provided type `i`. The default binder
		// does it based on Content-Type header.
		Bind(i interface{}) error

		// Validate validates provided `i`. It is usually called after `Context#Bind()`.
		// Validator must be registered using `Echo#Validator`.
		Validate(i interface{}) error

		// Render renders a template with data and sends a text/html response with status
		// code. Renderer must be registered using `Echo.Renderer`.
		Render(code int, name string, data interface{}) error

		// HTML sends an HTTP response with status code.
		HTML(code int, html string) error

		// HTMLBlob sends an HTTP blob response with status code.
		HTMLBlob(code int, b []byte) error

		// String sends a string response with status code.
		String(code int, s string) error

		// JSON sends a JSON response with status code.
		JSON(code int, i interface{}) error

		// JSONPretty sends a pretty-print JSON with status code.
		JSONPretty(code int, i interface{}, indent string) error

		// JSONBlob sends a JSON blob response with status code.
		JSONBlob(code int, b []byte) error

		// JSONP sends a JSONP response with status code. It uses `callback` to construct
		// the JSONP payload.
		JSONP(code int, callback string, i interface{}) error

		// JSONPBlob sends a JSONP blob response with status code. It uses `callback`
		// to construct the JSONP payload.
		JSONPBlob(code int, callback string, b []byte) error

		// XML sends an XML response with status code.
		XML(code int, i interface{}) error

		// XMLPretty sends a pretty-print XML with status code.
		XMLPretty(code int, i interface{}, indent string) error

		// XMLBlob sends an XML blob response with status code.
		XMLBlob(code int, b []byte) error

		// Blob sends a blob response with status code and content type.
		Blob(code int, contentType string, b []byte) error

		// Stream sends a streaming response with status code and content type.
		Stream(code int, contentType string, r io.Reader) error

		// File sends a response with the content of the file.
		File(file string) error

		// Attachment sends a response as attachment, prompting client to save the
		// file.
		Attachment(file string, name string) error

		// Inline sends a response as inline, opening the file in the browser.
		Inline(file string, name string) error

		// NoContent sends a response with no body and a status code.
		NoContent(code int) error

		// Redirect redirects the request to a provided URL with status code.
		Redirect(code int, url string) error

		// Error invokes the registered HTTP error handler. Generally used by middleware.
		Error(err error)

		// Handler returns the matched handler by router.
		Handler() HandlerFunc

		// SetHandler sets the matched handler by router.
		SetHandler(h HandlerFunc)

		// Logger returns the `Logger` instance.
		Logger() Logger

		// Echo returns the `Echo` instance.
		Echo() *Echo

		// Reset resets the context after request completes. It must be called along
		// with `Echo#AcquireContext()` and `Echo#ReleaseContext()`.
		// See `Echo#ServeHTTP()`
		Reset(r *http.Request, w http.ResponseWriter)
	}

	context struct {
		request  *http.Request
		response *Response
		path     string
		pnames   []string
		pvalues  []string
		query    url.Values
		handler  HandlerFunc
		store    Map
		echo     *Echo
		lock     sync.RWMutex
	}
)

Conceitos de Clean Code

Regra do Escoteiro

The Boy Scout Rule

Ao sair da área onde você estava acampado, deixe-a mais limpa do que quando a encontrou.

Ou seja...

  • Se você está mexendo num arquivo que tem um typo, corrija-o.
  • Se o nome dessa variável poderia ser melhor, refatore.
  • Se você está escrevendo testes para uma função e tem uma função não testada logo ao lado, escreva mais um teste!

Se você nunca fizer um pouquinho a mais pra melhorar seu código, ele não melhora sozinho.

Princípio da Responsabilidade Única (SRP)

type fox struct{}
                      
func (f *fox) Say() {
  fmt.Println("Ring-ding-ding-ding-dingeringeding!")
}
type fox struct{}
                      
func (f *fox) Say() {
  fmt.Println("Ring-ding-ding-ding-dingeringeding!")
}

func (f *fox) Meow() {
  fmt.Println("Meow-meow-meow-meow-meow-meow")
}
type fox struct{}
          
func (f *fox) Say() {
  fmt.Println("Ring-ding-ding-ding-dingeringeding!")
}

type cat struct{}

func (c *cat) Meow() {
  fmt.Println("Meow-meow-meow-meow-meow-meow")
}

DRY

Don't Repeat Yourself

Copiar e colar código ou escrever códigos muito parecidos é um sinal de que algo pode estar errado.

Criar códigos complexos para não copiar ou reescrever códigos simples é um sinal de algo está ainda mais errado.

O cinto de ferramentas do desenvolvedor Go

Tools

  • fmt
  • vet
  • pprof

O que não fazer

func converte(s string) int {
  n, _ := strconv.Atoi(s)
  return n
}

Sempre cheque seus erros!

Ops.

Referências Legais

0brigada!

Boas Práticas & Clean Code com Go

By Bianca Rosa

Boas Práticas & Clean Code com Go

  • 1,582