In: Computer Science
Sometimes when I'm working with a class (usually one that represents a database model), I'll have about 15 different properties on it, usually of different types. These are properties that need to be accessed by the users, as well, so each property will typically need some function like
T getPropertyName();
setPropertyName(T value);
But, it's also extremely valuable for me to be able to iterate through each property in a particular order(although, I suppose that "value" may stem from laziness of not having to type each one individually). Is there some logical way to set up this class, so that I could iterate through it in this order? Or am I helpless for organization, and I should just go back to the basics of having 15 private variables, and 15 "getters" and "setters"?
As an aside, currently I'm working with Android and Java, so answers pertaining specifically to that would be the most helpful, but seeing how I encounter this somewhat frequently in other languages, too, any solution would be ideal.
If you don't mind a bit of repetition if it means avoiding "magic"... Use a nested class (non-static) that implements java.util.Map<String,Object>. This provides a uniform way for outside code to enumerate a set of properties you choose, while keeping the implementation details (ex. reflection versus a bunch of if/then clauses) hidden.
public class Product {
private String productName;
private int productPrice;
private PropMap props = new PropMap();
class PropMap implements Map<String,Object>{
/* Reflection, or if-then statements, etc.
Access outer items ex: this.Product.productName
Throw exceptions if someone tries to store the wrong
kind of item.
keySet() and `iterator()` will need to return
implementations
that provide things in an appropriate order.
*/
}
public PropMap getPropMap(){
return props;
}
}
So external code could go:
Map<String,Object> m = myobj.getPropMap();
for(m.keySet(): String k):
Object v = m.get(k);
}
It's also possible to refactor PropMap into its own class,
ProductPropMap, but then it wouldn't have access to private
items.