Calling non-decorated methods on decorator object - java

Suppose we have implemented the Decorator Pattern as in the image below. With the CondimentDecorator class, the Beverage class can be decorated. The methods cost() and getDescription() will take care for that.
When creating a decorated Beverage like below, calling the method getName() won't work on the decorated object. In order to make this work, this method should also be placed in the class CondimentDecorator and delegate the call to the composed beverage variable.
Beverage b = new Milk(new Espresso("A very nice espresso"));
b.getName() // returns null
When having a lot of methods which don't need decoration, all of these should also be placed in CondimentDecorator to simply delegate. So the question is: What is a neat (generally accepted) way to solve this 'problem'?

The generally accepted approach to this 'problem' in a statically typed language like Java or C# (yes, C# is not quite statically typed, I know about DLR, and dynamic) is to have the decorated methods delegate to the decorated object explicitly. This solution has the obvious benefits of simplicity and explicitness.
In your example, if you don't override getName it means that you want to change the behaviour of the decorated object, which is exactly the purpose of the decorator pattern.
If you would choose to delegate to the decorated object by default then it would appear as if inheritance was broken, since CondimentDecorator inherits from Beverage but does not use the methods of base class.
Then, to change this behaviour, you would somehow need to define the methods that are not delegated to decorated object, but should work "as usual inheritance".
That would be not obvious and very messy.
That being said, what you want to achieve should be possible in Java.
For instance in .NET you could do this in the following ways, and I believe Java has something similar
By generating dynamic runtime proxies that use inheritance to dynamically modify the behaviour of the object, see Castle Dynamic Proxy
By using a MSIL rewriting technique that rewrites your itermediate code at compile time to modify it, for example see Fody - Method decorator
Additionally, check out how prototypical inheritance works in JavaScript - that behaviour is very similar to what you're trying to achieve

In your case if only few operation1() it is ok to add a delegate call to CondimentDecorator. If only few call() needs decoration then could make a decorator when needed, like:
DecoratorFactory.make(new Milk(new Espresso("A very nice espresso"))).getDescription();
or
CondimentDecorator.getDescription(new Milk(new Espresso("A very nice espresso")));
Key: patterns serve you.

Related

Why we use cloneable interface in java while making clones of the object?

