-1

I am designing a project where I have to enforce IF, ELSEIF and ELSE conditions on collection of objects.

For example:

public class Box {
    private List<Item> items;
}

I want to define IF ELSE IF, ELSE conditions on grouping of items.

For example:
IF (X=='abc' AND Y=='jkl') ==> get items[0], items[5], items[10]
ELSE IF(X=='abc') ==> get items[7], items[3]

Values for X and Y will be available at the time of reading the Object.

So the process is: one module will build this object with conditions and store them in DB or XML. Another module will pill pick up this data and acts on them.

This is just an example of what I have in my mind.

1 Answers1

3

You can always start with a method on the Box class:

public class Box {
    private List<Item> items;

    public filter(string x, string y) {
        List<Item> filteredItems = new List<Item>();

        if (x == 'abc' && y == 'jkl') {
            filterItems.add(items[0]);
            filterItems.add(items[5]);
            filterItems.add(items[10]);
        }
        else if (x == 'abc') {
            filterItems.add(items[7]);
            filterItems.add(items[3]);
        }
        else {
            filterItems = // copy the items field
        }

        return filterItems;
    }
}

If that isn't sufficient you can utilize the Strategy Pattern to determine the filtering strategy based on the values of x and y at runtime:

public class Box {
    private List<Item> items;

    public static BoxItemFilterStrategy getFilterStrategy(string x, string y) {
        if (x == 'abc' && y == 'jkl') {
            return new BoxItemFilterStrategy1();
        }
        else if (x == 'abc') {
            return new BoxItemFilterStrategy2();
        }

        return new DefaultBoxItemFilterStrategy();
    }

    public List<Item> filter(BoxItemFilterStrategy filterStrategy) {
        return filterStrategy.filter(items);
    }
}

public interface BoxItemFilterStrategy {
    List<Item> filter(List<item> items);
}

public class BoxItemFilterStrategy1 implements BoxItemFilterStrategy {
    public List<Item> filter(List<item> items) {
        // return items 0, 5 and 10
    }
}

public class BoxItemFilterStrategy2 implements BoxItemFilterStrategy {
    public List<Item> filter(List<item> items) {
        // return items 7 and 3
    }
}

public class DefaultBoxItemFilterStrategy implments BoxItemFilterStrategy {
    public List<Item> filter(List<item> items) {
        // return all items
    }
}

And an example usage:

Box box = new Box();
// add items

BoxItemFilterStrategy strategy = Box.getFilterStrategy(x, y);
List<Item> filteredItems = box.filter(strategy);

It all depends on how complex the filtering logic gets.