How complex should code be?

danmine picture danmine · Jan 16, 2009 · Viewed 9.3k times · Source

I'm studying about algorithms which can help me write smaller but more complex code. Instead of writing 150 lines of if-else statements, I can design an algorithm that does it in 20 lines. The problem is a lot of these algorithms can be complex and require a lot of math to understand them. I'm also the only one around here who understands them.

For maintainability of the code, would it be better to just write code like everyone else does, or is it better to use the algorithms?

Answer

Eclipse picture Eclipse · Jan 16, 2009

As Einstein said:

Make everything as simple as possible, but not simpler.

It applies to code as well as to physics.

Use your judgement - will it get easier to maintain? Often by reducing large if/else messes into something smaller you remove corner cases that didn't need to be there, preventing bugs that may have popped-up in the future. Of course by reducing a clear set of conditions into an obscure twist of boolean logic that only happens to work, you may be making things much more difficult to maintain when something changes.

EDIT:
With the case you cited, if the formula is going to work, then it's probably the better option - you can even leave a comment citing the source. It's entirely possible though, that the formula was there before, but was dropped to allow a specific case to be worked around. This is the sort of thing comments in your versioning repository should help with.

Since no one's posted a link yet, here's a description of the PID algorithm he's referring to.