Benefícios das interfaces no GO

Benefícios das interfaces no GO



No GO, as interfaces são diferentes de outras linguagens de programação populares, como Java, C ++, PHP. Eles têm algumas vantagens de design. Neste artigo, tentarei explicar o porquê.

Vou abordar os benefícios, fornecer exemplos e discutir alguns dos problemas que podem surgir ao usar interfaces.



O que há de especial nas interfaces no GO?



. , python, js, ruby. , , . GO TypeScript. .

. , , , .

PHP:



class Human implements Walkable
{
}

class Mountain
{
    public function walkAround(Walkable $walkable) {...}
}


:



$human = new Human();
$mountain = new Mountain();
$mountain.walkAround($human);


GO . , . , .



?





. . . - , . . , .. .



- , . .



.

, . . , :



package auth

import (
   "gitlab.com/excercice_detection/backend"
)

type userRepository interface {
   FindUserByEmail(email string) (backend.User, error)
   AddUser(backend.User) (userID int, err error)
   AddToken(userID int, token string) error
   TokenExists(userID int, token string) bool
}

// Auth  
type Auth struct {
   repository userRepository
   logger     backend.Logger
}

// NewAuth   
func NewAuth(repository userRepository, logger backend.Logger) *Auth {
   return &Auth{repository, logger}
}

// Autentificate    
func (auth Auth) Autentificate(userID int, token string) bool {
   return auth.repository.TokenExists(userID, token)
}


, .



main :



package main

import (
   "gitlab.com/excercice_detection/backend/auth"
   "gitlab.com/excercice_detection/backend/mysql"
)

func main() {
    logger := newLogger()
    userRepository := mysql.NewUserRepository(logger)
    err := userRepository.Connect()
    authService := auth.NewAuth(userRepository, logger)
...


userRepository, , , mysql , . . . .



. , . . , .



, , .





, . , . , , .

, .

. .. . . . , , : , , .





. , . .



:



type userRepositoryMock struct {
   user         backend.User
   findUserErr  error
   addUserError error
   addUserID    int
   addTokenErr  error
   tokenExists  bool
}

func (repository userRepositoryMock) FindUserByEmail(email string) (backend.User, error) {
   return repository.user, repository.findUserErr
}

func (repository userRepositoryMock) AddUser(backend.User) (userID int, err error) {
   return repository.addUserID, repository.addUserError
}

func (repository userRepositoryMock) AddToken(userID int, token string) error {
   return repository.addTokenErr
}

func (repository userRepositoryMock) TokenExists(userID int, token string) bool {
   return repository.tokenExists
}


, , userRepositoryMock userRepositor, , .





, . , , .

. , , , , , .



, , ?



, , , . , GO , . IDE GoLand .



, , . , .



, , ?



. . IDE , , . IDE , .





GO . , — , . , . , .



GO, . . , . GO , , .




All Articles