18.4.17

Golang: please use your interfaces, or don't declare them at all.

In golang an interface can easily be defined improperly.  And because its often the case that a programmer will write code that references a struct rather than an interface, this is easy to go overlooked.  Why?  Because the compiler doesn't allow you to define interface implementations explicitly.  Instead, it extracts them.  So please please please make sure when you define an interface you actually use it.

For example, below, if we delete the calls to Move(c), the code will compile and the subtle bug (which is the fact that Car doesn't implement the right return value for the Move() function) will be overlooked.

The good news: Whats even more subtle here is that there is operator overloading in golang.  So the good news is, the Compiler will flag the Move() function on Car as problematic... So long as you exersize the interface.

In short, Please exercise your interfaces, or don't declare them to begin with.

package main

import (
"fmt"
)

type Transporter interface {
    Move() int
}

type Car struct{

}
type Boat struct{

}

func (c *Car) Move(){
   fmt.Println("vroom!")
}

func (c *Boat) Move() int{
   fmt.Println("vroom!")
   return 0
}

// make sure to declare a function that uses your interface.
func Move(t Transporter){
   x := t.Move()
   fmt.Println(x)
}

func main() {
   fmt.Println("Hello, playground")
    c := &Car{}
    b := &Boat{}
 
    // should not compile, because of the fact that Move is not an interface.
    // its a good think we tried Move(c) on car, otherwise this interface bug would go unchecked.
    Move(c)
    Move(b)
}

No comments:

Post a Comment