Adding complexity by generalising: how far should you go?
Posted
by
marcog
on Programmers
See other posts from Programmers
or by marcog
Published on 2011-01-07T14:03:22Z
Indexed on
2011/01/07
14:58 UTC
Read the original article
Hit count: 298
Reference question: http://stackoverflow.com/questions/4303813/help-with-interview-question
The above question asked to solve a problem for an NxN matrix. While there was an easy solution, I gave a more general solution to solve the more general problem for an NxM matrix. A handful of people commented that this generalisation was bad because it made the solution more complex. One such comment is voted +8.
Putting aside the hard-to-explain voting effects on SO, there are two types of complexity to be considered here:
- Runtime complexity, i.e. how fast does the code run
- Code complexity, i.e. how difficult is the code to read and understand
The question of runtime complexity is something that requires a better understanding of the input data today and what it might look like in the future, taking the various growth factors into account where necessary.
The question of code complexity is the one I'm interested in here. By generalising the solution, we avoid having to rewrite it in the event that the constraints change. However, at the same time it can often result in complicating the code. In the reference question, the code for NxN is easy to understand for any competent programmer, but the NxM case (unless documented well) could easily confuse someone coming across the code for the first time.
So, my question is this: Where should you draw the line between generalising and keeping the code easy to understand?
© Programmers or respective owner