I have an abstract class called ChainHandler and many implementations of the ChainHandler.
Other programmers will write other implementations of that ChainHandler.
My program implements the Chain of Responsibility design pattern.
Each concrete implementation of the ChainHandler implements a handle method.
public abstract void handle(SomeclassA a);
If one handler can handle "a", it handles it and the chain stops. If not,"a" is passed to the next Handler until it hits the end of the chain.
I want each concrete handler to have a list of all "a"s it was able to handle. But I don't want to make the concrete classes developer to remember to write it to a list on success.
Is there a elegant way of doing it?
My best idea was the following:
1 - Change the handle method to protected at the concrete classes, make it return a boolean and change the name to innerhandle;
2 - Change the handle method at the abstract class to public and it calls the innerhandle. On success, it adds the object to the list.
The second option is surely better (and it relies on the Template method pattern) making it harder for someone implementing a subclass of doing it wrong, you can even make the handle method final so no one will ever be able to change it's behavior and break without noticing it.
The servlet API has such an example, the init method that takes a ServletConfig parameter can be overridden and it's rather common to see people forgetting to call super and the original init(ServletConfig) method, so you should try to avoid this same mistake.
Related
Java newbie here. Here's what I'd like to do:
Enumerate over a list of classes, each of which extends the same superclass.
Ask the class whether it's interested in an event.
If the class is interested, instantiate the class and call the object's event handler.
The idea is that steps 2 and 3 will prevent instantiation of classes that aren't interested. However, because I'm calling a method before instantiation, the check would have to be done statically. Java (rightly) doesn't allow the overriding of static methods, so it seems that I have to instantiate the class in step 2, making the sequence look like this:
Enumerate over a list of classes, each of which extends the same superclass.
Instantiate each class and ask the object whether it's interested in the event.
If the object is interested, call its event handler. If it's not interested, throw it away.
Am I missing a general way to accomplish the first set of steps?
Note that this question is mostly theoretical. Object creation overhead may be low enough to render it moot. I'm interested in the possibilities, though.
Since we're speaking about theory, I'm pointing at some facts and speaking in terms of design.
Static methods are not associated to a particular instance of a class, so overriding is not an option since it depends on having an instance. I'm talking about Java, because I recall some other languages that allow class method overriding.
The workaround to this is to define a static method in each subclass that returns the events it is interested in, so you can know this data before instantiation.
Another option is to put a specific class in charge of those objects instantiation and making that class keep a table associating an event with a list of interested classes (table that you can initialize and configure). This approach seems more maintainable because you won't have to change code if you want to unsuscribe a class from an event.
In the end, you just instantiate all the classes thata re associated to a certain event:
public class EventClassCreator {
private Map<String, List<String>> subscriptions;
public EventClassCreator() {
subscriptions = new HashMap<String,Set<String>>();
}
public void addSubscription(String event, String class) {
if(subscriptions.containsKey(event))
subscriptions.get(event).add(class);
else {
Set<String> subscriptionsForEvent = new HashSet<String>();
subscriptionsForEvent.add(class);
subscriptions.put(event, subscriptionsForEvent);
}
}
//You just need to make an event that loops over the list of classes,
//checks a subscription and instantiates a class if it is in the
//proper list.
}
Let's say you you have a class called Vehicle that outlines a protected (could also be abstract) method called speed. And, the sub class Car overrides that method to define its own implementation.
Now, assume that the need to have a speed method in the Vehicle class is no longer required (let's say all vehicles will be stationary for the whatever reason).
If I remove the method speed from Vehicle, I would like to throw a compile error so that so that the developer who has removed the method knows that sub class(es) are potentially relying on it to perform certain actions.
Technically speaking a compile error is not needed, but some sort of notification that acts as a hurdle when such re factoring is happening. Is there a programming pattern that can be employed to handle such a situation?
UPDATE: I am using Java 1.4 (Sorry!)
The #Override annotation is expressly for this purpose.
If you're not using Java 1.5+, then no, although you could use AOP to instrument those methods to throw an exception, or just use reflection and classpath scanning to go over all subclasses and check for the presence of said method.
If it's abstract, then there is no implementation that can be removed from the parent class, and your risk comes down to new subclasses not implementing it. If it's protected and defined in the parent, there are two cases that should already throw compiler errors if the parent implementation is removed.
1) A subclass calls that method without defining its own implementation. Method does not exist.
2) A subclass defines the method, but includes a call to super. Again, the method does not exist.
You can write super.speed() in nested classes and leave this method empty in parent. If you delete now this method in parent, you'll have an Exception. But there is a disadvantage - you must call it from all overrided methods. Try it, perhaps this will help you
Use #Override annotation for methods in subclases.
Once you remove the method from a base-class, tools like Eclipse and javac will issue a warining for those no-longer-overriding methods.
Edit: While you cannot use #Override before Java 1.5.0, there is a tool called xdoclet. Back in the days of J2EE and EJB 2.1 this was used to "simulate" annotations and do magical things with code based on javadoc-like markers. Look at it, maybe you can use it.
Edit 2: In Java 1.4.x, you can also use JavaDoc tag {#inheritDoc} for this kind of verification. Instead of annotating your method with #Override annotate it with #inheritDoc, like this:
public class MyAwesomeClass extends BaseClass
{
/** {#inheritDoc} */
protected void myAweSomeMethod()
{
//...
}
}
Now, if you change the myAweSomeMethod signature in BaseClass, or remove it, you will get warnings from JavaDoc tool, similar to this:
/home/npe/java-tests/MyAwesomeClass.java:4: warning - #inheritDoc used but myAwesomeMethod does not override or implement any method.
Hi I'm implementing a given design in java. Basically I have an abstract class which is called base and I have a number of concrete classes which are extending Base and implementing an interface from a different package. Each concrete class will be implementing a different interface. Now these interfaces contain both event-based and non event-based method signatures in them. My question here is; I'm only expected to implement non-event based methods in my concrete classes, however because of the implements keyword java forces me to insert an auto generated method body, which is basically return null. They might be implementing those event based methods later on but not at the moment. What would be an appropriate way to let the API user know that these methods do not contain an implementation. Here are my thoughts;
Use deprecated keyword
Create an exception class and throw that exception inside of the method and let the API user handle it.
I do not have the option of making changes to the existing architecture. Any idea really appreciated. Thank you.
According to Oracle, the reasons to deprecate an API include
It is insecure, buggy, or highly inefficient
It is going away in a future release
It encourages bad coding practices
neither of which actually fits your case.
Personally, I would favor throwing an UnsupportedOperationException which is already provided by the Standard Library in order to
indicate that the requested operation is not supported.
To me, this sounds more like what you actually want.
You can create your own interface which lists all the method you want users of your component to be able to access. Make this the only interface they use and additional public methods will not be visible.
Option (2) is good, but as you are following interfaces you'll want unchecked exceptions. And document the methods as unimplemented.
Deprecated implies a history, i.e., it works but should no longer be used. Since you are explicitly stating that the methods do not work, marking as deprecated will not prevent use nor indicate that the methods are unimplemented.
I would suggest use some mix bag of design patterns. That will help you solve this problem efficiently and make the code maintainable as well.
Based on my knowledge, you can use the Abstract Factory pattern here. See the design sketch below in the figure.
Method1 and method2 in subclass1 and subclass2 are the ones which are supposed to be exposed while method3 and method4 in subclass1 and subclass2 are the ones which we don't want to expose.
Create a Genericsubclass interface and create some methods in this interface depending upon the nature of methods you have in subclasses. For ex: i have create one method in this interface called nonEventbasedmethod1
Create a factory corresponding to every sub class and each factory will implement the GenericSubclass interface. Then implementation of nonEventbasedmethod1 method in subclass1Factory would be some thing like
nonEventbasedmethod1(){
subclass1.method1();
}
and implementation of nonEventbasedmethod1 method in subclass2Factory would be some thing like
nonEventbasedmethod1(){
subclass2.method3();
}
Then create a SubclassAbstract Factory which will return one of the subclass factories and then without worrying about which factory has been returned (that decision has already been taken in SubclassAbstractFactory before returning the appropriate factory) simply call the desired method from GenericSubclass interface and underneath one of the methods from the subclass1 or subclass2 will be invoked.
Hope this helps.
If you plain to throw an exception for "NotSupported" or "NotImplemented" Exception - consider the exception of NotImplementedException (at org.apache.commons).
However, I would reconsider to revisit your design and see if you can avoid having this - maybe you need to define another interface, which will hold the methods that are always implemented, and extend it in another interface (or provide an interface with no extension to the previous one) for the methods you not always implement.
The subject says it already:
I am thinking right now about following design-problem: I define an interface for a specific type of object that contains various methods.
Now i have the problem, that different implementations of this interface, need additional/different method-parameters (because the way they are implemented makes this necessary), which i cannot incorporate into the interface because they are not common to all interface-implementations.
Now i realize that interface implementations could come with their own property-files, loading their additional parameters from there, but what if these parameters need to be passed in at runtime?
Currently i can only think of passing in a Map<String, Object> parameters to overcome this problem - since JDK-Classes like DocumentBuilderFactory are doing something very similar by providing methods like setAttribute(String attName, Object attValue) this
seems like a feasible approach to solve this problem.
Nevertheless i would be interested in how others solve issues like this, alternative ideas?
I dont want to derive from the interface and add additional methods, since in my case i would then have to throw NotImplementException from the methods of the base interface.
UPDATE:
What could be eventual problems of the Map-approach? Implementing classes are free to ignore it completely if they cant make use of additional parameters.
Others might check if the Map contains the desired parameter-names, check the type of their values and use them if valid, throw an exception if not.
I have also seen this being used for the abstract class JAXBContext, so it seems to be a common approach..
UPDATE:
I decided to go for the map-approach, since i dont see any obvious disadvantages and it is being used in the JDK as well (yes, i know this does not necessarily mean much :)
Since i cannot accept an answer on this question, i will just upvote. Thanks for your input!
regards,
--qu
You should just initialize each inheritor with its own specific required parameters and let the interface method remain parameter-less, as in:
Interface Runnable:
public interface Runnable {
public abstract void run();
}
Implementation:
public class MyRunnable {
private final String myConcreteString;
public MyRunnable(String myConcreteString) {
this.myConcreteString = myConcreteString;
}
public void run() {
// do something with myConcreteString
}
}
The point of the interfaces is to have something that is common to all implementations. By trying to do this you destroy the whole reason why interfaces exists.
If you absolutely must do that there is a simple enough way that I have used before.
My answer is in C++ because I'm just not that fluent in other languages. I'm sure there are ways to implement this in java as well.
SomeMethod(void* parameterData);
void* parameterData is a pointer to a struct containing your data. In each implementation you know what you are receiving. You can even have a enum to tell you what kind of data you are receiving.
SSomeData* data = (SSomeData)parameterData
EDIT:
Another approach would be to create a new interface for the parameters: IParameterData.
Inside that interface you have 2 methods: GetParameter(name) and SetParameter(name).
For each implementation of your primary interface you create a implementation of IParameterData.
I hope it helps
couldn't you design subinterfaces that extend your (super)interface?
anyhow I see a design problem if you need a method with different parameters depending on the implementation!
edit: code to clarify
interface CommonBehaviour
{
void methodA(int aParam);
}
interface SpecificBehaviour extends CommonBehaviour
{
void methodB(int aParam, int anotherParam);
}
class SpecificBehaviourImpl implements SpecificBehaviour
{
void methodA(int aParam)
{
//do something common
}
void methodB(int aParam, int anotherParam)
{
//do something specific
}
}
CommonBehaviour myObj = new SpecificBehaviourImpl();
EDIT: You may benefit from the Command pattern:
"Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameters."
(source: wikipedia)
I don't think the Map approach to be any good, I may accept it as a fix of existing code that would allow you to have any parameter number and type, but without formal checks! You're trying to define a common behavior (interface methods) given a variable, runtime, state.
You should introduce parameter object representing a super-set of possible arguments.
In your place, I would consider finding appropriate design pattern to your problem, rather then try to bend the interface methods to suit your needs. Look into Strategy Pattern for starters.
Can you invert the problem, and implement an interface on the user of these objects which they can query for the additional parameters?
So, when you instantiate these objects implementing the common interface, you also pass in (e.g. to their constructor) an object which provides a way of accessing the additional parameters they might require.
Say your interface has a method 'doSomething' taking parameter 'a', but you have an implementation that needs to know what 'b' is inside this 'doSomething' method. It would call 'getB' on the object you provided to it's constructor to get this information.
So I have this really large method I wrote. If it's given a stack, it will return a stack. If it's given a queue, it will return a queue. It uses a lot of recursion, and it accepts a queue/stack and returns that same queue/stack modified accordingly.
I don't want to copy/paste my method just so I can change the type used inside, so is there any way I can make this generic? As in, it will accept any old collection and play with it? I tried just using Collection, but the trouble with that is it doesn't have a .remove() I can use with the stack/queue.
Any help would be greatly appreciated.
Thanks.
Make your method private, and create two public methods: one which takes a stack and one which takes a queue. have each of these methods cast and return the result of calling the private method. That way you avoid repetition while still having specific method signatures.
You could use Collection but then have special case handling just around your remove operations. Of course you'll have to figure out what to do when you get a collection that's not one of the two.
if (myCollection instanceof Queue) {
((Queue)myCollection).remove();
} else if (myCollection instanceof Stack) {
((Stack)myCollection).remove(thingy);
} else {
// Oops! Now what?
}
Queue and Stack both have a remove() method, but the method is not the same. Because of this, Java will need to know which of those methods to call when compiling the code. You will need to have 2 separate methods. Sorry
You need to write an interface that has the operations you need from both Stack and Queue, since you want to use recursion/operations upon both.
This new interface would have two concrete classes that would rely on instances of Stack and Queue underneath, then polymorphism would to the magic.
You can always have a method for 'getUnderlyingCollection()' so you could have the actual Stack or Queue, after the proper cast, but attain to polymorphic operations would make your recursive algorithm more generic.
I presume you mean java.util.Stack and java.util.Queue. Queue defines its own remove() method. Stack inherits its remove(...) methods from java.util.Vector, so I assume you actually mean pop()?
Two ways spring to mind:
Provide two public method overloads which both call a private method with two parameters, one of which is always null.
Define an interface with the common methods you need, with an anonymous inner class definition in each of two private methods (or a full concrete class definitions if they're sufficiently large).
Which you should choose depends on how many ugly conditional method calls you will need to do internally. An OO-purist would prefer the interface implementation regardless. :-)