开发者

Can we force a compile-time error when breaking code is introduced using custom attributes?

The question I'm asking pertains to How do you write code whose logic is protected against future additional enumerations?, but has the possibility to be more general.

For simplicity's sake, I will only consider these two answers (1, 2) to that questio开发者_StackOverflow社区n, because I do not want to have to restructure the code too much.

Solution 1 handles the situation by throwing a run-time exception in the default block of switch statement when the switch value is an enum value which is not handled specifically. If this happens during testing, the developer will be prompted to reexamine the code and add handling code for that particular enum value in the switch statement.

Solution 2 does it by using the visitor pattern, so any addition of enum values will create a compile-time if code which use that enum is not updated to reflect the additional value.

Now, both solutions are valid and good. However, I prefer compile-time error over run-time exception in case my code coverage during testing skips that part. Also, it's more natural to write code like solution 1 over solution 2 (too lengthy).

Hence I would like to know if there is a solution that has both the goodness of compile-time error of solution 2 and the simple addition of code in solution 1? Is it possible to write some custom attribute to specify that a particular enum when used in a switch must be checked against all possible enum values in that switch, and for the compiler to complain when this is violated.

[allValuesMustBeCheckedInSwitch]
enum Fruit {Apple, Banana, Coconut}

Fruit aFruit = Fruit.Apple;

switch (aFruit)
{
  case Fruit.Apple:
    //do something
    break;
  case Fruit.Banana:
    //do something
    break;
  default:
    break;
}

It will even be better if I can add something like this to the switch to selectively disable the compiler error (and perhaps change it to a warning).

[checkOnly(Fruit.Apple,Fruit.Banana)]

I said that my question is more general because I would like to know how expressive custom attributes can be, not having used attributes before. This example is just be one particular restriction I would like to define in my code, there could be other different types of restrictions.

If there are other tools which can perform similar tasks, I would like to know about it too.


I'm not sure if it's possible with CodeContracts, but be sure to check that out, maybe it suits your needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