Your example code is missing 4 error checks that should additionally be handled.
On Thursday, 1 November 2018 11:17:37 UTC+2, Henry wrote: > > Hi, > > I am concerned with the direction Go2 is going. If anything, Go2 should > reduce and consolidate features from Go1 rather than adding new ones. > Remember that C++ and Java too were once simple languages and people keep > adding stuffs instead of consolidating features. > > About error handling, I prefer the Go1 error handling approach. It is > simple, readable, and scalable. Everything is laid out in plain sight and > there is no hidden alternate execution paths. > > The complaint people have about Go1 approach is the repetitive error > checks. I will use the following code example from another thread > <https://groups.google.com/forum/#!topic/golang-nuts/1McP4_-oOpo> by DrGo. > > func CopyFile(src, dst string) error { > r, err := os.Open(src) > if err != nil { > return fmt.Errorf("copy %s %s: %v", src, dst, err) > } > defer r.Close() > > > w, err := os.Create(dst) > if err != nil { > return fmt.Errorf("copy %s %s: %v", src, dst, err) > } > > > if _, err := io.Copy(w, r); err != nil { > w.Close() > os.Remove(dst) > return fmt.Errorf("copy %s %s: %v", src, dst, err) > } > > > if err := w.Close(); err != nil { > os.Remove(dst) > return fmt.Errorf("copy %s %s: %v", src, dst, err) > } > return nil > } > > Many people are thinking how to reduce the four error checks in the above > example, and they come up with various keywords and ways to reduce those > error checks. However, they are forgetting that CopyFile function itself is > an error-check reduction mechanism. The next person who needs to copy file, > only needs to use the function and handle one error check instead of four. > In addition, you get the benefits of reusability and readability. You gain > all those with simple modularization instead of adding keywords. The > approach is also more flexible and scalable. > > So, the next time you feel you are writing too many error checks, see if > you can refactor those into smaller functions. Even if you can't further > decompose your code, take heart knowing that you only need to write them > once. The next time you need a similar functionality, you just reuse the > function and avoid repeating those error checks. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.