Does violation of the law of the demetator affect the golang?

This is what Effective GO had to say about investing in golang

When we implement a type, methods of this type become methods of the external type, but when called, the receiver of the method is the internal type, not the external

I had a piece of code where I had Struct Useras below

type User struct {
    Name     string
    Password string
    *sql.Tx
}

And then I call u.Query("some query here"), etc. I did this on purpose to avoid challenges such as u.Transaction.Query("query"), which clearly violates the Law of Demeter. Now, having read the documents and effectively, I doubt the benefits of the first approach. Am I breaking the Law of Demeter? If so, how can I avoid it?

+4
1

, , , . , LoD ( ).

, LoD. - , "" , ; , . , , .

, u.Tx.Query(), : , User *sql.Tx.

: u.Query(), . , *sql.Tx . , *sql.Tx (, "" , User.Query()).

, "" User.Query() , , :

type User struct {
    Name     string
    Password string
    tx       *sql.Tx // regular field, not embedded; and not exported
}

func (u *User) Query(query string, args ...interface{}) (*sql.Rows, error) {
    return u.tx.Query(query, args...)
}

:

, u.Query(), , , , User ( , u.Query() User, : User.Query()).

sql.Tx , , u.Query() . sql.Tx . , , . ( u.Query()), , u.Query(), , -, .

, LoD : u.Query() u.Tx.Query(), User , u.Query() . LoD - . . , , , .

, : LoD API . , , , "" . sql.Tx , Tx.Query() , "" LoD.

+6

Source: https://habr.com/ru/post/1612384/


All Articles