Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garrus/5b1f73a7640726c92273700eabed9056 to your computer and use it in GitHub Desktop.
Save garrus/5b1f73a7640726c92273700eabed9056 to your computer and use it in GitHub Desktop.
Another style of syntactic sugar on error handling

The check/handle keywords introduced to improve code style is a good effort, though doesn't help very much on the looking of golang source code. Before it, we see a lot of lines leading by if err != nil, after that we'll see a lot of lines leading by check.

How about we try another style, to put keyword AFTER a function call, just like below:

func CopyFile(src, dist string) error {

	on checked err {
		return fmt.Errorf("")
	}
	
	r := os.Open(src) checked
	defer r.Close()
	
	w := os.Create(dist) on err {
		w.Close()
		os.Remove(dist)
	}

	io.Copy(w, r) checked
	w.Close() checked
	
	return nil	
}

At least we don't have to see so many error-handling-related keywords at the beginning, which makes code look much cleaner. checked is more like a mark rather than an operator or directive. We'll get less distracted by a tailing mark when reading code.

Also, this style is better for code auto-completion experience. When we type a function call and press enter, IDE will check if a checked should be auto appended. What's important is, auto appending by IDE is better then prepending or even inserting something right into the middle, for human sense.

Syntax coloring can also help. When checked is renderred in a low contrast color (just to make it less distractive), the code still looks aligned. A LEADING check is never able to do that, is it?

@deefdragon
Copy link

A large downside with placing the keyword at the end that I can see is that for longer function calls, or multi-line calls for example, it becomes more difficult to determine what has been checked and what has not. Especially editing with a more limited editor width or height, as may be common when editing multiple files.

The other possible problem with this is that most common keywords are pre-ending. func, var, range, if, for, type etc. and it might be strange to suddenly add a post-ending keyword.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment