Question

When programming using other people's classes, you often find that they didn't quite anticipate your needs and you have to use a sequence of several steps all over for what should be a one step operation.

IE, you're using a class that indexes objects, and so has a getObjectAtIndex method and a getNameOfObjectAtIndex method, but you want to access objects by name instead of index, so you have to write a loop that uses the getNumberOfIndexes method and loops over each, checks the name against the name you want, returns the index, and then you use access the object at that index.

If you need to do this frequently, to keep your code tidy you should refactor.

In Obj-C, the solution is to write a category. You can just add a new getObjectWithName method to that class (and all of its subclasses) without having to subclass or encapsulate it.

In Java, I haven't yet found a particularly great solution. Instead I've been writing helper functions that aren't invoked on any object but require the object to be passed in. Basically I have a method with function notation, which can be difficult to read.

To be clear, this isn't a class I wrote and I don't have the source code to it. Some other code is creating and returning it, so making a subclass doesn't help as I can't change that code that returns it to return my subclass instead. I could encapsulate it, but that seems even less elegant than what I'm already doing.

Does anyone know of a way I can achieve functionality similar to Obj-C's Categories in Java?

Was it helpful?

Solution

In general, Java developers most commonly use helper methods for this sort of thing. It's flexible and relatively modular, and really not so bad as you think.

A related technique is to use a wrapper object; a class that contains an instance of the class of interest, implements the same interfaces, and delegates most calls through to the contained instance, perhaps adding some methods along the way. Some IDEs (IntelliJ IDEA, certainly) have built-in tools that make creating this sort of delegating wrapper painless. Then whenever you receive a reference to an instance of the class of interest, you construct an instance of the delegator around it before doing any further processing.

If you really want something more interesting, there is always Aspect-Oriented Programming (AOP), which refers to tools and techniques for injecting new code into existing code based on various criteria at runtime. It is possible that you could use AOP to do something like this; for example, by adding an interface to a class, and a method that implements it. You'd have to cast the objects to the interface at compile time to use the method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top