Video address of this article

1 Go recommended “small interface”

The word “interface” actually translates as a contract. Contracts can be simple or complex, and Go chooses simple.

1) The implementation class implements an interface automatically by implementing all the methods in an interface, not by implementing the implements keyword, as Java implements.
2) The small interface is more flexible to use.

Here are the definitions in the standard library

// $GOROOT/src/builtin/builtin.go
type error interface {
    Error() string
}

// $GOROOT/src/io/io.go
type Reader interface {
    Read(p []byte) (n int, err error)
}

// $GOROOT/src/net/http/server.go
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

type ResponseWriter interface {
    Header() Header
    Write([]byte) (int, error)
    WriteHeader(int)
}
Copy the code

There are only one or two methods of the interface described above, and this small interface is a Go language best practice that has been widely used. This contract is followed both in the standard library and in community projects.

2 Advantages of small interfaces

A) The smaller the interface, the higher the degree of abstraction, the more thorough, and the better accepted by others. In fact, the interface is the same as the reality, and the smallest interface is often empty interface, which is the most extreme case

B) Easy to implement and test small interfaces have fewer methods, generally only one method. To implement this interface, developers need only implement a method or a few methods. Unit testing is especially important because it costs less to verify that your program is buggy.

C) Single responsibility and easy combination.

The Go language recommends a combinatorial approach to writing programs. Go developers typically build new interface types by embedding them into other existing interface types. Official practice tells us that IO.Reader and IO.Writer build IO.

3 Define the following points for small interfaces:

A) Don’t worry about the interface size early on, just abstract it out first. B) After implementing these methods, you will analyze which scenarios are suitable for which methods of which interfaces, and you will try to extract the methods of these interfaces into a small interface. C) Single responsibility, which is a classic theoretical guide in software design patterns, should be followed as much as possible. This will make your code look clean, easy to maintain, and less buggy.