r/programmerchat • • May 27 '15

What good code habits have you learned from having to deal with the bad code of others?

I feel like a lot of my code style is a reaction to having to deal with heaps of bad code I've had to maintain.

For example, one of my coworkers always seemed to instantiate about 5 different variables, each of which could be returned depending on various if/then/else/try/catch logic. This made it virtually impossible to follow the program flow and debug the method when issues came up.

So I finally got so sick of this that I decided I'd never foist that kind of problem on others. Every method I write now, the first line is <returnType> returnValue = ...

and the only thing that ever gets returned is returnValue.

24 Upvotes

38 comments sorted by

View all comments

Show parent comment

2

u/[deleted] May 28 '15 edited May 28 '15

Out's OK. You shouldn't be using it all the time, because you shouldn't need it very often, but it's the correct solution when you need to return more than one thing and there's not enough of a use case to justify a full-fledged class to encapsulate the return values. (An out parameter on a void method is a definite code smell, though.)

I think multiple out parameters is a bit troubling, mostly because, at some point, I'd want to know why you didn't produce a small class or return a Tuple.

If you only need to return one 'thing', use a return type, never an out.

1

u/fosforsvenne May 28 '15

An out parameter on a void method isn't a definite code smell, though.

I never thought about this before, but I guess if a method has a side effect it's better for it to be void with an out parameter than to return a value. The first should make you realize that the method does something else than give you the value while the latter doesn't.

didn't produce a small class or return a Tuple

Oh right, I forgot about tuples. I guess they're cleaner than out. However, in my admittedly non-noteworthy opinion there's no more reason to make structs/classes for a few values than for just one. Having an RGB struct with three values for each color is definitely nicer than three different bytes, but a meter struct with one value is also nicer than just a double.

1

u/[deleted] May 28 '15

I guess if a method has a side effect it's better for it to be void with an out parameter than to return a value.

... no, it's better to return the value you're returning, and document the side effect. (Sorry, I mistyped: jumbled thoughts lead to jumbled communication.) Out parameters are not a convention for 'this has side effects'.

1

u/fosforsvenne May 28 '15

Out parameters are not a convention for 'this has side effects'.

No, but void is. But maybe it was a stupid idea anyway.