Benefits of interfaces in GO

Benefits of interfaces in GO



In GO, the interfaces are different from other popular programming languages ​​such as Java, C ++, PHP. They have some design advantages. In this article I will try to explain why.

I'll cover the benefits, provide examples, and discuss some of the issues that may arise when using interfaces.



What is special about interfaces in 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