Ryan's profileCeiled's stuffPhotosBlogListsMore ![]() | Help |
|
May 06 Or ifRecently I was working on something, and I found myself using a construct that looked like this:
if (ConditionA)
{
DoSomething();
DoSomethingElse();
}
if (ConditionB)
{
DoSomethingElse();
}
Now, the real intention of this code was that that DoSomething() should be run if ConditionA was met, and DoSomethingElse() should be run if either ConditionA or ConditionB was met. There are two things I don't like about this code: DoSomethingElse() needs to be specified twice, and it doesn't clearly communicate the intent. I feel like there must be a better way to do this. So far, I've come up with two syntaxes that could accomplish this in what I think is a fairly clear fashion. My first instinct was this:
if (ConditionA)
{
DoSomething();
}
or if (ConditionB)
{
DoSomethingElse();
}
I like that this is a nice, orthogonal extension of existing syntax. I also like that it eliminates the duplication from the original construct and doesn't require any extra code. I don't like that it doesn't clearly communicate the relationship between the two blocks. My second idea addresses this:
switch
{
case ConditionA:
DoSomething();
fallthrough;
case ConditionB:
DoSomethingElse();
}
The basic idea of this one is that a switch statement with no expression would interpret its case labels as expressions instead of simple labels, and would jump to the first one to evaluate as true. Then you can use fallthrough (note the explicit fallthrough statement, which is another wishlist item of mine -- perhaps I'll explain the thinking behind it in a future post) to execute both statements if both are true or just the second one if the second one is true. This solution eliminates the duplication and adds only a couple lines of code, but I can't decide which is a bigger departure from the expectations set by C#: executing more than one in a series of if blocks, or interpreting case statements as expressions. Any thoughts? Trackbacks (1)The trackback URL for this entry is: http://ceiled.spaces.live.com/blog/cns!FDEE70107FF2676B!137.trak Weblogs that reference this entry
|
|
|