简体   繁体   中英

What is the proper design to deal with this?

I'm working on a legacy Java application, that deals with "fruits" and "vegetables", let's say, for the sake of the question. They are treated as different things internally, cause they don't have all methods/properties in common, but a lot of things are DONE very similar to both of them.

So, we have a ton of methods doSomethingWithAFruit(Fruit f) and doSomethingWithAVegetable(Veg v) , that use the proper doOtherStuffWithAFruit(Fruit f) / doOtherStuffWithAVeg(Veg v) . And those are very similar, except that methods that do things with fruits only call the methods that do things with fruits, and the same thing for vegetables.

I want to refactor this to reduce the duplication, but I'm not sure what is the best way to accomplish that. I've read a bit about some design patterns, but I don't know if it has made any clearer to me. (I can recognize some patterns in the code I use, but I don't really know when I should be applying a pattern to improve things around. Maybe I should be reading more about refactoring itself...)

I was thinking of these two options:

1. Creating a class that can have an instance of either a Fruit or a Vegetable and pass it around to the methods, trying to minimize the duplication. It would go like this:

public void doSomething(Plant p) {
   // do the stuff that is  common, and then...
   if (p.hasFruit()) {
       doThingWithFruit(p.getFruit());
   } else {
       doThingWithVegetable(p.getVegetable());
   }
}

This would get things a bit better, but I don't know... it still feels wrong.

2. The other alternative I thought was to put an interface in Fruit and Vegetable with the stuff that is common to them, and use that to pass it around. I feel this is the cleaner approach, although I will have to use instanceof and cast to Fruit/Vegetable when it needs stuff that is specific to them.

So, what more can I do here? And what are the shortcomings of these approaches?

UPDATE: Note that the question is a bit simplified, I'm looking for way to do things WITH the "plants", that is, code that mostly "uses" them instead of doing things TO them. Having said that, those similar methods I refer to cannot be inside the "Plants" classes, and they usually have another argument, like:

public void createSomethingUsingFruit(Something s, Fruit f);
public void createSomethingUsingVegetable(Something s, Vegetable v);

Namely, those methods have other concerns besides Fruits/Vegetables, and aren't really appropriated to be in any Fruit/Vegetable class.

UPDATE 2: Most code in those methods only reads state from the Fruit/Vegetable objects, and create instances of other classes according to the appropriate type, store in the database and so on -- from my answer to a question in the comments that I think it's important .

I think the 2nd approach would be better.. Designing to an interface is always a better way to design.. That way you can switch between your implementation easily..

And if you use interfaces, you won't need to do typecast as you can easily exploit the concept of polymorphism .. That is, you will have `Base class reference pointing to a subclass object..

But if you want to keep only methods common to fruits and vegetables in your interface, and specific implementation in your implementation class.. Then in that case typecasting would be required..

So, you can have a generic method at interface level.. And more specific method at implementation level..

public interface Food {
    public void eat(Food food);
}

public class Fruit implements Food {

    // Can have interface reference as parameter.. But will take Fruit object    
    public void eat(Food food) {
        / ** Fruit specific task **/
    }
}

public class Vegetable implements Food {

    // Can have interface reference as parameter.. But will take Vegetable object
    public void eat(Food food) {
        /** Vegetable specific task **/
    }
}

public class Test {
    public static void main(String args[]) {
         Food fruit = new Fruit();
         fruit.eat(new Fruit());    // Invoke Fruit Version

         Food vegetable = new Vegetable();
         vegetable.eat(new Vegetable());   // Invoke vegetable version

    }
}

OK, I have modified a code to make eat() method to take parameters of type Food .. That will not make much of a difference.. You can pass Vegetable object to Food reference..

If you have functionality that is specific to fruits and vegetables respectively and a client using both types has to distinguish (using instanceof ) - that is a coherence vs. coupling problem.

Maybe consider if said functionality is not better placed near fruit and vegetable themselves instead of with the client. The client may then somehow be refered to the functionality (through a generic interface) not caring what instance he is dealing with. Polymorphism would be preserved at least from the client's perspective.

But that is theoretical and may not be practical or be over-engineered for your use case. Or you could end up actually just hiding instanceof somewhere else in your design. instanceof is going to be a bad thing when you start having more inheritance siblings next to fruits and vegetables. Then you would start violating the Open Closed Principle .

Another option you can use, or perhaps include it as part of your solution, is to ask the consumer if it can manage the object that you are passing it. At this point, it becomes the consumer's responsibility to ensure it knows how to handle the object you are sending it.

For instance, if your consumer is called Eat, you would do something like:

Consumer e = new Eat();
Consumer w = new Water();
if( e.canProcess( myFruit ) )
   e.doSomethingWith( myFruit );
else if ( w.canProcess( myFruit ) )
   w.doSomethingWith( myFruit );

.... etc

But then you end up with a lot of it/else classes, so you create yourself a Factory which determines which consumer you want. Your Factory basically does the if/else branching to determine which consumer can handle the object you pass, and returns the consumer to you.

So it looks something like

public class Factory {
   public static Consumer getConsumer( Object o ){
    Consumer e = new Eat();
    Consumer w = new Water();
    if( e.canProcess( o ) )
       return e;
    else if ( w.canProcess( o ) )
       return w;
   }
}

Then your code becomes:

Consumer c = Factory.getConsumer( myFruit );
c.doSomethingWith( myFruit );

Of course in the canProcess method of the consumer, it would be basically an instanceof or some other function your derive to determine if it can handle your class.

public class Eat implements Consumer{
   public boolean canProcess(Object o ){
     return o instanceof Fruit;
   }
}

So you end up shifting the responsibility from your class to a Factory class to determine which objects can be handled. The trick, of course, is that all Consumers must implement a common interface.

I realize that my pseudo-code is very basic, but it is just to point out the general idea. This may or may not work in your case and/or become overkill depending on how your classes are structured, but if well designed, can significantly improve readability of your code, and truely keep all logic for each type self-contained in their own class without instanceof and if/then scattered everywhere.

I would create and abstract base class (let's say - Food, but I don't know your domain, something else might fit better) and start to migrate methods to it one after another.

In case you see that 'doSomethingWithVeg' and 'doSomthingWithFruit' are slightly different - create the 'doSomething' method at the base class and use abstract methods to do only the parts that are different (I guess the main business logic can be united, and only minor issues like write to DB/file are different).

When you have one method ready - test it. After you're sure it's ok - go to the other one. When you are done, the Fruit and Veg classes shouldn't have any methods but the implementations of the abstract ones (the tiny differences between them).

Hope it helps..

This is a basic OOD question. since fruits and vegetables are of type Plant. I would suggest:

interface Plant {
    doSomething();
}

class Vegetable {
    doSomething(){
    ....
    }
}

and the same with the fruit.

it seems to me that doOtherStuff methods should be private for the relevant class.

You can also consider having them both implement multiple interfaces instead of just one. That way you code against the most meaningful interface according the circumstances which will help avoid casting. Kind of what Comparable<T> does. It helps the methods (like the ones that sort objects), where they don't care what the objects are, the only requirement is that they have to be comparable. eg in your case both can implement some interfaces called Edible , then take both of them as Edible where an Edible is expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM