Validate value objects (inheritance) in java - java

I want to validate my domain objects before I pass them on to a other part of the system. All the objects that I want to validate share the same interface. The problem is that I can't figure out how to write this in a good way. I don't want to move the validation inside my value object. But I don't want to be forced to do a instanceOf-check either.
An example:
public interface Vehicle {}
public class Car implements Vehicle {}
public class MotorBike implements Vehicle {}
public interface VehicleValidator {
void validate();
}
public class CarValidator implements VehicleValidator {
#Override
public void validate() {}
}
public class MotorBikeValidator implements VehicleValidator {
#Override
public void validate() {}
}
public void process(Vehicle vehicle) {
//TODO: validate vehicle
doSomething(vehicle);
}
In Scala I would have done something similar to http://debasishg.blogspot.se/2010/06/scala-implicits-type-classes-here-i.html
But those language constructs is not possible in Java.

This is a classic case for the Double Dispatch design pattern.
You need to add a tiny bit of call-back code in the vehicle, which will be dynamically bound to the appropriate method of the validator at runtime:
public interface Vehicle {
void validate(Validator validator);
}
public class Car implements Vehicle {
public void validate(Validator validator) {
validator.validateCar(this);
}
}
public class MotorBike implements Vehicle {
public void validate(Validator validator) {
validator.validateMotorBike(this);
}
}
public class Validator {
public void validateCar(Car car) {
// validate a car
}
public void validateMotorBike(MotorBike motorBike) {
// validate a motorbike
}
}
public void process(Vehicle vehicle) {
Validator validator = new Validator();
vehicle.validate(validator);
doSomething(vehicle);
}

As Oli Charlesworth wrote in his comment, this is usually done by Visitor pattern. http://en.wikipedia.org/wiki/Visitor_pattern
There is good java example on that wiki page.

Your best bet is a strategy pattern imo, however this won't get you away from doing instanceof/isAssignableFrom checks. However, if you build it well, at least you can abstract it out some, handle it generically, and not have to worry about adding additional checks if you add additional vehicle types.
I could go on to explain strategy patterns, but it's done better here: http://www.javacodegeeks.com/2012/04/strategy-pattern.html (with spring)
Many frameworks will have classes out-of-the-box to facilitate this.

Related

Java: polymorphically call super implementation

