Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice - HashMap instead of list of parameters, good idea ?

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?

like image 334
Jako Avatar asked May 22 '12 20:05

Jako


People also ask

Why is HashMap faster than list?

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.

How can HashMap be made more efficient?

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.

In what scenario should a programmer choose to use a HashMap?

The hash map is used whenever data is stored as key-value pairs, where values can be added, retrieved, and deleted using keys.

Is HashMap better than Map?

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.


1 Answers

When I encounter situations like this, I tend to create a Params class, and pass that around. The benefits are that:

  • unlike when using a Map, you can have meaningful getters/settings, proper validation etc;
  • it's type-safe and self-describing (meaning it's easy to find out the available parameters and their types).
  • you can add new parameters without having to refactor any intermediate layers.
like image 93
NPE Avatar answered Nov 03 '22 16:11

NPE