lundi 22 janvier 2018

How to write DRY(dont repeat yourself) and effictive if-statement in golang?

I am newbie to golang. I have following code:

func main() {
    // counts := make(map[string]int)
    files := os.Args[1:]
    if len(files) == 0 {
        counts := make(map[string]int)
        countLines(os.Stdin, counts)
        fmt.Println("os.Stdin")
        printCounts(counts)
    } else {
        for _, arg := range files {
            counts := make(map[string]int)

            f, err := os.Open(arg)
            if err != nil {
                fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
                continue
            }
            countLines(f, counts)
            f.Close()
            // print counts of each file
            printCounts(counts)
        }
    }
}
func printCounts(counts map[string]int) {
    //...
}
func countLines(f *os.File, counts map[string]int){
    //...
}

where i repeat myself in if-else statement by initiating counts dict twice, (counts := make(map[string]int)) both in if and else.

My question is what is the gopher-way of writing this?

Is that better to do the allocation outside the if-else statment with new and do initiation in every block?

Aucun commentaire:

Enregistrer un commentaire