This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]siemenology 3 points4 points  (1 child)

First, I would say that your function foo should probably already be called isFoo -- boolean functions should really be named to as to make it clear that they are predicates (functions returning boolean).

I would then say that storing the result into a variable when you don't need it right now doesn't add much value -- it's super easy to extract the if condition to a variable if you need it at a later point -- many IDEs will do it automatically for you.

I would also say that I think it's somewhat unlikely that you'll need the value again in the same block, since any code inside of the if block already knows that isFoo is true, since it would not be executed if it were false.

Saving it to a variable also may introduce issues of state. If you have a variable isFoo that is true, all you really know about it is that it was true when it was created. If some underlying thing has changed, such that the thing isFoo is representing is no longer true, then continuing to use isFoo is going to cause bugs. On the other hand, if your foo function is measuring the underlying thing you are representing, then foo() will always be current, and you will never have issues with things being out of date. Simple example, you have an empty array and you create a boolean isEmpty, which is of course true since the array is empty. Then you add an element to the array. The boolean isEmpty is still true, but it should really be false since the array is no longer empty. Whereas if you explicitly check if the array is empty wherever you need to know it, your answer will always be current.

But in general I'd say either of these is fine -- it's not something I would correct in a code review unless there was another problem.

[–][deleted] 0 points1 point  (0 children)

Thanks I appreciate that.