Suppose I have this:
public class A {
public String foo() { return "A"; }
}
public class B extends A {
public String foo() { return "B"; }
public String superFoo() { return super.foo(); }
}
public class C extends B {
public String foo() { return "C"; }
}
Here, new C().superFoo() returns "A".
Is there a way I can polymorphically make new C().superFoo() invoke B.foo() (and hence return "B") without the need to override superFoo() in C?
I tried with reflection (redefining B.superFoo() like this: return getClass().getSuperclass().getDeclaredMethod("foo").invoke(this)), hoping that with getDeclaredMethod I could reference the exact method implementation in superclass, but I get "C" in that case (hence, polymorphism is applied).
I was searching for a solution that doesn't require me to redeclare superFoo() whenever I add a new subclass to the hierarchy.
TL;DR
Going through the question and comments, it seems like the ask here is to incrementally build up on a behavior. Taking a different perspective, I would prefer Composition over Inheritance in this scenario.
You can use Decorator pattern and compose the instances together; which in turn gives you a reference to the parent's foo() implementation. One of the other benefits is that you can extend/change the behavior at runtime, which is not possible with a static inheritance design.
About Decorator Pattern
Decorator pattern can be used to attach additional responsibilities to an object either statically or dynamically.
Component - Interface for objects that can have responsibilities added to them dynamically.
ConcreteComponent - Defines an object to which additional responsibilities can be added.
Decorator - Maintains a reference to a Component object and defines an interface that conforms to Component's interface.
Concrete Decorators - Concrete Decorators extend the functionality of the component by adding state or adding behavior.
Sample Code
Let's take a Pizza baking process as an example.
Component interface - Defines the contract that a Pizza must be baked.
public interface Pizza {
void bake();
}
ConcreteComponent class - This is your implementation of the interface which can stand alone by itself. It should not extend the Decorator and it appears at the innermost position when the objects are composed together (see client code at the end)
public class VeggiePizza implements Pizza {
#Override
public void bake() {
System.out.println("I'm a Veggie Pizza in the making :)");
}
}
Decorator - Specifies a contract for extending the functionality of the ConcreteComponent.
public abstract class Topping implements Pizza {
private Pizza pizza;
public Topping(Pizza pizza) {
this.pizza = pizza;
}
#Override
public void bake() {
pizza.bake();
}
}
Concrete Decorator - These implementations add to the functionality of the ConcreteComponent by nesting their constructors together (one of the ways to compose!). The concrete decorator can appear anywhere while composing, except for the innermost position (see client code below).
Here we are defining two toppings - Mushroom and Jalapeno.
public class Mushroom extends Topping {
public Mushroom(Pizza pizza) {
super(pizza);
}
#Override
public void bake() {
addMushroom();
super.bake();
}
private void addMushroom() {
System.out.println("Adding mushrooms...");
}
}
public class Jalapeno extends Topping {
public Jalapeno(Pizza pizza) {
super(pizza);
}
#Override
public void bake() {
addJalapenos();
super.bake();
}
private void addJalapenos() {
System.out.println("Adding jalapenos...");
}
}
Client code - How do you compose the ConcreteDecorator and ConcreteComponenttogether?
public void bakePizza() {
Pizza pizza = new Mushroom(new Jalapeno(new VeggiePizza()));
pizza.bake();
}
Notice that we build upon the VeggiePizza by wrapping the objects around with additional behavior from Mushroom and Jalapeno. Here, the ConcreteComponent is the innermost VeggiePizza, while our ConcreteDecorators are Jalapeno and Mushroom.
Note: Constructor composition is only one of the ways to compose. You can compose object together via setters or use a Dependency Injection framework.
Output
Adding mushrooms...
Adding jalapenos...
I'm a Veggie Pizza in the making :)
Following will return B though I've omitted various safety features for the sake of brevity and used commons-lang because you don't want to have to do this stuff yourself! At a minimum, this code assumes every class defines foo() and the you never directly call a.superFoo()! :)
public String superFoo() {
return superXXX("foo");
}
private <T> T superXXX(String name, Object... args) {
Method overriddenMethod = MethodUtils.getAccessibleMethod(getClass(), name);
Iterator<Method> methods = MethodUtils.getOverrideHierarchy(overriddenMethod, EXCLUDE).iterator();
methods.next(); // this is C
Method parentMethod = methods.next(); // This is B;
try {
return (T)parentMethod.invoke(this, args);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
FYI. There may well be an AspectJ/Javassist/Bytebuddy style solution possible as well whereby you can reimplement the superFoo method on all children of A to be super.foo()

Java 8: looking for a design pattern to reduce code duplication

I'm having the following test classes. I'm wondering if there's a design pattern that can reduce the code duplication in the following scenario.
public abstract class BaseTestClass {
protected String color;
protected String type;
protected Product product;
abstract void setColor();
abstract void setClothType();
abstract Product createTheProduct();
#BeforeClass
public void setUp(){
// there're partial overlaps of "setup" for pants and shirts
}
#Test
public void doATest(){
testSomethingWithProduct(product);
}
#AfterClass
public void tearDown(){
// there're partial overlaps of "tearDown" for pants and shirts
}
}
public class TestBlueShirt extends BaseTestClass {
#Override
void setColor() {
this.color = "blue";
}
#Override
void setClothType() {
this.type = "shirt";
}
#Override
Product createTheProduct() {
setColor();
setClothType();
// create this.product based on color and type...
}
}
public class TestRedShirt extends BaseTestClass {}
public class TestBluePants extends BaseTestClass {}
public class TestRedPants extends BaseTestClass {}
...
You will find there's duplicated code when setting colors for the same type of cloth or when setting the type for the same color. I'm wondering how I can have a concrete class that can produce something like Class<T> (RedShirt, BlueShirt, RedPants, etc.), and based on Class<T>, I can directly implement #Test in the base class. So I can avoid code duplication as much as I can.
something like:
public abstract class BaseTestClass {
protected Product product;
abstract Product createTheProduct(Class<T> ...);
#BeforeClass
public void setUp(){
setUpBasedOnProduct(Class<T> ...);
}
#Test
public void doATest(){
testSomethingWithProduct(product);
}
#AfterClass
public void tearDown(){
tearDownBasedOnProduct(Class<T> ...);
}
}
import ...ClassGenerator
public class TestBlueShirt extends BaseTestClass {
#Override
createTheProduct(ClassGenerator.createClass("blue", "shirt"));
}
Thanks in advance!
You want to create an object, so what you're looking for falls under the umbrella of creational design patterns. I'm not sure if there's a perfect fit for your needs, but the Factory pattern matches some of your needs.
In a typical Factory pattern use case, you would supply a type (as a String or enumeration) to a method, and receive a matching object. Your logic would be a little more complex in that there will be several inputs and some branching logic to locate the correct type. For example, you can't just use a String "shirt" to get your object since the color is built into the types (you have RedShirt, BlueShirt, etc...).
As a final note, I'd consider asking yourself why RedShirt and BlueShirt have to be of different types. Rather than using a design pattern to get around the issue, I'd reconsider the original design. For example, you could use an Apparel extends Product class containing a color and type member, such that you can query that information regardless of the type of Apparel. Of course, use your best judgement depending on your situation.

Partial implementation of interface

I have an Inreface say
public interface myInterfacy {
String kilogramToGram();
Long litresTomiliLitres();
String inchesToMillimeters();
String ouncesToGrams();
}
I need to have multiple implementaton of this interface but I want the partial implementation of this inteface on different implementation,
As:
public class A implements myInterfacy {
public String kilogramToGram(){
//code
};
I don't want to give the definition of other methods.
}
public class B implements myInterfacy {
Long litresTomiliLitres(){
//code
};
I don't want to give the definition of other methods.
}
I thought that I can di it via using an abstract class, but I wonder If any other good approach is possible.
The answer is relatively simple but has many options.
You could
Make a number of partial interfaces and the one that "does it all" implements them all (not great)
You could make a number of "dummy" interfaces which throw an exception of unimplemented functionality. So, every proxy class would implement the full interface but throw runtime errors on unsupported methods (also not great)
Simply do nothing - literally. Implement the full interface and provide empty bodies (also really not great)
Or, you could encapsulate the functionality with a specific proxy to provide the given functionality.For example,
class FullyFunctional {
public void foo() {...}
public void bar() {...}
}
class PartiallyFunctional {
FullyFunctional ff;
public PartiallyFunctional(FullyFunctional ff) {
this.ff = ff;
}
// No foo...
public void bar() { ff.bar(); }
}
One way to do this, is with a convenience base class. This is however not really a good idea, because you won't get compile type checking to help ensure that you don't call unimplemented method.
public interface Converter {
public String kilogramToGram();
public long litresTomiliLitres();
public String inchesToMillimeters();
public String ouncesToGrams();
}
public abstract class AbstractConverter implements Converter {
#Override
public String kilogramToGram() {
throw new UnsupportedOperationException();
}
#Override
public long litresTomiliLitres() {
throw new UnsupportedOperationException();
}
#Override
public String inchesToMillimeters() {
throw new UnsupportedOperationException();
}
#Override
public String ouncesToGrams() {
throw new UnsupportedOperationException();
}
}
public final class A extends AbstractConverter {
#Override
public String kilogramToGram() {
//code
}
}
Follow interface-segregation-principle
Divide fat interface into granular small interfaces
Implement only require interface
One extreme case: I will declare four interfaces for four methods
public interface IKGToGram {
String kilogramToGram();
}
public interface ILitersToMilliLeters{
Long litresTomiliLitres();
}
public interface IInchesToMilliMeters{
String inchesToMillimeters();
}
public interface IOunceToGrams{
String ouncesToGrams();
}
Now you can implement whatever interface set you want to.
Have a look at explanation about interface segregation concept:
Interface Segregation Principle- Program to an interface

Is there a pattern for this? Common base class with special actions for certain child classes

I have code that when given a thing it needs to sort out what specific kind of thing it is and then take special actions based on that. The possible classes it could be are all desc
public void doSomething(BaseThing genericThing)
{
if (genericThing instanceof SpecificThing)
{
SpecificThingProcessor stp = new SpecificThingProcessor((SpecificThing) genericThing);
}
else if (genericThing instanceof DifferentThing)
{
DifferentThingProcessor dtp = new DifferentThingProcessor((DifferentThing) genericThing);
}
else if (genericThing instanceof AnotherThing){
AnotherThingProcessor atp = new AnotherThingProcessor((AnotherThing) genericThing);
}
else
{
throw new IllegalArgumentException("Can't handle thing!");
}
}
Is there a pattern or better way of handling this? Unfortunately the operations being performed do not lend themselves to generalization around the BaseThing, they have to be done for each specific class of thing.
The best option I can think of is to abstract the functionality in to an Interface and have each type implement that Interface.
If you add a little more detail about what you're trying to do based on the types, I could make a better suggestion (possibly with some sample code).
EDIT
After the edit, there is definitely a clear way to do this. Each Processor will implement a specific Interface:
public interface IProcessor
{
void Process();
}
public class SpecificThingProcessor : IProcessor
{
public void Process() { /* Implementation */ }
}
public class DifferentThingProcessor : IProcessor
{
public void Process() { /* Implementation */ }
}
public class AnotherThingProcessor : IProcessor
{
public void Process() { /* Implementation */ }
}
Each BaseThing must implement a method to return the specific processor:
public abstract class BaseThing
{
public abstract IProcessor GetProcessor();
}
public class SpecificThing : BaseThing
{
public override IProcessor GetProcessor()
{
return new SpecificThingProcessor();
}
}
public class DifferentThing : BaseThing
{
public override IProcessor GetProcessor()
{
return new DifferentThingProcessor();
}
}
And then your method will simply be:
public void doSomething(BaseThing genericThing)
{
IProcessor processor = genericThing.GetProcessor();
processor.Process();
}
You should define a method in BaseThing to be overridden by the specific Things.
In other words you should be using a virtual function.
The operations being performed are not
being performed on the generic thing.
Depending on its specific type, a
"Producer" class needs to be
instantiated to deal with the correct
type of thing. It is not appropriate
to call the Producer from the
BaseThing subclasses
You can still do: thing.GetProcessor(), and have each thing return the specific processor its used for it. Processors would of course implement a common interface or base class.
For another alternative, this hits my java limit, but I'm sure you should be able to do something along these lines:
store a list/dictionary of type, processor constructor.
Get the type of genericThing instance you are receiving
search for the type in the list and call the corresponding constructor.
The visitor pattern is exactly what you're trying to achieve. However, a "good old-fashioned polymorphism" should do just fine for what you need. For example :
abstract class BaseThing {
abstract public void doSomething();
}
class ThingA extends BaseThing {
public void doSomething() {
System.out.println("ThingA...");
}
}
class ThingB extends BaseThing {
public void doSomething() {
System.out.println("ThingB...");
}
}
class ThingC extends BaseThing {
public void doSomething() {
throw new UnsupportedOperationException("Cannot call this on ThingC");
}
}
and then
class ThingHandler {
public void doSomething(BaseThing thing) {
try {
thing.doSomething();
} catch (UnsupportedOperationException e) {
throw new IllegalArgumentException("Can't handle thing!");
}
}
}
Thus
ThingHandler handler = new ThingHandler();
handler.doSomething(new ThingA()); // -> ThingA...
handler.doSomething(new ThingB()); // -> ThingB...
handler.doSomething(new ThingC()); // -> IllegalArgumentException: Can't handle thing!
You have mentioned "it needs to sort out what specific kind of thing it is", so all you need now is have your BaseThing have an abstract method that will return a Comparator and each ThingA, etc. will implement it and return the proper comparator for the ThingHandler class to sort. Each BaseThing implementation can perform the specific operations or return some kind of value that you'd need in ThingHandler (you could even pass the ThingHandler instance in the BaseThing.doSomething method...)
But if the Visitor pattern is really what you need, here is an example for your need :
interface IThing {
public void accept(ThingHandler handler);
}
interface IThingHandler {
public void visit(ThingA a);
public void visit(ThingB b);
//...
}
class ThingA implements IThing {
public void accept(IThingHandler h) {
h.visit(this);
}
public String getSomeValueA() {
return "Thing A";
}
}
class ThingB implements IThing {
public void accept(IThingHandler h) {
h.visit(this);
}
public String getSomeValueB() {
return "Thing B";
}
}
// ...
class ThingHandler implements IThingHandler {
public void visit(ThingA thing) {
// sort according to ThingA
System.out.println(thing.getSomeValueA() + " has visited");
doSomething(thing);
}
public void visit(ThingB thing) {
// sort according to ThingB
System.out.println(thing.getSomeValueB() + " has visited");
doSomething(thing);
}
private void doSomething(IThing thing) {
// do whatever needs to be done here
}
}
Then
IThingHandler handler = new ThingHandler();
new ThingA().accept(handler); // -> Thing A has visited
new ThingB().accept(handler); // -> Thing B has visited
//...
But since this means maintaining the IThingHandler interface every time a new IThing class is implemented, I prefer suggesting the first modified/simplified implementation of the pattern. However, feel free to adapt the pattern for your need and don't stop yourself because it doesn't exactly look like the described visitor pattern.
The two questions to ask are
"who is responsible to handle the operation?"
"who is responsible to hold the necessary data to perform the operation?"
I usually prefer keeping most of the concrete at the same place and generalize elsewhere; it helps maintaining (i.g. adding and removing features). Although the visitor pattern helps to centralize the operation in a same class...
This sounds like one of the basic ideas of object-oriented programming. You create a superclass that declares doSomething, and then you create subclasses each of which implements it differently. That is:
public class BaseThing
{
abstract public void doSomething();
}
public class SpecificThing extends BaseThing
{
public void doSomething()
{
System.out.println("I'm a SpecificThing!");
}
}
public class DifferentThing extends BaseThing
{
public void doSomething()
{
System.out.println("I'm a DifferentThing!");
}
}
public class AnotherThing extends BaseThing
{
public void doSomething()
{
System.out.println("I'm an AnotherThing!");
}
}
If you really need to pass the "thing" as a parameter for some reason, okay. Do the above, then write:
void doSomething(BaseThing genericThing)
{
genericThing.doSomething();
}
If some of your subclasses can't do the function and should give an error message instead, then just instead of making it abstrct in the supertype, make the supertype do the "invalid" processing, like:
public void BaseThing
{
public void doSomething()
throws IllegalArgumentException
{
throw new IllegalArgumentException("Can't handle this thing");
}
}
The question is almoust the text-book example of Strategy-pattern. You extract the specific behavoir into separate classes that al implement the same interface (with a method like doIt() of something). And then you give each specific class a reference to the "behavior"-object you want it to have.
Bonus:
1) You can change the behavior of an object at runtime by simply given it another "behavior"-object.
2) You don't have to override a method (danger with overriding methods could be class-booming).
This could be dealt with using plain old OO polymorphism before trying to force a pattern onto it.
You don't need to necessarily subclass the processors, you can overload the method declarations in a single Processor class keeping the method name the same but declaring the parameter for the specific type.
void foo(BaseTing ting) { System.out.println("Default " + ting.name); }
void foo(TingA ting) { System.out.println("AA " + ting.name); }
void foo(TingB ting) { System.out.println("BB " + ting.name); }
Java will resolve the method that most closely matches the parameter type, so if you have TingC that extends TingB, then foo(TingB) will be invoked until foo(TingC) is defined in the Processor class.
If you are going to add a lot more actions for each type of thing, i.e. baz(Ting), bar(Ting), bat(Ting) etc. then you may want to split you Processor classes by Ting subtype and use a factory method to create the specific processor a la Strategy pattern.
i.e. BaseProcessor, TingAProcessor, TingBProcessor.
The BaseProcessor would be a good candidate to house the factory method, and should provide default implementations for each of the methods, even if the default implementation is abstract or just throws an exception. The specialised Processors classes should extend from the BaseProcessor and inherit and override the default operations.
You have few options:
* Abstract your functionality into an interface and let other classes implement that interface.
* You could use The Chain of responsibility pattern(consisting of a source of command objects and a series of processing objects).
* You could also use the Strategy design pattern( algorithms can be selected at runtime)

