3 ms·
It's a balance between readability meaning 'short, and concise' and readability meaning 'very clear, even if that requires being overly verbose'. return (d
by deckiedan 11y ago
It's a balance between readability meaning 'short, and concise' and readability meaning 'very clear, even if that requires being overly verbose'.
return (data.name !== '' ?: 'New Data')
or Python style:
return (data.name if data.name else 'New Data')
vs:
if (data.name != '') {
return data.name
} else {
return 'New Data'
}
The former being much more concise, so that you can display (and grok, perhaps) a single function in 3 or 4 lines, vs the Go style, which can result in extremely long functions (long because they do a few things, and require error checks before and after each one, and so on, rather than being long for actually doing a lot).
The single line version implies at the beginning that all the line does is return. The longer version requires you to read the whole paragraph to figure out what it does.
- jlebrech 11y agoextra long functions promotes breaking them down into smaller functions.
- deckiedan 11y agoOf course - absolutely. No-one disputes that (seriously). The difference ends up being between a 5 line function, which does 5 simple things, and a 20 line function that does 5 simple things. In my previous example, it was 1 line which returned either the name, or 'New Name', or else 5 lines to do the same. In the end, not a big deal. A matter of taste, rather than judgement, I feel.
- sagichmal 11y ago> if (data.name != "") { > return data.name > } else { > return "New Data" > } Not exactly... if data.name != "" { return data.name } return "New Data" And consider the likely context... func name(ref int64) string { data, ok := get(ref) if !ok { return "No Data" } if !data.valid { return "Invalid Data" } if data.name == "" { return "New Data" } return data.name } Straightforward and unambiguous.
- vorg 11y agoDoesn't compile though. You'll need lots of extra lines just to see an output, which is really much of what the posted article was talking about with its wandering-eyed gopher tale... package main import "fmt" func main(){ fmt.Println(name(28)) } type T struct{name string; valid bool} func get(ref int64) (T, bool) { return T{"abc", true}, false } func name(ref int64) string { switch data, ok := get(ref); true { case !ok: return "No Data" case !data.valid: return "Invalid Data" case data.name == "": return "New Data" default: return data.name } }