Premature Optimization can hold back the release of software, and make it more complicated to debug.
.
Say you already have a function that returns the list of children in a node..
.
But you need a function that brings back only the first child if it exists.
.
1. Do you copy the function and return just the first item when you have it (with the associated code around the function) for efficiency sake.
2. Or.. Call the existing function and return the first item if there is at least one element?
.
1 Will be the best answer if you have a million records to load from disk.
2.Will be the best answer if you only have 20-30 records on average.
.
But 2 is the best answer before debugging, check that the code works properly before duplicating it and modifying it.
Answer 3 would be to add a limit parameter, and call the other two functions with it. That way, if limit=0, return all records. if limit=1, return one record maximum.
.
Sometimes the answer is to think differently about the problem altogether.
To be pedantic, the answer is neither. You use an abstraction that supports either answer with similar ease, provided by the language/framework/tools you used.
You bring up a very real point, but the most obvious cases are also most obvious to the people developing the stack below you and have almost certainly gone through the trouble of solving those problems.
This issue rears its head when edge cases are non-obvious and typically manifest through profiling, not through design meetings.
.
Say you already have a function that returns the list of children in a node..
.
But you need a function that brings back only the first child if it exists.
.
1. Do you copy the function and return just the first item when you have it (with the associated code around the function) for efficiency sake.
2. Or.. Call the existing function and return the first item if there is at least one element?
.
1 Will be the best answer if you have a million records to load from disk.
2.Will be the best answer if you only have 20-30 records on average.
.
But 2 is the best answer before debugging, check that the code works properly before duplicating it and modifying it.
Answer 3 would be to add a limit parameter, and call the other two functions with it. That way, if limit=0, return all records. if limit=1, return one record maximum.
.
Sometimes the answer is to think differently about the problem altogether.