Reputation: 160
Im creating an app with a large amount of if/else statements. Also the if/else statements contains a randomnumber where for example an if statement can contain several options. Can I use a NSDictionary for this type of blocks or is there at least some way to put it in a seperate file to "clean" up the mainViewController? The if/else statement chunk of code comes back in two parts of my mainViewController. Anyway, this is a small part of the code:
if ([newCondition.number floatValue] >= 15.0f) {
if (randomNumber == 1){
[mainLabel setText:@"THIS IS"];
[label1 setText:@"ONE"];
[label2 setText:@"WAY TO GO"];
} else {
[mainLabel setText:@"THIS IS"];
[label1 setText:@"THE RIGHT"];
[label2 setText:@"WAY TO DO IT"]; }
} else if ([newCondition.number floatValue] <=1.0f && [newCondition.anothernumber
floatValue] >= 90.0f) {
if (randomNumber == 0) {
[mainLabel setText:@"THIS ISN´T"];
[label1 setText:@"GOOD"];
[label2 setText:@""];
} else {
[mainLabel setText:@"ARE"];
[label1 setText:@"YOU"];
[label2 setText:@"DONE?"]; }
} else if ([newCondition.number floatValue] >=30.0f && [newsCondition.anothernumber
floatValue] >= 80.0f) {
[mainLabel setText:@"CAN"];
[label1 setText:@"YOU"];
[label2 setText:@"STOP?"];
Upvotes: 1
Views: 5591
Reputation: 3369
First off, good job noticing that large if/else statements are not a positive thing. There are a lot of ways to make them less painful and easier to read, some of which you've touched on. For example, you could move this to another class (as you said), or at the very least another method to isolate them from the rest of your code.
One design pattern that I've found helpful in this situation is the chain-of-responsibility pattern. In the CoR pattern, you have a number of command objects that are responsible for knowing if they can handle a particular value. So in your case, you'd have a command object for each if/else in your logic, and each command object would know if they can handle newCondition.number. If the command object can handle the value, it performs its' logic (in your case, it'd perform the stuff inside the if/else); if it cannot, it passes the message along to the next object in the chain.
This has the benefit of isolating the logic and making it easier to add functionality with minimal impact. You can also name the command subclasses something interesting and informative to remove some of the mystique of the code.
At the very least, I'd refactor the if statement into its own method. And if you have lots of if/else statements, I'd consider the chain-of-responsibility pattern.
There is a great book called Refactoring to Patterns that I highly recommend.
Upvotes: 4