5 ms·
I don't have a SE account so I'm going to provide the answer he's searching for to get out of the switch statement: dynamic object construction. He's got code
by gspencley 5y ago
I don't have a SE account so I'm going to provide the answer he's searching for to get out of the switch statement: dynamic object construction.
He's got code that looks like this:
switch(type) {
case BidPrice:
case BidSize:
MatchSellOrders();
The solution to ditching the switch statement is to create small classes whose names and locations conform to a convention so they can be inferred from the type value:
class BidPriceOrders : MatchSellOrders {}
class BidSizeOrders : MatchSellOrders {}
The corollary to switch statements is "primitive obsession" and that's the name for the code smell that includes enums. An enum doesn't have behaviour. It's just primitive data with an expressive symbol and namespace. The switch exists to couple behaviour to the symbol, both of which exist independently of each other because of poor design. The basic idea of OOP is all about grouping data with the methods that operate on it so that they live and evolve together as objects.
A switch is a middleman that has to understand the type and the behaviour as things that live and evolve separately. It's a point of coupling that needs to be maintained independently of the data and methods. In other words: it's superfluous code; unnecessary complexity that any code-base would benefit from not having to deal with.
So the idea is to replace the enum with an object without having to introduce the switch. He's right that you need a factory, but he's wrong that you need a switch statement to implement the factory. You can also just stick a static "factory method" on the abstract base class that defines the generic object type to keep the code / overhead as low as possible. The pseudo-code implementation is:
abstract class BidType {
static create(typeFlag: BigTypeFlag): BidType {
const className = `${BidTypeClassPath}/${typeFlag}Orders`;
if(!notExists(className)) {
throw new IllegalArgumentException('Unsupported bid type');
}
return new className();
}
}
const bidType = BigType::create(typeFlag);
Every language will have a different mechanism that allows you to dynamically instantiate an object but that's the basic idea.
- bouke 5y agoBut now you have traded compile-time safety for a runtime error whenever the api changes. I’d prefer the switch in this case.