How to use java interfaces with multiple implementing classes

public interface Foo {
}
public class SpecificFoo implements Foo {
}
public interface SomeInterface {
void thisMethod(Foo someKindOfFoo);
}
public class SomeClass implements SomeInterface {
public void thisMethod(Foo someKindOfFoo) {
// calling code goes into this function
System.out.println("Dont go here please");
}
public void thisMethod(SpecificFoo specificFoo) {
// not into this function
System.out.println("Go here please");
}
}
public class SomeOlderClass {
public SomeOlderClass( SomeInterface inInterface ) {
SpecificFoo myFoo = new SpecificFoo();
inInterface.thisMethod(myFoo);
}
}
calling code:
SomeClass myClass = new SomeClass();
SomeOlderClass olderClass = new SomeOlderClass(myClass);
I have an interface (SomeInterface) that several classes call into (such as SomeOlderClass). I have a class that implements the interface, but I want to do type safe operations on the specific implementations that are passed into the generic interface.
As shown in the above code, I really want to able to make another method that matches the specific type passed in to the interface. This doesn't work. I assume it is because the calling code only knows about the interface, and not the implementation with the more specific methods (even though SpecificFoo implements Foo)
So how can I do this in the most elegant way? I can get the code working by adding an if statement in the class implementing the interface (SomeClass):
public void thisMethod(Foo someKindOfFoo) {
// calling code goes into this function
if ( someKindOfFoo.getClass().equals(SpecificFoo.class) )
thisMethod(SpecificFoo.class.cast(someKindOfFoo));
else
System.out.println("Dont go here please");
}
However, this is not elegant, as I have to add if statements everytime I add a new kind of Foo. And I might forget to do so.
The other option is to add SpecificFoo to the SomeInterface, and let the compiler sort out reminding me that I need implementations in SomeClass. The problem with this is that I end up adding quite a bit of boiler plate code. (If someone else implements the interface, they have to implement the new method, as well as any tests)
It seems that there should be another option I am missing, given that Foo and SpecificFoo are related. Ideas?
MORE INFO:
Well I actually worked for a while to try and simplify the question. As I add more details the complexity goes up by quite a bit. But whatever... I think I can explain it.
Basically, I am write a GWT web apps RPC servlet using the command pattern as explained by Ray Ryan in his talk
There are several implementations of it on google code, but many of them suffer this inherit problem. I thought it was a bug in the GWT-RPC code bugreport HOWEVER, as I was implementing further I noticed a similar problem happening purely on the client side, and while in hosted mode. (ie all java, no gwt javascript madness).
So I abstracted the basic ideas to a raw java command line case, and saw the same issue, as described above.
If you follow along with what Ray Ryan discusses, Foo is an Action, SpecificFoo is a specific action I want to call. SomeInterface is the client side RPC service and SomeClass is the server side RPC class. SomeOlderClass is a kind of rpc service that would know about cacheing and whatnot.
Obvious, right? Well as I said, I think all the GWT RPC nonsense just muddies up the waters on the base issue, which is why I tried to simplify it as best I could.
If you need to find out the actual type of an object at runtime, then the design is most probably wrong. That violates at least the Open Closed Principle and Dependency Inversion Principle.
(Because Java does not have multiple dispatch, the thisMethod(Foo)will be called instead of thisMethod(SpecificFoo). Double dispatch could be used to get around the language's limitations, but there might still be some design problem lurking there...)
Please give more information on what you are trying to accomplish. Right now the question does not provide enough information to come up with a right design.
A generic solution is that since the action depends on the runtime type of Foo, that method should be part of Foo so that its implementation can vary depending on Foo's type. So your example would be changed to something like below (possibly adding SomeInterface or other parameters to thisMethod()).
public interface Foo {
void thisMethod();
}
public class SpecificFoo implements Foo {
public void thisMethod() {
System.out.println("Go here please");
}
}
Try using double dispatch: Add a method to the Foo interface that is called by SomeClass#thisMethod. Then place the code in the implementation of this method.
public interface Foo {
public void thatMethod(SomeClass a);
public void thatMethod(SomeOlderClass a);
}
public class SomeClass implements SomeInterface {
public void thisMethod(Foo someKindOfFoo) {
someKindOfFoo.thatMethod(this);
}
}
Sorry, I find the problem description far too abstract to be able to make a recommendation. You clearly have a design issue because you generally should not need to check the type of interface. I will give it a go though... First, I need to make your problem more concrete for my small brain to understand. Instead of Foos, how about Birds?
public interface Bird {
}
public class Ostrich implements Bird {
}
public interface BirdManager {
void fly(Bird bird);
}
public class AdvancedBirdManager implements BirdManager {
public void fly(Bird bird) {
System.out.println("I am in the air. Yay!");
}
public void fly(Ostrich ostrich) {
System.out.println("Sigh... I can't fly.");
}
}
public class ZooSimulation {
public ZooSimulation(BirdManager birdManager) {
Ostrich ostrich = new Ostrich();
birdManager.fly(ostrich);
}
}
public static void main(String[] args) {
AdvancedBirdManager advancedBirdManager = new AdvancedBirdManager();
ZooSimulation zooSimulation = new ZooSimulation(advancedBirdManager);
}
Here, the Ostrich will declare "I am in the air. Yay!" which is not what we want.
OK, so, ignoring the fact that I am failing basic OO here, the problem is that the BirdManager will look for the least-specific method that matches the type that is passed in. So no matter what kind of bird I give it, it will always match fly(Bird). We can put some if checks in there, but as you add more types of birds, your design will degrade further. Here's the tough part - I have no idea if this makes sense within the context of your problem, but consider this refactoring where I move the logic from the manager into bird:
public interface Bird {
void fly();
}
public class BasicBird implements Bird {
public void fly() {
System.out.println("I am in the air. Yay!");
}
}
public class Ostrich implements Bird {
public void fly() {
System.out.println("Sigh... I can't fly.");
}
}
public interface BirdManager {
void fly(Bird bird);
}
public class AdvancedBirdManager implements BirdManager {
public void fly(Bird bird) {
bird.fly();
}
}
public class ZooSimulation {
public ZooSimulation(BirdManager birdManager) {
Ostrich ostrich = new Ostrich();
birdManager.fly(ostrich);
}
}
public static void main(String[] args) {
AdvancedBirdManager advancedBirdManager = new AdvancedBirdManager();
ZooSimulation zooSimulation = new ZooSimulation(advancedBirdManager);
}
Our Ostrich now says the correct thing and the bird manager still treats it as just a bird. Again, bad OO (Ostriches should not have fly() methods) but it illustrates my thoughts.
As long as there are not too many implementations of Foo, I would declare an abstract method in SomeInterface for each subclass of Foo, and have an abstract class forward calls to a default method that is defined for the most general type:
public interface Foo {
}
public class SpecificFoo implements Foo {
}
public interface SomeInterface {
void thisMethod(Foo someKindOfFoo);
void thisMethod(SpecificFoo specificFoo);
void thisMethod(OtherSpecificFoo otherSpecificFoo);
}
public abstract class AbstractSomeInterface {
public void thisMethod(Foo wrongFoo) {
throw new IllegalArgumentException("Wrong kind of Foo!");
}
public void thisMethod(SpecificFoo specificFoo) {
this.thisMethod((Foo) specificFoo);
}
public void thisMethod(OtherSpecificFoo otherSpecificFoo) {
this.thisMethod((Foo) specificFoo);
}
}
public class SomeClass extends AbstractSomeInterface {
public void thisMethod(SpecificFoo specificFoo) {
// calling code goes into this function
System.out.println("Go here please");
}
}
public class SomeOlderClass {
public SomeOlderClass( SomeInterface inInterface ) {
SpecificFoo myFoo = new SpecificFoo();
inInterface.thisMethod(myFoo);
}
}

Categories

Resources