Inheritance is one of the great elements of OO programming and it’s used all over the place. One area where we might not think to use it is with the Core libraries. It might be a psychological apprehension. We feel as though we shouldn’t “mess” with the internals. In reality though, we aren’t messing with the internals at all, we’re just starting with their functionality as a base.
Suppose you wanted to make a crazy implementation of a LinkedList that has pointers going all over the place and you want these pointers to be accessible. You could either write you own, which would be really fun let me tell ya, or simply extend the LinkedList object from the existing library and add the new functionality you want.
In a simpler example, let’s say we have a class called XmlTag. This class takes a Map parameter in it’s constructor, which it will use to build the attributes of an actual XML element. Now, you’d typically probably do something like this:
Map m = new HashMap();
m.put("id", "1");
m.put("name", "myTag");
m.put("description", "This is an XML Tag");
XmlTag xt = new XmlTag(m);
This is fine and dandy, but if you’re going to be creating these objects often, it’s going to be a pain to keep setting up these Map objects in advance. With the Map objects in the core library, we don’t really have an easy way of setting default values when the object is constructed. The solution is to create our own Map which extends an existing Map object from the core library, and give it the functionality we want.
public class DefinedHashMap extends java.util.HashMap
{
public DefinedHashMap(Object[] keys, Object[] values)
{
if(keys.length == values.length && keys != null && values != null)
{
for(int i=0; i<keys.length; i++)
{
this.put(keys[i], values[i]);
}
}
}
public DefinedHashMap(Object key, Object value)
{
if(key != null && value != null)
{
this.put(key, value);
}
}
}
Now we have a Map object that can be passed some basic values through a couple different constructors. We can use the constructor which takes two Object arrays as parameters (signifying keys and values respectively), and thus accomplish our goal in one line of code.
XmlTag xt = new XmlTag(new DefinedHashMap(new String[]{"id", "name", "description"}, new String[]{"1", "myTag", "This is an XML Tag"}));
By using fundamental OO concepts and various patterns we can code exactly how we want or get very close to it.
2 Comments
With your specific example, I believe there is a better approach. I would create a XmlTagFactory class that contains static factory methods to create XmlTag instances. With the name completion available in most IDEs, it makes finding the desired factory method relatively easy.
TagFactory.createXmlTag(String[] keyArray, String[] valueArray);
Yes, that is a more elegant way. I did it the noob way.
Post a Comment