I would like to add a collection of objects to an arrayList ,only if the particular attribute is not null.
I am thinking of extending the ArrayList and implementing the check inside the child class.
One alternate way is to check for the the attribute before putting it in a Arraylist, but that would mean , i will have to scatter the if checks every where if i need to add the objects to the arraylist based on the logic.
I would like to know your thoughts on it … on a second thought is it a overkill ?
Decorator pattern
I would actually recommend wrapping
ArrayListusing well-documented Decorator pattern. You simply wrap yourArrayListwith anotherListimplementation that delegates most of the methods but adds validation logic:Advantages:
Listimplementation, you can add validation toLinkedListor Hibernate-backed persistent lists. You can even think about genericCollectiondecorator to validate any collection.Implementation notes
Despite the implementation remember there are quite a lot of methods you have to remember about while overriding:
add(),addAll(),set(),subList()(?), etc.Also your object must be immutable, otherwise the user can add/set valid object and modify it afterwards to violate the contract.
Good OO design
Finaly I wrote:
but consider:
which is a better design.
Stacking validations
As noted before if you want to stack validations, validating each proprty/apsect in a single, separate class, consider the following idiom:
…and few implementations:
Want to only validate foo?
Want to validate both foo and bar?