JavaScript newbie here, I was going through some js code at work when i came across a helper function for object creation, which went like this
createElement = function(name, data){
if(name == TYPES.TEXT){
return new Text(data);
}
else if(name == TYPES.WORD){
return new Word(data);
}
else if(name == TYPES.PARAGRAPH){
return new Paragraph(data);
}
else if(name == TYPES.TABLE){
return new Table(data);
}
<list goes on and on and on... >
}
while this does get the job done i would like to know if there is a better, cleaner way of writing this.
You’re right, excessive
if..thenorswitchlogic is a code smell and can almost always be refactored into something more elegant. In this case, a factory based upon a name can be refactored into a dictionary with key as that name and value as the function to returnLive example: http://jsfiddle.net/KkMnd/
EDIT: That line in the
createElementmethod could/should first check that something is configured for theTYPES.*passed in. A good way is to check that there is an element in the dictionary before trying to call that method.