'Good practice / design pattern to resolve the nested if else?
Currently I have code like this:
for (each item) {
if (item == 'x') {
print
}
if (item == 'y') {
print
}
}
Now, there is an additional requirement - I want the same checks but instead of printing, I need to insert in DB.
ie
for (each item) {
if (item == 'x') {
insertDB
}
if (item == 'y') {
insertDB
}
}
This has duplicated code, so flags come to my thought.
for (each item) {
if (item == 'x') {
if (insertDB) {
insertDB
} else {
print
}
}
if (item == 'y') {
if (insertDB) {
insertDB
} else {
print
}
}
}
This has clearly caused a lot of if-else clutter. My Object oriented programming tells me a new idea.
for (each item) {
if (item == 'x') {
obj.doItemXAction();
}
if (item == 'y') {
obj.doItemXAction();
}
}
Object obj = new PrintObj();
Object obj = new DBInsertObj();
Code looks much cleaner. But, given what I could think off, can anyone point me to exact design pattern which deals in situations like this?
Solution 1:[1]
A simpler example of polymorphism:
public interface Actionable {
void doItemAction();
}
public class Item implements Actionable {
@Override
public void doItemAction() {
// insert or print
}
}
public static void main(Actionable... args) {
for (Actionable item : args) {
item.doItemAction();
}
}
You might take it a step further and extend Actionable
with Insertable
and Printable
.
Solution 2:[2]
There are so many ways that you can do. It's really depending on how you wanna organize your code. There are more than one good ways. If I give you vague short answers, "Abstraction", "Polymorphism", "Separation of concerns", etc. Here is one example, no if/else is required:
interface AnimalBehavior {
void eat();
void drink();
}
abstract class Animal implements AnimalBehavior {
abstract void eat();
abstract void drink();
}
class Bear extends Animal {
void eat() {
// bear eats cookies
}
void drink() {
// bear drinks juice
}
}
class Chicken extends Animal {
void eat() {
// chicken eats candy
}
void drink() {
// chicken drinks soda
}
}
class AnimalStats {
main () {
Animal chicken1 = new Chicken();
Animal chicken2 = new Chicken();
Animal bear1 = new Bear();
Animal bear2 = new Bear();
List<Animal> animals = Arrays.asList(chicken1, chicken2, bear1, bear2);
for(Animal animal: animals) {
animal.eat();
animal.drink();
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jaco0646 |
Solution 2 | Tin |