Chapter06 - pslpune/golang-jumpstart GitHub Wiki

Methods

Lets consider the case of sensors attached to a single board computing device. Such sensors are then expected to be setup, calibrated and tested before they are sent into a continuous loop to measure the physical phenomenon.

type DHT11 struct {

}
type MQ135 struct{

}

func SetupDHT11(dht *DHT11, pwr, gnd, op int) error {
    // Setup the pins here
}
func SetupMQ135(dht *MQ135, pwr, gnd, op int) error {
    // Setup the pins here
}
func Setup() error {
    // settinup would mean we have to call individual methods as follows
    if err :=SetupDHT11(&DHT11{}, 1,6, 26); err !=nil{
        return fmt.Errorf("failed to instantiate DHT11 sensor, this might take some hw reconfig")
    }
     if err :=SetupMQ135(&MQ135{}, 1,6, 26); err !=nil{
        return fmt.Errorf("failed to instantiate MQ135 sensor, this might take some hw reconfig")
    }
}

As you can notice everytime there would be a new sensor we would have to write a method along with it. A method thats specific to the setup of the sensor. Such methods differ only in the implementation, in that they are calling different object instances everytime. Im tempted to write a single method like so ..

type DHT11 struct {

}
type MQ135 struct{

}
func SensorSetup(sensor interface{}, pwr, gnd, op int) error {
    // Setup the pins here
    if dht, ok := sensor.(*DHT11); ok {
        // do what it takes to setup DHT11
        return nil
    } else if mq135, ok := sensor.(*MQ135); ok{
        // do what it takes to setup MQ135
        return nil
    }
    return fmt.Errorf("invalid type of sensro, cannot setup")
}
func Setup() error {
    // settinup would mean we have to call individual methods as follows
    if err :=SensorSetup(&DHT11{}, 1,6, 26); err !=nil{
        return fmt.Errorf("failed to instantiate DHT11 sensor, this might take some hw reconfig")
    }
     if err :=SensorSetup(&MQ135{}, 1,6, 26); err !=nil{
        return fmt.Errorf("failed to instantiate MQ135 sensor, this might take some hw reconfig")
    }
}

We are just displacing the object casting from Setup to SensorSetup, with ofcourse the extra step of having an interface{} param. The if-else loop is just a variation of what we had done previously in Setup. Just that Setup has now become agnostic of which sensor;s Setup is being run.

There has to be some way we should be able to call sensor.Setup() and it would then polymorphically run the setup as intended (object instance in the memory)