vendredi 9 juillet 2021

Design Choice : Returning initialised function or the constructor

This is main package :

package main

import (
    "example.com/test-cf-golang/print_a"
)

// Method 1
/*
func main() {
    A := print_a.Function_Map["A"]
    A.PrintA()
}
*/


// Method 2
func main() {
    a := print_a.Function_Map["A"]
    // Using method 2, hence invoking the constructor
    A := a()
    A.PrintA()
}

And

This is print_a module :

package print_a

import (
    "fmt"
    "log"
)

type Printer interface {
    PrintA()
}

type print_a struct{}

func (c *print_a) PrintA() {
    fmt.Println("A")
}

func NewPrintA() Printer {
    log.Println("In NewPrintA")
    return &print_a{}
}

// Method 1
var Function_Map = map[string]Printer{
    "A": NewPrintA(),
}

// Method 2
var Function_Map = map[string]func() Printer{
    "A": NewPrintA,
}

Now I've a choice in the above Function_Map ( i.e. print_a.Function_Map ) :

Method 1 : Call the function and return &print_a{}

Method 2 : Pass in the Constructor ( as is currently done )

Differences between the two :

Method 1 :

  • As the Function_Map is exported so that will be triggered by the go runtime and hence NewPrintA() will be called, thus printing In NewPrintA and unnecessary creating a struct
  • This would again be triggered when main is run

Method 2 :

  • Nothing is triggered
  • Needs to call the constructor again to get &print_a{}

What Do I Want To Know

I would love to know the implications for both of these in a long term project :

  1. Web API project
  2. CLI project

Also, if there's a reason of when to use either, that would be great.

Thanks.

Aucun commentaire:

Enregistrer un commentaire