I'm an iOS app developer. I got stuck on some refactoring issue while removing bad smells on my code. it's like this.
My project uses a XML data,
<resource>
<item type='textbox' ... />
<item type='checkbox' ... />
<item type='selectbox' ... />
</resource>
and I use it by this code.
Item *item = nil;
for (Element *itemElement in resourceChilds)
{
...
if ([[itemElement valueForAttributeNamed:@"type"] isEqualToString:@"textbox"])
{
item = [[Textbox alloc] initWithProperty:itemAttributes];
...
}
else if ([[itemElement valueForAttributeNamed:@"type"] isEqualToString:@"checkbox"])
{
item = [[Checkbox alloc] initWithProperty:itemAttributes];
...
}
else if ([[itemElement valueForAttributeNamed:@"type"] isEqualToString:@"selectbox"])
{
item = [[Selectbox alloc] initWithProperty:itemAttributes];
...
}
...
}
'Item' class is the super class of 'Textbox', 'Checkbox' and 'Selectbox' classes.
And 'itemAttributes' object is an instance of NSDictionary.
As you can see above through 'initWithProperty:itemAttributes' I already gave the 'type' attribute value into an 'Item' instance. I think it's possible to use this information in the 'Item' instance to specialize it to Textbox or Checkbox or Selectbox.
Is there any way to remove these 'if' statements and refactoring this? Any suggestion are welcome. And I really appreciate it sharing your time for this.
Thanks,
MK