Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I've seen it in professional work. If it's actually a single variable conditional, that's irritating but by itself not worth more than a comment in the PR. However, in practice it's rarely this cut and dry. I usually see conditions expanded like this for clarity reasons. For example, I consider this kosher if it's in some business logic... instead of writing:

> return a && !(b || c) || d;

I've seen (pardon the formatting, I'm typing on my phone):

> if (d) {return true}

> else if (a) {return !(b || c);}

> else {return false}

It's usually a choice to be verbose for clarity.



I think that would be clearer as "return a && !b && !c || d". Also, your second example doesn't directly correspond with the first, because condition 'a' is evaluated first.

The major problem with code that's "overly branchy", as in containing a lot of if/else, is that you're forced to go through each case when trying to understand how it works, and it often proliferates into even more branchy code as someone makes a bugfix (with another if/else) in one of the cases, but neglects to see that a similar if not identical change must be made to some of the others.

In other words, if/else cases like your second example optimise for micro-readability when what's often important in debugging and understanding is macro-readability.


While I get your point, several thoughts:

1. I'm talking about acceptable code, as opposed to "the best choice". There are good reasons to go for verbosity. Depending on the problem domain I might agree with your expansion of the parentheses, but when we get to this type of discussion, usually my overwhelming reaction is "this is bikeshedding," because...

2. If it's "overly branchy" code and you're worried about causing macro-readability issues, the answer is to refactor, not to compress. Modifying inline conditions runs just as much of a risk of becoming inscrutable. You choose between following branches and enumerating binary tables. If it's showing up too many places, you're likely extracting either expression into its own function.

When overly branch code happens, my experience is that the root cause is underthinking/overthinking the method, not taking time to design the right high level abstractions, or as you mentioned a case of too much repeating yourself. Generally, the fixes for those issues don't have that much to do with your choice of boolean expression vs conditional.


  // a b c d
  // * * * 1  true
  // * 1 * 0  false
  // * * 1 0  false
  // 1 0 0 *  true
  // 0 * * 0  false

  if (d)    {return true }
  if (b||c) {return false}
  if (a)    {return true }
  return false


> return d || a && !(b || c);




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: