I've attempted a backend assignment in Go from geektrust Assignment Link. I'm not sure the code that I have written is idiomatic in the go way. I need some feedback on this code based on its extensibility, proper use of data structures. How can this code be more improved?
Main build function of the project.
package main
import (
"fmt"
"geektrust/commander"
"geektrust/portfolio"
"io/ioutil"
"os"
"time"
)
func main() {
args := os.Args[1:]
inputFile := "input.txt"
if len(args) > 0 {
inputFile = args[0]
}
// read input file
data, err := ioutil.ReadFile(inputFile)
if err != nil {
fmt.Println("Error while reading file", err)
}
// generate commands from input file
commands := commander.GenerateCommands(data)
// generate portfolio from commands
startYear := time.Now().Year()
_ = portfolio.BuildPortfolio(commands, startYear)
}
-
1\$\begingroup\$ The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How do I ask a good question?. \$\endgroup\$BCdotWEB– BCdotWEB2021年07月06日 06:47:56 +00:00Commented Jul 6, 2021 at 6:47
1 Answer 1
I suggest avoid running the commands/build code if you received an error when reading the file. In the case of an error, I would prefer to not let the program continue. Below I used the else
block, but you could also use os.Exit(0)
to quit after an error (just beware that way doesn't run any defers).
Additionally, remove the blank identifier at _ = portfolio...
.
func main() {
args := os.Args[1:]
inputFile := "input.txt"
if len(args) > 0 {
inputFile = args[0]
}
// read input file
data, err := ioutil.ReadFile(inputFile)
if err == nil {
// generate commands from input file
commands := commander.GenerateCommands(data)
// generate portfolio from commands
startYear := time.Now().Year()
portfolio.BuildPortfolio(commands, startYear)
} else {
fmt.Println("Error while reading file", err)
}
}