Var-Arg DAO Finders
Tuesday, 8. August 2006, 13:21:39
- findByNameAndFamilyName
- findByPositionAndDepartment
- findByMonthAndCategoryAndTitle
- findByBlahBlahDamnBlahBlahAndGodDamnBlahBlah
This has always been distracting to me. Once I see a class with such stupid method names, I try my best to keep myself away from it. I DON'T LIKE LENGTHY METHOD NAMES! I DON'T LIKE METHODS WITH LARGE NUMBER OF ARGUMENTS (unless, well continue reading...!) It's the sign of a bad design. It might be an inherent weakness of the host language, but that doesn't solve anything. Some languages support named arguments which is just fine and pleasant to work with:
- find(name: "James" familyName: "Gosling")
However, the declarations still remain just as lengthy. But thanks to variable length arguments introduced in Java 5, it's very easy to write finder methods that not only are concise to declare and invoke, but also more generic and flexible. The idea is to pass a comma separated list of arguments as a string followed by the arguments themselves:
- find ("name, familyName", "James", "Gosling")
This even eliminates the need to have more than one equity-based finder method in your DAOs. A negative side-effect is the loss of type-safety, but I belive, overall, it won't hurt that much and is neglectible.
In a follow-up post, I'll provide a simple JDBC DAO implementation as well as a more flexible finder that not only supports equity comparision, but also LIKE, between, less than, greater than, and more operators as well.
Neat! Izhn't dish jusht sho shibit?