Tuesday, June 2, 2009

Vector to HashMap pattern

motivation: i recently discovered a bug via vector which resulted in the validation incorrectly checked.

Some Action

Vector v = new Vector();

v.add(request.getParameter("name"));
v.add(request.getParameter("address"));
v.add(request.getParameter("telephone"));

Some Manager

v.get(0);
v.get(1);
v.get(2);

can be replaced with

HashMap hm = new HashMap();

hm.add("name",request.getParameter("name"));
hm.add("address",request.getParameter("address"));
hm.add("telephone", request.getParameter("telephone"));

later on

hm.get("name");
hm.get("address");
hm.get("telephone");

this is much less error prone then refering via vector indexes. you can add new parameters without affecting the orders of the parameters also. String should be extracted out into a constants class to obey the principles of DRY.

No comments:

Post a Comment