Related
I am facing difficulties to decide between using a marker interface or an empty abstract class.
I have two classes BrokerResponse and Notification, which have no structural similarity. The only thing connecting them is the need to be subscribable for.
void register(Receivable receivable, BrokerObserver observer)
I somehow dislike using a Marker Interface, because it violates the basic definition of an Interface. On the other hand using an abstract super class would make me as uncomfortable, because both classes have no relationship with one another.
What is the generally preferable approach in this scenario and why?
Edit 1
I forgot to mention, that BrokerResponse is an abstract class itself, that has several subclasses to determine the respective type.
Abstract class vs. marker interface:
There is nothing wrong with marker interface and there are some use cases for it. Choosing between those two, marker interface has more flexibility.
If you do want to define a type, do use an interface.
An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design - your classes don't have common design and nothing to share. Moreover you will stick both of them to some restricted design and will be not so flexible if you will need to add a real different parents to them in the future.
List of use-cases for abstract class:
Share code among several closely related classes.
Classes that extend your abstract class have many common methods or
fields or require access modifiers other than public (such as
protected and private).
Declare non-static or non-final fields what enables you to define
methods that can access and modify the state of the object to which
they belong.
Use-cases for interface:
Unrelated classes would implement your interface.
Specify the behavior of a particular data type, without concerning
who implements its behavior.
Advantage of multiple inheritances.
All listed arguments are for the usage of interface. Since BrokerResponse is abstract itself and has it's own hierarchy, making the fact that those classes don't have something in common more stronger.
As alternative you can use marker annotation. I would consider to stick one of those two approaches instead of Abstract Class.
Marker interface vs. marker annotation:
According to Joshua Bloch's 'Effective java':
Marker interfaces have two advantages over marker annotations. First
and foremost, marker interfaces define a type that is implemented by
instances of the marked class; marker annotations do not. The
existence of this type allows you to catch errors at compile time that
you couldn’t catch until runtime if you used a marker annotation.
Another advantage of marker interfaces over marker annotations is that
they can be targeted more precisely.
When should you use a marker annotation?
you must use an annotation if the marker applies to any program
element other than a class or interface, as only classes and
interfaces can be made to implement or extend an interface.
When should you use a marker interface?
Ask yourself the question, Might I want to write one or more methods
that accept only objects that have this marking? If so, you should use
a marker interface in preference to an annotation. This will make it possible
for you to use the interface as a parameter type for the methods in
question, which will result in the very real benefit of compile-time
type checking.
Summary:
If you want to define a type that does not have any new methods
associated with it, a marker interface is the way to go.
If you want to mark program elements other than classes and
interfaces, to allow for the possibility of adding more information to
the marker in the future, or to fit the marker into a framework that
already makes heavy use of annotation types, then a marker annotation
is the correct choice.
Using empty abstract class does not make any sense in this case as there is no multiple inheritance in Java.
Making you class implement some marker interface does not change you class hierarchy, it just marks your class with some additional metadata.
Image the case when your class which already is marked as Subscribable should also be for example Writable. If you use empty abstract class you will need to redesign the entire hierarchy. With marker interface it is just as easy as to add Writable to list of implementations.
How about annotating them? You got your answer that using a mark interface is the way to go here if you would have to choose, but using an annotation depending on what you might need to do would be much cleaner.
The fact that you say you need to make them somehow "the same" talks about an instanceof call and doing something based on that. The same thing could be achieved via isAnnotationPresent or the like.
But if you add a marker interface, how about making it not a marker interface - only in case you have a finite number of classes you need to test against? Something along the lines of MyInterface {boolean isSubscribable();}
A new collaborator of mine who was reviewing some code I'd written told me that she wasn't used to seeing interfaces used directly in Java code, e.g.:
public interface GeneralFoo { ... }
public class SpecificFoo implements GeneralFoo { ... }
public class UsesFoo {
GeneralFoo foo = new SpecificFoo();
}
instead, expecting to see
public interface GeneralFoo { ... }
public abstract class AbstractFoo implements GeneralFoo { ... }
public class SpecificFoo extends AbstractFoo { ... }
public class UsesFoo {
AbstractFoo foo = new SpecificFoo();
}
I can see when this pattern makes sense, if all SpecificFoos share functionality through AbstractFoo, but if the various Foos have entirely different internal implementations (or we don't care how a specific Foo does Bar, as long as it does it), is there any harm in using an interface directly in code? I realize this is probably a tomato/tomato thing to some extent, but I'm curious if there's an advantage to the second style, or disadvantage to the first style, that I'm missing.
If you have no need for an abstract class with certain details common to all implementations, then there's no real need for an abstract class. Complexity often gets added to applications because there is some perceived need to support future features that haven't yet been defined. Stick with what works, and refactor later.
No, she's inexperienced, not right. Using interfaces is preferred, and writing redundant abstract super classes for the sake of redundancy is redundant.
UsesFoo should care about the behaviour specified by the interface, not about the super class of its dependencies.
For me "she wasn't used to" is not good enough reason. Ask her to elaborate on that.
Personally I'd use your solution, because:
AbstractFoo is redundant and ads no value in current situation.
Even if AbstractFoo was needed (for some additional functionality), I'd always use lowest needed type: if GeneralFoo was sufficient, then I'd use that, not some class derived from it.
It depends only on your problem.
If you use interfaces only, then if all your classes have a same method, it would have to be implemented redundantly (or moved away to a Util class).
On the other hand, if you do write an intermediary abstract class, you solved that problem, but now your subclass may not be a subclass of another class, because of absence of multiple inheritance in Java. If it was already necessary to extend some class, this is not possible.
So, shortly - it's a trade off. Use whichever is better in your particular case.
There is not harm in directly using an interface in code. If there were, Java would not have interfaces.
The disadvantages of using an interface directly include not being able to reach and class-specific methods which are not implemented in the interface. For poorly written interfaces, or classes which add a lot of "other" functionality, this is undesirable as you lose the ability to get to needed methods. However, in some cases this might be a reflection of a poor design choice in creating the interface. Without details it is too hard to know.
The disadvantages of using the base class directly include eventually ignoring the interface as it is not frequently used. In extreme cases, the interface becomes the code equivalent of a human appendix; "present but providing little to no functionality". Unused interfaces are not likely to be updated, as everyone will just use the base abstract class directly anyway. This allows your design to silently rot from the viewpoint of anyone who actually tries to use the interface. In extreme cases, it is not possible to handle an extending class through the interface to perform some critical functionality.
Personally, I favor returning classes via their interface and internally storing in members them via their lowest sub-class. This provides intimate knowledge of the class within the class's encapsulation, forces people to use the interface (keeping it up-to-date) externally, and the class's encapsulation allows possible future replacement without too much fuss.
I'm curious if there's an advantage to the second style, or disadvantage to the first style, that I'm missing
That reasons for the first interfaces style:
Often, the design is such that the interface is the public interface of the concept while the abstract class is an implementation detail of the concept.
For example, consider List and AbstractList in the collection framework. List is really what clients are usually after; fewer people know about about AbstractList because its an implementation detail to aid suppliers (implementers) of the interface), not clients (users) of the class.
The interface is looser coupling, therefore more flexible to support future changes.
Use the one that more clearer represents the requirement of the class, which is often the interface.
For example, List is often used rather than AbsrtactList or ArrayList. Using the interface, it may be clearer to a future maintainer that this class needs some kind of List, but it does not specifically need an AbstractList or an ArrayList. If this class relied on some AbstractList-specific property, i.e. it needs to use an AbstractList method, then using AbstractList list = ... instead of List list = ... may be a hint that this code relies on something specific to an AbstractList .
It may simplify testing/mocking to use the smaller, more abstract interface rather than to use the abstract class.
It is considered a bad practice by some to declare variables by their AbstractFoo signatures, as the UsesFoo class is coupled to some of the implementation details of foo.
This leads to less flexibility - you can not swap the runtime type of foo with any class that implements the GeneralFoo interface; you can only inject instances that implement the AbstractFoo descendant - leaving you with a smaller subset.
Ideally it should be possible for classes like UsesFoo to only know the interfaces of the collaborators they use, and not any implementation details.
And of course, if there is no need to declare anything abstract in a abstract class AbstractFoo implements GeneralFoo - i.e. no common implementation that all subclasses will re-use - then this is simply a waste of an extra file and levels in your hierarchy.
Firstly I use abstract and interface classes plentifully.
I think you need to see value in using an interface before using it. I think the design approach is, oh we have a class therefore we should have an abstract class and therefore we should have interfaces.
Firstly why do you need an interface, secondly why do you have an abstract class. It seems she may be adding things, for adding things sake. There needs to be clear value in the solution otherwise you are talking about code that has no value.
Emperically there you should see the value in her solution. If there is no value the solution is wrong, if it cant be explained to you she does not understand why she is doing it.
Simple code is the better solution and refactor when you need the complexity, flexibility or whatever perceived value she is getting from the solution.
Show the value or delete the code!
Oh one more thing have a look at the Java library code. Does that use the abstract / interface pattern that she is applying .. NO!
I'm using an interface in java, that communicates with PureData. In order to do so, my classes have to extend a given class MaxObject. While designing my class, which is a cirular buffer, I discovered that I need to extend java's Iterator class. So I have to extend two classes at the same time.
My guess is that the only solution is to create two different classes and let one of them be a component of the other one. But, is it the only solution? Is it the best one?
Further, whenever I find myself needing inherit from two classes, is it a because of a bad design? Is there a design pattern to solve this class?
Thank you
Iterator is not a class, it's an interface. As such, you don't extend it, you implement it. You can implement any number of interfaces - the only limitation is that you can only extend one class.
In your case:
class MyClass extends MaxObject implements Iterator<Type>
edit: I should have read closer what's being extended. EboMike is right, you don't need to extend the Iterator class.
Sounds like the DDofD: http://javacodeonline.blogspot.com/2009/08/deadly-diamond-of-death.html
Iterator is an interface. From a theoretical point of view there's nothing against extending MaxObject and implementing Iterator.
Due to a lack of information I cannot say if it's a good idea to do this, but I have a bad feeling.
Is there a reason to use a 100% abstract class and not an interface ?
Can you give me a good example when to use both so I can grasp the concept a little?
Update:
100% Abstract class -> abstract class with only abstract methods.
I'm curios if there are differences between php and java regarding this aspect.
Update2:
Even if I understand most of the reasons I'm more interested in the conceptual more than technical reasons.
If by "100% abstract class" you mean "abstract class with no concrete methods", then I can think of a reason: visibility.
You can define an abstract method to be protected, and hence not part of the public API of the class. However, that seems like an odd design.
Another thing that came to my mind is when you expect to add common functionality to the base class - i.e. if it is likely to have some utility methods shared by all implementors, but these methods are not implemented.
Another thing - instance variables. You can have inheritable instance variables in the abstract class.
The one case where an "100% abstract class" may be advantageous over an interface is in places where API stability is a key concern.
If you write an API where other people are expected to implement your interface you have to stick to the interface. You can't add any methods to the interface later on because that would break all clients (you would have to work around this by implement a second interface and let your code check againt the usage with instanceof checks and provide an fallback).
If you realize the same with an class you can add (non abstract) methods later on without breaking the client.
Next to visibility, another reason could be to be able to specify a certain Constructor you want all implementations to implement, or define a certain property. But in general, I agree with Alexander that a 100% abstract class isn't a good idea. I would prefer an interface in most cases unless there's a very good reason not to use an interface.
I personally think the difference as conceptual more than technical. For instance it would be bad idea to have an interface called "Human" and implement them on Male and Female. It would make more sense to make the Human as class.
You can implement multiple interfaces and you should see interfaces as add-ons.
I'm not quite sure how to answer this conceptually anymore, but in practice I use interfaces for the following reasons:
To indicate different classes have a shared interface: that you can manipulate them / use them in the same way
You can implement multiple interfaces, but only extend one class
Reasons for using abstract classes:
To share functionality between similar objects. For example Porshe911 could extend Car, overwrite a few methods and keep the rest.
To write frameworks that people can adapt. For example by leaving a few crucial methods unimplemented and writing the rest of the class to be internally consistent provided you implement those few methods. An example would be a menu class with a single abstract method getMenuItems()
Your example of the 100% abstract class seems senseless to me. As far as I can see that would just make it an interface, with the added restriction that you can have only one.
100% Abstract class isn't good idea. For common structure of child classes uses Interface. For similiar classes with same some methods and not same others more better to use Abstract Class.
This question was asked already here, but rather than answering the specific question, descriptions of how the decorator pattern works were given instead. I'd like to ask it again because the answer is not immediately evident to me just by reading how the decorator pattern works (I've read the wikipedia article and the section in the book Head First Design Patterns).
Basically, I want to know why an abstract decorator class must be created which implements (or extends) some interface (or abstract class). Why can't all the new "decorated classes" simply implement (or extend) the base abstract object themselves (instead of extending the abstract decorator class)?
To make this more concrete I'll use the example from the design patterns book dealing with coffee beverages:
There is an abstract component class called Beverage
Simple beverage types such as HouseBlend simply extend Beverage
To decorate beverage, an abstract CondimentDecorator class is created which extends Beverage and has an instance of Beverage
Say we want to add a "milk" condiment, a class Milk is created which extends CondimentDecorator
I'd like to understand why we needed the CondimentDecorator class and why the class Milk couldn't have simply extended the Beverage class itself and been passed an instance of Beverage in its constructor.
Hopefully this is clear...if not I'd simply like to know why is the abstract decorator class necessary for this pattern? Thanks.
Edit: I tried to implement this, omitting the abstract decorator class, and it seems to still work. Is this abstract class present in all descriptions of this pattern simply because it provides a standard interface for all of the new decorated classes?
Better one and a half year late than never:
A base class for decorators of a certain interface is not necessary.
However, it is very useful to have:
for one thing, as a means of documenting that classes derived from it are decorators of the interface in question
but mostly, because decorators usually do not need to add functionality to every single method of the decorated interface.
So, a base decorator class allows derived decorators to implement only those methods of the interface to which they actually need to add some functionality, leaving the rest of the methods to the base class to provide a default implementation for. (Which simply delegates the call to the decoree.)
Contrast this with writing decorators that implement the decorated interface from scratch, where the compiler requires that you provide an implementation for every single method of the interface, whether your decorator will be adding any functionality to it, or not.
It is that simple, really.
I was wondering the same thing. Going back to the source, GOF Design Patterns, I see this under 'Implementation' in the Decorator chapter:
"Omitting the abstract Decorator class. There's no need to define an abstract Decorator class when you only need to add one responsibility. That's often the case when you're dealing with an existing class hierarchy rather than designing a new one. In that case, you can merge Decorator's responsilibility for forwarding requests to the component into the Concrete Decorator."
So at least in that case, it seems that GOF agree with you :-)
I'm not sure what the meaning of 'one responsibility' is. I'm not sure if more than 'one responsibility' would mean one concrete decorator that has more than one responsibility or more than one concrete decorator, each with its one responsibility. Either way, I don't see why the abstract Decorator is necessary. My guess is that tvanfosson's answer (in his comment on his own answer) is the right one - that once you start creating a number of decorating classes, it clarifies the design decision to group them under a superclass. On the other hand, where there is just one class, it perhaps makes the design decision less clear if you add in a second class that just sits as a pointless middle-man between base component and decorator (having said that, it's fairly likely that you'll want to add more at some point, so maybe better to include the abstract decorator even in the single case...)
At any rate, seems like it's to do with making the design clear, rather than the being the difference between the code working and not.
(A bit late to your question..)
I also spent quite a while to try to figure out an answer. In my case the non-concrete Decorator extends the class to be decorated ("decoree"), instead of an interface common to both the decoree and the Decorator.
After reading from different sources, it seems to me that, besides what tvanfosson said, the reason to have the concrete decorators extend an abstract, or more general, decorator is so that we don't repeat the "delegation" code over and over again.
[Beverage]<———————[(abstract) CondimentDecorator]<—————[Milk]
[decoree ]——————<>[ adds code to efficiently ]
[ forward calls to decorated ]<—————[LemonJuice]
[ instance of Beverage ]
In your case, your abstract decorator would extend the decoree and would implement the same interface as the decoree, delegating/forwarding all method calls to it. Then, the concrete decorators that you may build, would only need to implement those methods where you would want to do something different than just forward the method call to the decoree.
I hope I was clear.. :-S
Personally, I'm a bit disappointed at the need to repeat the decoree's interface in the decorator. This adds some coupling, since any time the decoree's interface changes (like getting more methods), the decorator needs to catch up.
In PHP 5.3.2 (yes, I know your question is related to Java), though, it should be possible to dynamically catch all method calls and forward them all, without the Decorator needing to know which methods are being called (in a not a very efficient way, though, having to use the Reflection API). I guess this is possible in Ruby and other languages already.
PS: This is my first answer ever in SO! ^_^
It enables the decoration of the base class independently with various decorators in different combinations without having to derive a class for each possible combination. For example, say you want your Beverage with milk and nutmeg. Using decorators based on the abstract decorator class, you merely wrap with with Milk and Nutmeg decorators. If it was derived from Beverage, you'd have to have a MilkWithNutmegBeverage class and a MilkBeverage class and a NutmegBeverage class. You can imagine how this explodes as the number of possible combinations increases. Using the abstract decorator implementation reduces this to just one decorator class implementation per decoration.
The base Decorator makes it easier to create additional decorators. Imagine that Beverage has dozens of abstract methods, or is an interface, say stir(), getTemperature(), drink(), pour() and the like. Then your decorators all have to implement these methods for no other reason than to delegate them to the wrapped beverage, and your MilkyBeverage and SpicyBeverage each have all those methods.
If instead you have a concrete BeverageDecorator class that extends or implements Beverage by simply delegating each call to the wrapped Beverage, subclasses can extend BeverageDecorator and only implement the methods they care about, leaving the base class to handle delegation.
This also protects you if the Beverage class (or interface) ever gains a new abstract method: all you need to do is add the method to the BeverageDecorator class. Without it, you would have to add that method to each and every Decorator you had created.
actually i also sometimes leave out this 'middle-man' abstraction (if you don't have many decorator combinations). it decouples more but also adds complexity. in my view the main idea behind decorating is wrapping interfaces inside their own implementations.
In the case of the Decorator pattern, inheritance is being used for type matching. This is not the typical reason for sub-classing. The normal reason for sub-classing is to inherit behavior
To make this distinction clear, it makes sense to sub-class Beverage with CondimentDecorator because the CondimentDecorator class makes the distinction between a drink implementation (like DarkRoast) and condiment (like Mocha) clear. Consider for example you were tasked to come up with a menu for StarBuzz just by looking at the code. You would immediately know which are "base" beverages and which condiments by looking as the base class. DarkRoast's base class is Beverage. Mocha's base class is CondimentDecorator.
Still, I think it might make more sense in Java to implement the Beverage abstract class as an interface instead. According to the book, the code didn't use this approach because StarBuzz already had an abstract Beverage class (p 93) and an abstract base component is the historical approach to implementing the pattern.
The BaseDecorator (CondimentDecorator) class enforce the ConcreteDecortor (Milk) to have a base abtract class (Brevrage) in input in the constructor.
If the BaseDecorator class does not exist, it does not force you to implement a decorator that require a BaseAbstractClass in input. It is the goal of the Decorator Pattern to enforce input and ouput of classes.
(I think you take your example from Head First Design Pattern, and in their example, the BaseDecorator class do not have this contructor).
maybe years too late but here is the point with the gof statement of single responsibiltiy.
suppose the abstract decorator also have additional methods not own by the component (abstract) there by the decarator have multiple responsibilty.
this ensure that the component is always reuseable for it should implements all abstract / interface of the component but must not implements the decorator additional responsibilty.
any program that use the component(abstract) can ensure the component works accordingly in the utilization wise(into running object) and concrtete creation of the component(abstract). thus this will ensure program integrity and ease of development and expandsion of application/program.
thus decorator will leave those alove and then as though stand as his own object to be use in any manner as possible include manners similar to above.
eg. decorator being decorated.(just an idea)
great isnt it? (clap)