I'm new to java and was studying object cloning. My question is that since Object class is the top most class in java and all other classes inherits this class and clone() method is defined in the Object class, then what is purpose of using cloneable interface? Why can't we just override the clone() method of Object class in our class and return super.clone() from it(or modify it for deep copy according to our needs)?
Also which is the recommended way (java standard way) of creating clones of the object? Using clone() method or creating copy constructor just like C++ which is mentioned in Andreas dolk's answer to this question?
The clone situation is unique and is rather anti-java-like - there's a reason its not recommended to use it in the first place. The way Cloneable is used in the JDK is not something you should be taking notes on - this isn't how to design APIs, nothing else in the java ecosystem works this way.
Weirdly, this is a common thing: The core parts of java often aren't java-like. For example, nobody in their right mind would make an API that defines an application by 'it has a method with the signature public static void main(String[] args). The obvious design principle would be to make an abstract class or interface with an abstract start() method, and to make a java app you write a class that has a no-args constructor and implements/extends that interface/class. Same story for arrays: They are weird - their toString, equals, and hashCode implementations are surprising, to say the least. They aren't entirely type-safe either.
The reasons for all of this are historic: To explain them, you need to know about all sorts of things that were relevant at the time, but aren't important anymore and haven't been for decades.
Cloneable is no different. Let me explain why it works that way:
The 'system' of cloning is offered by the JDK itself, it's a built-in thing that an ordinary library could not easily make. Kinda how "java SomeClass invokes its main method" is part of java itself.
The system, however, needs an opt-in mechanism: The act of cloning may not make sense (what does it mean to 'clone' an InputStream representing a TCP network connection's incoming bytes? What does it mean to 'clone' the value of an enum which tries to guarantee that only one instance ever exists? What does it mean to 'clone' a singleton?)
Thus, 'just make all objects cloneable' is dangerous, so java didn't want to do that: They want you to opt in to it. Java wants the author of a class to explicitly say: Yup. I am clonable, using the standard mechanism (which deep-copies all fields, if memory serves).
That is what Cloneable is for! - that's how you say: Yup. I'm good with it. By implementing that. It's a flag.
Java could also have decided to do something like:
/** #cloneable */
public class Something {}
instead, but they didn't. If it had been designed in this more modern age, perhaps it would have looked like:
#Cloneable
public class Something {}
But annotations were introduced in java 1.5 as a demo feature in 1.6 properly. The cloneable interface is as old as java 1.0 - over a decade earlier. "add an interface that defines nothing" was the standard way to flag class properties back then, even if it isn't now.
NB: You don't just implements Cloneable, you also make a public clone method. The implements Cloneable part tells the cloning system: You may clone this class, for example even if it is part of the deep structure of an encompassing object that is being cloned. Making a clone method that invokes the protected JVM-provided clone() method that j.l.Object has is how you expose the API. Maybe you want to name it copy instead, or maybe you want cloning but not as part of your public API. Your question isn't about how to use clone, but why it works like it is - my advice if you want to use it is simple. Don't, write clone code yourself, or better yet, design your API with more immutables so that cloning is no longer neccessary.
clone() method has no implementation in Object and does nothing. To make it work, your class has to implement Cloneable. This is a marker interface and adds some methods to any class inheriting it so that you can clone an object of that class.

Java inheritance, two-step inheritance

I have the main abstract class that is a base for bunch of classes. Some of them does not need all the fields and methods from the main abstract class, so I have created second abstract class and splitted main abstract class into two parts. The main abstract class contains, for example, a, x fields and their getters/setters, the second abstract class inherits from the main and contains additional b, c fields and their getter/setters. There are simple classes that are inheriting from the main class,and more complicated are inheriting from the second class. I want to create objects of each class as instances of the main class. Is it right way to do that? I have to type check and cast when I want to use methods from the second abstract class. It makes my code complicated. How can I solve this problem?
MainAbstractClass ---> SecondAbstractClass ---> MyComplicatedClasses
|
|
V
MySimpleClasses
One of the OO principles is Favor composition over inheritance.
This means that common behavior is not provided through base classes but via Component classes which are passed in via dependency injection (preferably as constructor parameters.
The answer depends on your actual needs.
You can instead choose to store the extended abstract class specific fields in a class that does not implement your base class and make it a member of more complicated classes.
You can choose to keep everything in a single base class and nothing forces you to use all the fields of an interface in every class that implemented your interface.
You can also keep using your approach but since you store the classes as an instance of the base class, it will be hard to read.
I believe that if you think code does not look very good, it is probably not good. However, there is usually no single answer to this kind of design questions and the best solution is relative to your preferences.
I think this need of type cast is a smell of fragile design. Here when we assume MyComplicatedClass ISA KIND OF MainAbstractClass as shown by TJ Crowder then object must behave as MainAbstractClass (meaning it can honor only API of MainAbstractClass). If it expects special treatment as MyComplicatedClass its false commitment and will need Casting. Such casting (by identifying type) goes against OO principles and kills polymorphism. Later this will end up in Ladder of InstanceOf and type casts as in the scenarios rightly pointed out by T.J. Crowder.
I would suggest readdress the design. e.g. though our all user defined type instances ARE KIND OF Object, but we use Object API only for methods defined in Object class. We do not use Object o = new MyClass(). There are occasions in frameworks or like Object.equals() method where type cast is needed as API is defined before even concrete extension is written. But it is not a good idea for such simple complete (without open hooks for extensions) Hierarchies.

Extending fluent interface

I'm starting using Fluent Assertions and I like it a lot, but wonder if it's possible to extend the existing tests in a general way like this:
add method hasSizeAtLeast(int limit) in GroupAssert
add method startsWithIgnoringCase(String prefix) in StringAssert
use alternatives like x.either().isIn(someSet).or().isNull()
These are just examples what I could need soon. I can do some workaround for each of them, but then I lose the readability and the easy of use of the fluent interface.
My last example is meant to throw iff both x.isIn(someSet) and x.isNull() do.
Here is a post by the author about opening up his API for extending assertions on already handled types. Lesson #1 in particular discusses the change to un-finalize classes. The post also gives an example of sub-classing StringAssert as MyStringAssert.
However, it looks like you cannot extend classes such as StringAssert in a way that maintains the "fluency" of the API. The StringAssert class isn't final, but still it doesn't allow you to parameterize its type (i.e. the "this" type that's returned by methods in StringAssert itself) in subclasses. For example, let's say you add a method checkFoo in MyStringAssert. As you discovered, the following is invalid because the original StringAssert methods return StringAssert:
new MyStringAssert("abcd").contains("a").checkFoo(); // compile-time error!
You only can call your subclass's methods first, which is valid but kind of lame:
new MyStringAssert("abcd").checkFoo().contains("a"); // compiles
You might consider contacting the author, or even submitting a patch to his git project. A possible solution would be to add the parameterized type back into StringAssert, and also provide the StringAssert concrete type via an anonymous subclass within Assertions.assertThat(String), which is the recommended entry point anyway. Then, everybody else can subclass StringAssert as you described. I haven't tested this suggestion either, but it seems to make sense...

Java Interfaces/Implementation naming convention [duplicate]

This question already has answers here:
Interface naming in Java [closed]
(11 answers)
Closed 7 years ago.
How do you name different classes / interfaces you create?
Sometimes I don't have implementation information to add to the implementation name - like interface FileHandler and class SqlFileHandler.
When this happens I usually name the interface in the "normal" name, like Truck and name the actual class TruckClass.
How do you name interfaces and classes in this regard?
Name your Interface what it is. Truck. Not ITruck because it isn't an ITruck it is a Truck.
An Interface in Java is a Type. Then you have DumpTruck, TransferTruck, WreckerTruck, CementTruck, etc that implements Truck.
When you are using the Interface in place of a sub-class you just cast it to Truck. As in List<Truck>. Putting I in front is just Hungarian style notation tautology that adds nothing but more stuff to type to your code.
All modern Java IDE's mark Interfaces and Implementations and what not without this silly notation. Don't call it TruckClass that is tautology just as bad as the IInterface tautology.
If it is an implementation it is a class. The only real exception to this rule, and there are always exceptions, could be something like AbstractTruck. Since only the sub-classes will ever see this and you should never cast to an Abstract class it does add some information that the class is abstract and to how it should be used. You could still come up with a better name than AbstractTruck and use BaseTruck or DefaultTruck instead since the abstract is in the definition. But since Abstract classes should never be part of any public facing interface I believe it is an acceptable exception to the rule. Making the constructors protected goes a long way to crossing this divide.
And the Impl suffix is just more noise as well. More tautology. Anything that isn't an interface is an implementation, even abstract classes which are partial implementations. Are you going to put that silly Impl suffix on every name of every Class?
The Interface is a contract on what the public methods and properties have to support, it is also Type information as well. Everything that implements Truck is a Type of Truck.
Look to the Java standard library itself. Do you see IList, ArrayListImpl, LinkedListImpl? No, you see List and ArrayList, and LinkedList. Here is a nice article about this exact question. Any of these silly prefix/suffix naming conventions all violate the DRY principle as well.
Also, if you find yourself adding DTO, JDO, BEAN or other silly repetitive suffixes to objects then they probably belong in a package instead of all those suffixes. Properly packaged namespaces are self documenting and reduce all the useless redundant information in these really poorly conceived proprietary naming schemes that most places don't even internally adhere to in a consistent manner.
If all you can come up with to make your Class name unique is suffixing it with Impl, then you need to rethink having an Interface at all. So when you have a situation where you have an Interface and a single Implementation that is not uniquely specialized from the Interface you probably don't need the Interface in most cases.
However, in general for maintainability, testability, mocking, it's best practice to provide interfaces. See this answer for more details.
Also Refer this interesting article by Martin Fowler on this topic of InterfaceImplementationPair
I've seen answers here that suggest that if you only have one implementation then you don't need an interface. This flies in the face of the Depencency Injection/Inversion of Control principle (don't call us, we'll call you!).
So yes, there are situations in which you wish to simplify your code and make it easily testable by relying on injected interface implementations (which may also be proxied - your code doesn't know!). Even if you only have two implementations - one a Mock for testing, and one that gets injected into the actual production code - this doesn't make having an interface superfluous. A well documented interface establishes a contract, which can also be maintained by a strict mock implementation for testing.
in fact, you can establish tests that have mocks implement the most strict interface contract (throwing exceptions for arguments that shouldn't be null, etc) and catch errors in testing, using a more efficient implementation in production code (not checking arguments that should not be null for being null since the mock threw exceptions in your tests and you know that the arguments aren't null due to fixing the code after these tests, for example).
Dependency Injection/IOC can be hard to grasp for a newcomer, but once you understand its potential you'll want to use it all over the place and you'll find yourself making interfaces all the time - even if there will only be one (actual production) implementation.
For this one implementation (you can infer, and you'd be correct, that I believe the mocks for testing should be called Mock(InterfaceName)), I prefer the name Default(InterfaceName). If a more specific implementation comes along, it can be named appropriately. This also avoids the Impl suffix that I particularly dislike (if it's not an abstract class, OF COURSE it is an "impl"!).
I also prefer "Base(InterfaceName)" as opposed to "Abstract(InterfaceName)" because there are some situations in which you want your base class to become instantiable later, but now you're stuck with the name "Abstract(InterfaceName)", and this forces you to rename the class, possibly causing a little minor confusion - but if it was always Base(InterfaceName), removing the abstract modifier doesn't change what the class was.
The name of the interface should describe the abstract concept the interface represents. Any implementation class should have some sort of specific traits that can be used to give it a more specific name.
If there is only one implementation class and you can't think of anything that makes it specific (implied by wanting to name it -Impl), then it looks like there is no justification to have an interface at all.
I tend to follow the pseudo-conventions established by Java Core/Sun, e.g. in the Collections classes:
List - interface for the "conceptual" object
ArrayList - concrete implementation of interface
LinkedList - concrete implementation of interface
AbstractList - abstract "partial" implementation to assist custom implementations
I used to do the same thing modeling my event classes after the AWT Event/Listener/Adapter paradigm.
The standard C# convention, which works well enough in Java too, is to prefix all interfaces with an I - so your file handler interface will be IFileHandler and your truck interface will be ITruck. It's consistent, and makes it easy to tell interfaces from classes.
I like interface names that indicate what contract an interface describes, such as "Comparable" or "Serializable". Nouns like "Truck" don't really describe truck-ness -- what are the Abilities of a truck?
Regarding conventions: I have worked on projects where every interface starts with an "I"; while this is somewhat alien to Java conventions, it makes finding interfaces very easy. Apart from that, the "Impl" suffix is a reasonable default name.
Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:
IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations
The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.
I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.
I use both conventions:
If the interface is a specific instance of a a well known pattern (e.g. Service, DAO), then it may not need an "I" (e.g UserService, AuditService, UserDao) all work fine without the "I", because the post-fix determines the meta pattern.
But, if you have something one-off or two-off (usually for a callback pattern), then it helps to distinguish it from a class (e.g. IAsynchCallbackHandler, IUpdateListener, IComputeDrone). These are special purpose interfaces designed for internal use, occasionally the IInterface calls out attention to the fact that an operand is actually an interface, so at first glance it is immediately clear.
In other cases you can use the I to avoid colliding with other commonly known concrete classes (ISubject, IPrincipal vs Subject or Principal).
TruckClass sounds like it were a class of Truck, I think that recommended solution is to add Impl suffix. In my opinion the best solution is to contain within implementation name some information, what's going on in that particular implementation (like we have with List interface and implementations: ArrayList or LinkedList), but sometimes you have just one implementation and have to have interface due to remote usage (for example), then (as mentioned at the beginning) Impl is the solution.

trying to use only one method name

When I was programming a Form Validator in PHP, when creating new methods, I needed to increase the number of arguments in old methods.
When I was learning Java, when I read that extends is to not touch previously tested, working code, I thought I shouldn't have increased the number of arguments in the old methods, but overridden the old methods with the new methods.
Imagine if you are to verify if a field is empty in one part of the form, in an other and in yet an other.
If the arguments are different, you'll overload isEmpty, but, if the arguments are equal, is it right to use isEmpty, isEmpty2, isEmpty3, three classes and one isEmpty per class or, if both are wrong, what should I have done?
So the question is:
If I need different behaviors for a method isEmpty which receives the same number arguments, what should I do?
Use different names? ( isEmpty, isEmpty2, isEmpty3 )
Have three classes with a single isEmpty method?
Other?
If that's the question then I think you should use:
When they belong to the same logical unit ( they are of the same sort of validation ) but don't use numbers as version, better is to name them after what they do: isEmptyUser, isEmptyAddress, isEmptyWhatever
When the validator object could be computed in one place and passed around during the program lifecycle. Let's say: Validator v = Validator.getInstance( ... ); and then use it as : validator.isEmpty() and let polymorphism to it's job.
Alternatively you could pack the arguments in one class and pass it to the isEmpty method, although you'll end up with pretty much the same problem of the name. Still it's easier to refactor from there and have the new class doing the validation for you.
isEmpty( new Arguments(a,b,c ) ); => arguments.isEmpty();
The Open/Closed Principle [usually attributed to Bertrand Meyer] says that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification". This might be the principle that you came across in your Java days. In real life this applies to completed code where the cost of modification, re-testing and re-certification outweighs the benefit of the simplicity gained by making a direct change.
If you are changing a method because it needs an additional argument, you might choose to use the following steps:
Copy the old method.
Remove the implementation from the copy.
Change the signature of the original method to add the new argument.
Update the implementation of the original method to use the new argument.
Implement the copy in terms of the new method with a default value for the argument.
If your implementation language doesn't support method overloading then the principle is the same but you need to find a new name for the new method signature.
The advantage of this approach is that you have added the new argument to the method, and your existing client code will continue to compile and run.
This works well if there is an obvious default for the new argument, and less well if there isn't.
Since java 5 you can use variable list of arguments as in void foo(Object ... params)
You will need to come up with creative names for your methods since you can't overload methods that have same type and number of arguments (or based on return type). I actually personally prefer this to overloading anyway. So you can have isEmpty and isEmptyWhenFoo and isEmptyWhenIHaveTheseArguments (well meybe not the last one :)
Not sure if this actually answers your question, but the best way to think about OO in "real life" is to think of the Nygaard Classification:
ObjectOrientedProgramming. A program execution is regarded as a physical model, simulating the behavior of either a real or imaginary part of the world.
So how would you build a physical device to do what you are trying to do in code? You'd probably have some kind of "Form" object, and the form object would have little tabs or bits connected to it to represent the different Form variables, and then you would build a Validator object that would take the Form object in a slot and then flash one light if the form was valid and another if it was invalid. Or your Validator could take a Form object in one slot and return a Form object out (possibly the same one), but modified in various ways (that only the Validator understood) to make it "valid". Or maybe a Validator is part of a Form, and so the Form has this Validator thingy sticking out of it...
My point is, try to imagine what such a machine would look like and how it would work. Then think of all of the parts of that machine, and make each one an object. That's how "object-oriented" things work in "real life", right?
With that said, what is meant by "extending" a class? Well, a class is a "template" for objects -- each object instance is made by building it from a class. A subclass is simply a class that "inherits" from a parent class. In Java at least, there are two kinds of inheritance: interface inheritance and implementation inheritance. In Java, you are allowed to inherit implementation (actual method code) from at most one class at a time, but you can inherit many interfaces -- which are basically just collections of attributes that someone can see from outside your class.
Additionally, a common way of thinking about OO programming is to think about "messages" instead of "method calls" (in fact, this is the original term invented by Alan Kay for Smalltalk, which was the first language to actually be called "object-oriented"). So when you send an isEmpty message to the object, how do you want it to respond? Do you want to be able to send different arguments with the isEmpty message and have it respond differently? Or do you want to send the isEmpty message to different objects and have them respond differently? Either are appropriate answers, depending on the design of your code.
Instead having one class providing multiple versions of isEmpty with differing names, try breaking down your model into a finer grained pieces the could be put together in more flexible ways.
Create an interface called Empty with
one method isEmpty(String value);
Create implemntations of this
interface like EmptyIgnoreWhiteSpace
and EmptyIgnoreZero
Create FormField
class that have validation methods
which delegate to implementations of
Empty.
Your Form object will have
instances of FormField which will
know how to validate themselves.
Now you have a lot of flexibility, you can combine your Empty implemenation classes to make new classes like EmptyIgnoreWhiteSpaceAndZero. You can use them in other places that have nothing to do with form field validation.
You don't have have have multple similarly named methods polluting your object model.

Categories

Resources