Checking subclasses for relevance before instantiating them? - java

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.
}

Related

Can this be considered polymorphism?

I've got a task to do polymorphism but I am not entirely sure I understand the concept as per testimony of my teacher.
According to web definitions and examples, this by all means is polymorphism, but they say it is not. Can I please get confirmation?
OversizedParcel.java
public class OversizedParcel implements ParcelType {
public void resolve(PrivateUser user) {
//do theese
//and those
}
public void resolve(LegalUser user) {
//do different thing
//and a completely different thing
}
}
IllegalParcel.java
public class IllegalParcel implements ParcelType {
public void resolve(PrivateUser user) {
//do this
//do that
}
public void resolve(LegalUser user) {
//do a thing
//do a different thing
}
}
(hypothetical class)
public class Main{
private User user; //loaded user
private List<ParcelType> parcels; //assume this contains the loaded parcels already
public static void main(String[] args){
for(ParcelType type : parcels) type.resolve(user);
}
}
Polymorphism can be defined as -
it is the ability of an object to take on many forms
. The most common example of polymorphism could be-
when a parent class reference is used to refer to a child class
object.
So as per your question, in most simplistic way polymorphism can be defined as
ParcelType oversizedparcel = new oversizedParcel();
ParcelType illegalparcel = new illegalParcel();
Here ParcelType can be a oversizedParcel or illegalparcel
So if your understanding is as per my answer, then indeed it is an example of polymorphism.
I'd like to offer a dissenting opinion from what appears to be majority here. Keep in mind that "Polymorphism" is a fairly flexible term, and that what is written here does not necessitate 100% universal truth. This is simply something to aid the balance of thought.
No, what you have written is not polymorphism. This is due to the fact that they instantiate different unrelated objects that simply implement the same interface.
Traditionally, Polymorphism occurs when you have a child object that overrides a parent object's implementation of a method. Hence, there is "multiple forms" of a method that exist at the same time at different levels of the object's vertical hierarchy.
However, interfaces are merely an agreed-upon contract of inputs and outputs that standardize interactions. They don't by themselves hold an instance of the code (we shall exclude default interface methods for the sake of this conversation). Because of this, there is no "Re-definition" of the interface within an object. the same object tree does not instantiate multiple versions of the interface (unless it is through the traditional view of polymorphism).
Even if a method required two arguments of interface ParcelType, it does not necessarily mean polymorphism, it simply means that the method is asking for two 'boxes' of a particular shape and size. These boxes are empty until they are passed into the method as two distinctly different objects that are referenced separately (And not the same method object being overridden by a child object, for example)
Different objects can take advantage of the interface contract, and in a way you can say that it is "Horizontal Polymorphism", but I think this is taking away from the intention of what polymorphism means in the context of Java.
According to the W3School definition, it is indeed polymorphism. Anyway, if your teachers said it is not, they may have been expecting you to do something else.
Polymorphism is, to go further than just an example, an entire concept meaning that you can do entirely different things by using "the same things", or more exactly "things named the same".
Have a look on the Wikipedia definition, which is more complete than any language-specific one, to have a wider view on it.
Polymorphism is having the same thing in different forms. So, Yes this is polymorphism.
I assume that resolve is defined in ParcelType interface. Then the type.resolve calls in for(ParcelType type : parcels) type.resolve(user) are dispatched polymorphically on ParcelType

Am I using instanceof "wrong"?

