Hi Stackoverflow community,
I am working on some code where a list of optional criterias criterias is submitted to my dao. Method signature contains the list of +/- 10 parameters, which I really don't like and want to reformat. Plus I would like to avoid having to refactor all method signatures from different layers just because I add/remove a criteria
List searchParams(String name, Long countryCode, ...){
...
}
would become
List searchParams(HashMap<String,Object> map) {
BeanUtils.populate(this,map);
...
}
I am a bit worried that this happen to because kind of a bad practice, because I give up control of what is passed in the map to give me that flexibility ? So my question is if I am on the right path proceeding that way?
The ArrayList has O(n) performance for every search, so for n searches its performance is O(n^2). The HashMap has O(1) performance for every search (on average), so for n searches its performance will be O(n). While the HashMap will be slower at first and take more memory, it will be faster for large values of n.
Use wrappers for composite HashMap keys Whenever a HashMap has composite String keys, use a wrapper instead of concatenating the strings to make a key. Doing so will make the lookup much faster and reduce allocation rate, as the benchmark below demonstrates.
The hash map is used whenever data is stored as key-value pairs, where values can be added, retrieved, and deleted using keys.
HashMap is faster than Map since it does not keep track of the order in which its components are inserted. HashMap, unlike Map, can hold duplicate values. It's feasible to use the Map interface implementing classes to implement it. HashMap, on the other hand, is all about implementing the Map interface.
When I encounter situations like this, I tend to create a Params
class, and pass that around. The benefits are that:
Map
, you can have meaningful getters/settings, proper validation etc;If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With