DEV Community

Discussion on: [Go] unusual: move "if err !=nil" into struct methods

Collapse
 
andreidascalu profile image
Andrei Dascalu

So, to sum up:

  • it doesn't reduce the err!=nil checks
  • you say it makes code clearer but I disagree since it hides the error handling AND you will be doing a number of pointless checks (you have an error, deal with it or return and stop the flow - but in this case your code keeps checking the error pointlessly) which isn't apparent by looking at it
  • you are binding together not just data with functions but functions between themselves. I can't think of a situation where that's desirable (though I guess it can shorten the parameter count in some situation at the cost of always having at least one pointer in play)
Collapse
 
julianchu profile image
Julian-Chu

Hi Andrei,
thanks for comments. Yes, l also write in the end, this way doesn't reduce lines of err check , only move the err check to methods. maybe I should find a better title..

For second, you're right it have pointless checks. IMHO I think it a tradeoff, the pointless check almost costs nothing and no performance impact, if it can reduce the err check code in the higher level code block, maybe worth.

For binding functions, I think I won't do this way for functions as well, only by methods in one struct which may share states.

Collapse
 
andreidascalu profile image
Andrei Dascalu

Well, that's not quite so. If it were only the if checks, it wouldn't be much overhead if you don't overdo it, but we're also talking about calling functions unnecessarily. When you call a function, there are all sorts of allocations happening and garbage collection. There's an overhead to function calls beyond whether they run their full code or not. You should run a profiler test.

There's another bit. When checking on demand, you may have a reusable err variable that only ever holds nil in happy case an at most one error which is collected at the end of function call.

I'm you case you have a full error allocated regardless of usage. Even in the happy case you have an error that's only garbage collected when the whole program ends.

Of course, the last point is also a nitpick in that it's not idiomatic.