|
|
>> You might also want to assert( trees.size() > 0 ) to make sure the
>> function worked properly and there's something there to return.
>
> The loop right above that is while(trees.size() > 1). Each pass of the
> loop removes two trees and inserts one tree.
It definitely matters less when you're the only one editing the code, but
asserting things like this is still a good habit to get into. I noticed that
the loop had that behavior, but what if:
- The loop didn't work as intended and sometimes, for instance, broke out
before inserting the new element?
- The loop works right, but at a later date you change it for some
unrelated reason and break it in a subtle way?
- trees.size() is 0 in the first place? This could happen if an empty
vector was passed in.
The alternative to adding an assert is a small risk that at some point in
the future you'll spend hours tracking down a crash. The more asserts you
use, the more time you'll save! It takes time to learn where to add them,
and I admit I went for years without using a single one. Once you start to
use them consistently, you can be surprised at how frequently you see them
fail, and you learn more about your own potential to make mistakes.
By the way, I wouldn't have recommended adding that assert if the loop were
while( trees.size() != 1 ), since that would make the assert perfectly
redundant. Of course in that case, I would assert that trees.size() >= 1
before the loop to make sure the loop could work properly.
- Slime
[ http://www.slimeland.com/ ]
Post a reply to this message
|
|