Reputation: 665
I've recently started programming a lot more for my job. While I can normally get the work done, my code doesn't "smell" right to me.
How would I properly refactor something like this:
def functiona()
def functionb()
def functionc()
def functionn()
if (a){
functiona
}
elif (b){
functionb
}
etc, etc, etc,
For some context, I'm ingesting a large XML file which has a contact field for each object, which is formatted differently depending on another property of the object (i.e. agency) and then I've made all of these functions to parse the contact field out.
Upvotes: 2
Views: 7386
Reputation: 119031
The design pattern would be the object state pattern: wiki State_pattern.
In an OO language this would be a set of different classes which each implement the same interface and you create an appropriate instance based on the 'state' and that instance completes all processing until the 'state' changes. Then it's destroyed and a different instance created.
In non-OO languages that could be done with a pointer to a function with a set signature, and the 'state' dictates which out of several functions that pointer points to.
Both of these techniques are very flexible, but generally are harder to follow than a simple if
statement. That said, a massive if
is often error prone due to reader fatigue and code blindness...
Upvotes: 4