public class Stats {
public int HP;
public int STR;
public int MAG;
public int SPEED;
public int SKILL;
public int DEF;
public int RES;
public int LUCK;
public int WEIGHT;
public int MOV;
public int getStat(String stat) throws InvalidKeyException {
if (stat.equalsIgnoreCase("HP")) {
return HP;
} else if (stat.equalsIgnoreCase("STR")) {
return STR;
} else if (stat.equalsIgnoreCase("MAG")) {
return MAG;
} else if (stat.equalsIgnoreCase("SPEED")) {
return SPEED;
} else if (stat.equalsIgnoreCase("SKILL")) {
return SKILL;
} else if (stat.equalsIgnoreCase("DEF")) {
return DEF;
} else if (stat.equalsIgnoreCase("RES")) {
return RES;
} else if (stat.equalsIgnoreCase("LUCK")) {
return LUCK;
} else if (stat.equalsIgnoreCase("WEIGHT")) {
return WEIGHT;
} else if (stat.equalsIgnoreCase("MOV")) {
return MOV;
}
throw new InvalidKeyException("No Such stat");
}
}
Refactorings
No refactoring yet !
Chris Jester-Young
April 23, 2009, April 23, 2009 01:14, permalink
Use reflection! :-P
public int getStat(String stat) {
try {
Field field = Stats.class.getField(stat.toUpperCase());
return field.getInt(this);
} catch (NoSuchFieldException exc) {
throw new IllegalArgumentException(exc);
} catch (IllegalAccessException exc) {
throw new IllegalArgumentException(exc);
}
}
Chris Jester-Young
April 23, 2009, April 23, 2009 01:18, permalink
Seriously, a better solution is to make an enum type containing all the keys (HP, STR, etc), then look each attribute up using an EnumMap.
import java.util.EnumMap;
import java.util.Map;
public class Stats {
public enum Type {
HP, STR, MAG, SPEED, SKILL, DEF, RES, LUCK, WEIGHT, MOV;
}
private Map<Type, Integer> attrs = new EnumMap<Type, Integer>(Type.class);
public int getStat(Type type) {
if (attrs.containsKey(type))
return attrs.get(type);
throw new IllegalArgumentException(type);
}
public int getStat(String type) {
return getStat(Type.valueOf(type.toUpperCase()));
}
}
staykov.myopenid.com
April 23, 2009, April 23, 2009 02:43, permalink
Wow thanks, Chris, you are awesome
Corey
April 23, 2009, April 23, 2009 18:53, permalink
Hello. That's very nice site but I've seen this before here <a href="http://href.inguaro.com/77a7d63b189e4a2d18ad6ebd535983db/cb8d865fbe44164ad01142de2103e8ba">http://text.inguaro.com/77a7d63b189e4a2d18ad6ebd535983db/cb8d865fbe44164ad01142de2103e8ba</a>
cb8d865fbe44164ad01142de2103e8ba
Hello. That's very nice site but I've seen this before here <a href="http://href.inguaro.com/77a7d63b189e4a2d18ad6ebd535983db/cb8d865fbe44164ad01142de2103e8ba">http://text.inguaro.com/77a7d63b189e4a2d18ad6ebd535983db/cb8d865fbe44164ad01142de2103e8ba</a> cb8d865fbe44164ad01142de2103e8ba
this is the most idiotic code ive ever written. i dont want setters and getters for each stat though. any winnars out there if you could poke at it please.