Here are the conditions:
1. When ActiveOnly flag is true, then only add items that are active.
2. When ActiveOnly flag is false, add all items.
Ok, I know it seems simple, and it was very easy to write this as an if statement. This is what I started with:
...
if(activeOnly)
{
if(item.IsActive){
dropdown.Items.Add(item.Name);
}
} else {
dropdown.Items.Add(item.Name);
}
...
Ok that gets the job done, but it doesn't look very elegant, and I've repeated my insert code twice.
After looking at this a while, I decided that there had to be a better way to write that code, so I did a classic truth table:
ACTIVE
ONLY -------------
ACTIVE | T | F |
-------------
| T | T |
-------------
Basically indicating to me that the only time that I DON'T want to write a value is when ONLYACTIVE = true AND ACTIVE = false.
At this point this is starting to look like an opportunity for a specification pattern but I'm trying to just get the job done AND I didn't want to over kill it. Thinking in terms of specifications does shed light on how we should think about this test. If the ONLY time we DON'T write a value is when ONLYACTIVE = true AND ACTIVE = false, then shouldn't we TEST to see if this CONDITION is TRUE?
This is the final if statement result:
...
if(!(activeOnly && !item.IsActive)){
dropdown.Items.Add(item.Name);
}
...
Now isn't that less smelly??
No comments:
Post a Comment