Over the years I have come to the conclusion when working
with switch statements that switches on enum values, a DEFAULT block MUST be
required. Not only should it be
required, I think it should throw a developer exception.
*** NOTE ***
My stance on this is ONLY in scenarios where the switch statement is the
primary pathway. If the switch is for
secondary actions, this may not be needed.
*** NOTE ***
Too many times odd/weird bugs have cropped up in code
because a new enum value was added to the enum
and the switch block did not handle it correctly and the code get all
fooed up.
Why should it be required?
- Enforces tight
code
How does it enforce tight code, but failing if all conditions are not met. By adding the default block, all new enums values will be handled and an exception
will be thrown. This exception will notify
the developer that a new case needs to be taken into account.
- Makes the developers immediately aware of
changes that may affect their code
By adding the default block developers will immediately become aware when a
new enum value is added. This should be
caught early on and handled, so in reality it SHOULD never be exposed
in production.
Possible scenarios where this should NOT be required
- When there is already a default statement
in used for business reasons
If the case statement already has a default block for some valid business
reason, then of course you cannot have it throw an exception.
- When the switch statement is NOT the
primary pathway.
If the switch statement only performs secondary actions, there may not be a need to have the default
block. You should look at this closely….
Enum Defined
Usage 1 – Wrong in my opinion
Usage 2 – Correct in my opinion
The point of this post is to get you to code for failures in
order to succeed. You may not agree with
my stance, but I bet if you give it a try you will find you will have less
errors when enum values are added and you will be happier in the long run.
Posted
06-26-2007 7:08 AM
by
Derik Whittaker