1
\$\begingroup\$

Github repo

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)
}
asked Jun 16, 2021 at 11:05
\$\endgroup\$
1
  • 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\$ Commented Jul 6, 2021 at 6:47

1 Answer 1

2
\$\begingroup\$

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)
 }
}
answered Jul 5, 2021 at 17:32
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.