I thought to do away with getters and setters behind the real world objects such as Person, Company or Address, i.e. getName
and setName
.
Each of these have public enum Attrib
of states.
And the state is actually a pure Object
mapped to a private HashMap
.
package model;
import java.util.HashMap;
import java.util.Map;
public class Person {
public enum Attrib {
NAME, //String
EMAIL, //String
PHONE; //int
@Override
public String toString() {
return name().toLowerCase();
}
}
private final Map<Person.Attrib, Object> attribs;
public Person(String name, String email, int phone) {
attribs = new HashMap<>();
attribs.put(Person.Attrib.NAME, name);
attribs.put(Person.Attrib.EMAIL, email);
attribs.put(Person.Attrib.PHONE, phone);
}
public Object getAttrib(Person.Attrib attribute) {
return attribs.get(attribute);
}
public boolean setAttrib(Person.Attrib attribute, Object value) {
if (attribute == Person.Attrib.PHONE && !(value instanceof Integer)) {
return false;
}
attribs.put(attribute, value);
return true;
}
@Override
public boolean equals(Object o) {
if (o instanceof Person) {
Person person = (Person) o;
String _this = (String) this.getAttrib(Person.Attrib.NAME);
String _that = (String) person.getAttrib(Person.Attrib.NAME);
return _this.equalsIgnoreCase(_that);
}
return false;
}
@Override
public int hashCode() {
return attribs.get(Person.Attrib.NAME).hashCode();
}
@Override
public String toString() {
return (String) attribs.get(Person.Attrib.NAME);
}
}
I did saved some getters and setters but I guess it can't justify that all attributes are objects. To check what instanceof
the getAttrib(Person.Attrib attribute)
is, i.e. skim the class source to know whether you deal with a String
or an Integer
or Whatever
, type cast it.
public int phone;
is, IMO, a Very Bad Thing. If you're not doing math with it, use a string, Full Stop. \$\endgroup\$name.toLowerCase()
for theenum Attrib
toString()
method. Horribly inefficient. \$\endgroup\$