So in a simple game engine of mine I use an interface "UpdatedGameElement" to signal that an object having that interface has to be updated every frame through an implementation of an update() method.
Now in my "main"(not THE main) class I iterate through a list of GameElement 's and check if these are an instanceof UpdatedGameElement. If this is the case I cast them, and then call .update().
Now the thing is, I just read that using instanceof is usually a sign of bad coding; and in cases where classes are used as markers when they could be easily replaced with a variable, I agree. But I'm not so sure about my case.
I guess I could let the GameElement class implement UpdatedGameElement, and define a standard empty update() method that needs to be overridden to actually do something, but I'm not sure if and why that would be better than what I have now.
What would you say?
Edit: some code from my main class:
public void process()
{
if (active)
{
for (GameElement GE: elements)
{
if (!GE.isToBeRemoved())
{
//Relevant part
if (GE instanceof UpdatedGameElement)
{
((UpdatedGameElement) GE).update();
}
}
else
{
prepareRemoval(GE);
}
}
processRemovals();
}
}
Following the invitation if the OP:
If use of the interface has no other reason than to add a marker plus the update method to GEs, and if the type UGE isn't used except after this single instanceof, then it is a weak reason for having these extra types. ESpecially when the capability of being updated can be extended to all other GEs, where it is just a NOOP.
An abstract method in the base class forces the programmer to decide whether update needs to be coded for a particular subclass. This approach is rather "safe" from a "defensive design" point of view. But, of course, you write more code.
In contrast to the previous technique: If you forget the interface there's no alarm.
Also, if you code a NOOP update method in the base class and rely on programmers' alacrity to override where necessary: convenient, but risky when you forget to do it.
Summarizing: There are a few subtle pro's and con's - not just the instanceof "smell".
Based on your comments you mentioned that GameElement implements UpdatedGameElement, for now GameElement is the only class which is implementing UpdatedGameElement but it could be more in future. Also I hope you are aware that an interface cannot be instantiated thus you cannot create an instance of UpdatedGameElement thus in real the instances are created of the implementing classes of an interface. Thus during runtime when you create an instance of GameElement and assign it to UpdatedGameElement variable, that doesn't mean the instance is of type UpdatedGameElement now, its actually of type GameElement, now suppose that you have one more class implementing XYZElement implements UpdatedGameElement and create instance as below:
UpdatedGameElement ge = new GameElement();
UpdatedGameElement xyze = new XYZElement();
Do you think it good to use instance of check as below, as in either case it will be true and you never know which kind of instance ge and xyze are of.
if(ge instance of UpdatedGameElement)
instead one should always check for if(ge instance of GameElement)
Similarly for if(xyze instance of UpdatedGameElement)
instead one should always check for if(ge instance of XYZElement)
Hope this helps.
I guess I could let the GameElement class implement
UpdatedGameElement, and define a standard empty update() method that
needs to be overridden to actually do something
Yes, you should definitely do it!
Reason: suppose in the future you'll need to implement another "updateable" class that extends UpdatedGameElement - consider the code changes you'll have to do in every place you've used instanceof...

What is best way to use instance of one class into another class without passing into constructor

If both classes are at same level (Both are child class), how to use instance of one class into another one.What is best way to use instance of one class into another class without passing into constructor? so manually require to pass null. How to make independent code?
Class PreviewPanel{
private PreviewPanel(Builder builder) {
this.previewMode=builder.previewMode;
formsPreview=new NTFormsPreview(previewMode);
formsPreview.setCanAddComment(builder.canAddComment);
ntPreviewTreePanel=new NTPreviewTreePanel(builder,formsPreview);
//This class have some event bus implemented.Sometime There, formsPreview instance is require.
}
public static class Builder {
private PreviewMode previewMode;
private Document document;
public Builder(PreviewMode previewMode,Document document) {
this.previewMode = previewMode;
this.document=document;
}
public PreviewPanel build() {
return new PreviewPanel(this);
}
}
}
If I pass that instance into constructor,I have to follow chain of inner class and pass same instance to reach specific class. I want to avoid it. This is big product. it is not easy to show how many classes inside it to reach actual handler implementation.
Code Structure:
private PreviewPanel(Builder builder)
->formsPreview=new NTFormsPreview(previewMode);
->NTPreviewTreePanel(builder,formsPreview);
->NTPreviewTree(document, bidDocuments, previewMode, canAddComment,canViewComment, previewFormTxnEncryptionDetails,formsPreview);
->NTTreeNode(formsPreview)
private void fireReportItemClicked(Document document,esenderCSReport){
eventBus.fireEventFromSource(formPreviewEvent, formsPreview);
}
is there any way to use instance of one class into another class without passing instance into constructor?
There are other ways.
Pass the instance of the second class to the first class using a setter method.
Pass the instance of the second class to the first class by assigning to a instance variable in the first class.
Create the instance of the second class in the first class.
If you an answer that is more relevant to your example, you will need to explain more clearly what you are trying to do here, and why you think that your current solution is unsatisfactory.
Re this attempted explanation:
I have to follow chain of inner class and pass same instance to reach specific class. I want to avoid it.
I have no idea what you are trying to say. I suspect that other readers has the same problem.
I suspect that the real problem here is with the design of your existing code. It looks like you / someone has gone a bit crazy with nesting classes, and that you are suffering the consequences. It could be that the only way to simplify things is to unpick the nesting or rethink the constructors. (Why does a private constructor require a "builder" argument?)
It is a fairly common phenomenon for complicated OO software to have inherently complicated initialization patterns. There tends to be no neat way to deal with this programatically, but you can often avoid this by using some kind of "Dependency Injection" (DI) mechanism. Another name for this is "Inversion of Control" (IoC).
For example, Spring DI works by adding annotations to your class, and getting Spring to create and assemble the instances in the required form. Or you can specify how the instances (beans) are assembled in XML.
This could be a solution for you ...
Your problem is unclear to me but I think you could do the following :
Create a new Class that will "Own both of your child class - composition"
Make it work a Mediator Pattern so that one can use and call stuff on the other one following the rule/logic you want.
No need to pass one of the child to the other one in any way.
Freely, redesign the interaction logic if it gets to change
No need to "change"" the structure you already have
FYI The builder, seems to be related to the Builder Pattern, you might wanna read on it and see if you can understand something out of your project.

