iface
is a linter designed to identify the incorrect use of interfaces in Go code, helping developers avoid interface pollution. By detecting unnecessary or poorly implemented interfaces, iface
ensures your Go code remains clean, efficient, and maintainable.
It consists of several analyzers:
unused
: Identifies interfaces that are not used anywhere in the same package where the interface is defined.identical
: Identifies interfaces in the same package with identical methods or constraints.opaque
: Identifies functions that return interfaces, but the actual returned value is always a single concrete implementation.
To install the linter which has all the checks:
go install github.com/uudashr/iface/cmd/ifacecheck@latest
To install individual linter, use the following command:
go install github.com/uudashr/iface/unused/cmd/unusediface@latest
go install github.com/uudashr/iface/duplicate/cmd/duplicateiface@latest
go install github.com/uudashr/iface/opaque/cmd/opaqueiface@latest
Run the linter
ifacecheck ./...
or show the help
ifacecheck help
# or
ifacecheck help <analyzer-name>
We encourage to use default behavior and put effot to follow the rules. But, for some reason rules are not applicable. Due to this we can exclude specific package to be scanned by the analyzers. Use -unused.exclude
flag and currently only unused
has this feature. See help for more information:
Example usage:
ifacecheck -unused.exclude=github.com/example/log ./...
Exclusion can be done by using directive in the code by placing the //iface:ignore
to ignore the code from being scanned by the analyzer. Example:
iface:ignore
to ignore the from all analyzers.iface:ignore=[analyzer names]
which names is comma separators to exclude from defined names only. Ex:iface:ignore=unused
ignore fromunused
analyzer.iface:ignore=unused,identical
ignore fromunused
andidentical
analyzers.
Note: use exclusion with careful consideration.
One of Go's powerful features is interfaces. However, sometimes people misuse the interfaces event though the code works but the code polluted with interfaces.
The following quotes inspired the creation of these analyzers:
"Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values. The implementing package should return concrete (usually pointer or struct) types: that way, new methods can be added to implementations without requiring extensive refactoring."
"Don’t export any interfaces until you have to."
"The use of interfaces when they are not necessary is called interface pollution."
"Go interfaces generally belong in the package that consumes values of the interface type, not a package that implements the interface type."