|The problem with using
switch statements to control behavior is this: when you want to add a new type of block, you have to hunt down every
switch statement that requires a new
case label. That's why using virtual methods is preferable. You just invoke the virtual method, and each different type of block provides the code that would otherwise have gone with a
It can sometimes be hard to define the interface for a virtual method. For those situations, you can invoke a virtual
type method that returns a block's type, which you can then use in a
switch statement after all. But if you find yourself doing this often, it can mean that your methods are too big and should be broken into smaller pieces that would make it easier to delegate most of what they do to virtual methods instead.
It's annoying to have to define a virtual method and override it in all the necessary places. The "code it now!" approach is to just write a
switch statement. But in a large program, the time needed to add virtual methods will be more than recovered because the resulting code will be easier to maintain and evolve.