OOP-Design: Interface-Methods with implementation-dependent parameters

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.

Find info about class in java, software design?

I have a bunch of classes extending an abstract Base class.
Each subclass takes an array as in the constructor, (different length depending on class).
These classes could be written by other people.
What is the best way to figure out the length of the array the class needs?
I could:
(A) Require that each derived class have a static method, returning the length.
However, the base class cannot enforce this, since abstract static methods does not work in java.
(B) Each derived class have a constructor with no arguments, and I construct
such classes just to be able to call the countParameters() method, that
I can enforce from the Base class. This feels "cludgy", since I am not interested in creating such object, but only need some info about it.
The reason is that I am creating a GUI, that gives the user the ability to create
instances of Derived classes, but each Derived class takes different number of parameters.
That is, I need to know how to draw the GUI before I can create the classes.
EDIT:
I could just require that each Derived class have a private
constructor, with no arguments, and using reflection I can call the countParameters() method.
EDIT2: Actually, what I am interested in, is what the names of the parameters are.
That is, if the class Derived have the constructor
public Derived(double name1,double name2,...)
I need a way to generate the String[] array
{name1,name2,...}
I guess this would be impossible to do without creating an instance of the class,
but for the user to be able to create such class, he/she needs the parameter names!
Moment 22.
It sounds like you need the Factory Pattern.
In general, it's a bad idea for a base class to know the set of it's descendant's. So you define another class whose job it is to know that.
If you have something like a Shape, with ThisShape and ThatShape as derived classes, then a ShapeCreator will handle the job of creating the specific set of shapes your program supports, giving each one the arguments it needs.
It's not quite clear what you're trying to achieve, but I wonder: Do the subclasses really have to take a single parameter with an array, as opposed to a list of parameters?
Constructor<?> ctor = Test.class.getConstructors()[0];
int parameterCount = ctor.getParameterTypes().length;
ctor.newInstance(new Object[parameterCount]);
how about this code:
public absract Base {
public abstract int size();
public Base(Object[] objs) {
if (objs.length != size()) {
throw new IllegalArgumentException();
}
//rest of your code.
}
each child class needs to implement size method.
hope its help.
I'd go with method A. You can't get the compiler to enforce the existence of such a method, but you can certainly enforce it in your program - no method, no work!
Seriously, this whole scheme is a bit brittle and I can't think of a way to make it significantly better. An incorrect implementation of those subclasses will bomb out, that's life.
A possible remedy would be for you to provide a set of interfaces for those subclasses, such as
SubClassTaking2Args
SubClassTaking3Args
...
and requiring your sub's to implement one of those as a marker interface. But that's just more bureaucracy with little more effect.

Categories