java - What is this design (or anti-) pattern and more importantly is there a better way? -
i'm receiving webservice list of key-value pairs, , have inherited following code:
public string iconvalue = null; ... (over 50 class variables assigned in myobject constructor below) public myobject(list<attribute> attrs) { string attrname, attrvalue; (attribute : attrs) { try { attrname = a.getname(); attrvalue = a.getvalue(); if (attrvalue == null || "".equals(attrvalue.trim())) continue; if (icons.equals(attrname)) { //do including assignment this.iconvalue = attrvalue; } else if (url.equals(attrname)) { //do including assignment } else if (...) giant list of on 50 different attributes hardcoded { //do including assignment } ...
so,except keeping hashmap - there better way above keep hard coded variables within class , use "when-if" pattern.
also,does pattern have name?
one way can think use enum
s , dynamically dispatch works each of enum
object, instead of doing huge if else, esp. since enum
s can looked names.
that strategy pattern.
for example:
- implement
enum
have methoddojob()
each of instances; - use
valueof()
method dispatch works.
code sample:
public enum strategies { url { @override public void dojob(myobject mo) { // work } }, icons { @override public void dojob(myobject mo) { // work } }; public abstract void dojob(myobject mo); }
and when using it,
try { strategies.valueof(attrname).dojob(); } catch (illegalargumentexception e) { // enum not exist, illegal parameter }