列挙値に基づく単純なswitchステートメントを使用してコードを記述しています。将来、開発者が新しい値を追加する可能性があることに気付いたので、実行時にこれをキャプチャして例外をスローするデフォルトのメソッドを含めました。ただし、このようなロジックを挿入するたびにこれを実行する必要があり、コンパイル時ではなく実行時にのみこのような問題が発生することに気付きました。
列挙型自体にコメントを追加するだけでなく、列挙型の値を更新する場合に特定のメソッドを更新する必要があることをコンパイラーに通知させるために追加できるコードがあるかどうか疑問に思っていますか?
たとえば(以下の例は純粋に理論的なものです。開発ライフサイクルからステータスを選択して、ほとんどの人に馴染みのあるものにするようにしました)。
public enum DevelopmentStatusEnum
{
Development
//, QA //this may be added at some point in the future (or any other status could be)
, SIT
, UAT
, Production
}
public class Example
{
public void ExampleMethod(DevelopmentStatusEnum status)
{
switch (status)
{
case DevelopmentStatusEnum.Development: DoSomething(); break;
case DevelopmentStatusEnum.SIT: DoSomething(); break;
case DevelopmentStatusEnum.UAT: DoSomething(); break;
case DevelopmentStatusEnum.Production: DoSomething(); break;
default: throw new StupidProgrammerException(); //I'd like the compiler to ensure that this line never runs, even if a programmer edits the values available to the enum, alerting the program to add a new case statement for the new enum value
}
}
public void DoSomething() { }
}
public class StupidProgrammerException: InvalidOperationException { }
これは少しアカデミックですが、アプリを堅牢にするのに役立つと思います。誰かがこれを以前に試したことがありますか/これがどのように達成されるかについて何か良いアイデアがありますか?
前もって感謝します、
JB