1

Hopefully Iʼm posting this in the right SX, and Iʼve tagged it correctly.

I have a legacy system that Iʼm making additions to which contains a custom list object.

This list object can contain two types of elements, another list, or an item.

Part of a current task requires that I make an adjustment to the list in such a way as to exclude the addition of items or lists dependent on their type or whether they are in another list of a different or the same type.

An array of items can be passed to the list object, and theyʼre added one at a time in a loop.

I would like to implement the rules as to whether an item can be added to a list as a separate business rules class where I pass the list and item to the rule class and receive a Boolean value back as to whether the item can be added to the list or not. Something along the lines of:

function InsertItems(ArrayOfItems)
    for each item in ArrayOfItems
        if ruler.CanItemBeAddedToList(item, list) then
            add(item)
        end if
    end for
end function

The language used for the legacy system is VB.NET hence the BASIC style of the pseudo-code.

In general terms is it best to have a separate class to hold a rule such as this, or should it be part of the list class or the item class? That said the more I think about it the more I prefer a rule-class to make the decision rather than embedding the decision in the list. I donʼt believe it should be embedded in the item class. Though you can write it nicely e.g.

if item.CanBeAddedTo(list) then
   add(item)
end if

But this effectively means that the item must know about lists, which is not good from a coupling point-of-view. On the other hand should a list know about items especially given that the list is not a generic one?

1 Answer 1

1

From my point of view the method "CanBeAdded" should neither be in the item, nor in a special rulter. It should be in the list itself. Therefore:

if list.CanAdd(item)
    ...
end

The List implementation then should have a set (probably implemented as list) of rules, that define whether an item can be added.

function CanAdd(item) As Boolean
    for each rule in ListOfRules
        if Not(rule.IsFulFilledBy(this, item))
           return False
        end
    end
    return True
end

This allows the system to be open to new rules, without having to be changed (Open/Closed-Principle).

I beg to excuse any syntactical mistakes. I am not very familiar with BASIC style languages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.