How to deal with Java Polymorphism in Service Orie

2020-02-23 08:21发布

问题:

What is the path of least evil when dealing with polymorphism and inheritance of entity types in a service-oriented architecture?

A principle of SOA (as I understand it) is to have entity classes as mere data constructs, lacking in any business logic. All business logic is contained in narrow-scoped, loosely-coupled services. This means service implementations are as small as possible furthering the loose coupling, and means the entities avoid having to know about every behaviour the system may perform on them.

Due to Java's quite baffling decision to use the declared type when deciding which overloaded method to use, any polymorphic behaviour in the service implementations is instead replaced with a series of conditionals checking object.getClass() or using instanceof. This seems rather backward in an OOPL.

Is the use of conditionals the accepted norm in SOA? Should inheritance in entities be abandoned?

UPDATE

I definitely mean overloading and not overriding.

I define SOA to mean that behaviour of the system is grouped by use case into interfaces, and then the logic for these is implemented in one class per interface, generally. As such an entity class (say Product) becomes nothing more than a POJO with getters and setters. It absolutely should not contain any business logic related to a service, because then you introduce one focal point of coupling whereby the entity class needs to know about all business processes that may ever operate on it, completely negating the purpose of a loosely-coupled SOA.

So, being that one should not embed business process-specific behaviour in an entity class, one cannot use polymorphism with these entity classes - there is no behaviour to override.

UPDATE 2

The above behaviour is more simply explained as an overloaded path is chosen at compile-time, and an overridden path at run-time.

It'd be bad practice to have a subclass of your service implementation for each subtype of the domain model class it's acting on, so how do people get around the overloading-at-compile-time issue?

回答1:

It took me a while from reading this to work out what you were really asking for.

My interpretation is that you have a set of POJO classes where when passed to a service you want the service to be able to perform different operations depending on the the particular POJO class passed to it.

Usually I'd try and avoid a wide or deep type hierarchy and deal with instanceof etc. where the one or two cases are needed.

When for whatever reason there has to be a wide type hierarchy I'd probably use a handler pattern kind of like below.

class Animal {

}
class Cat extends Animal {

}

interface AnimalHandler {
    void handleAnimal(Animal animal);
}

class CatHandler implements AnimalHandler {

    @Override
    public void handleAnimal(Animal animal) {
        Cat cat = (Cat)animal;
        // do something with a cat
    }

}

class AnimalServiceImpl implements AnimalHandler {
    Map<Class,AnimalHandler> animalHandlers = new HashMap<Class, AnimalHandler>();

    AnimalServiceImpl() { 
        animalHandlers.put(Cat.class, new CatHandler());
    }
    public void handleAnimal(Animal animal) {
        animalHandlers.get(animal.getClass()).handleAnimal(animal);
    }
}


回答2:

You can avoid this problem by designing the business logic in different classes based on the entity type, based on single responsibility principle it would be the best way to go when you place business logic in a service layer and use a factory to create logic implementation, for example

enum ProductType
{
    Physical,
    Service
}


interface IProduct
{
    double getRate();
    ProductType getProductType();    
}

class PhysicalProduct implements IProduct
{
    private double rate;

    public double getRate()
    {
        return rate;
    }

    public double getProductType()
    {
        return ProductType.Physical;
    }
}

class ServiceProduct implements IProduct 
{
    private double rate;
    private double overTimeRate;
    private double maxHoursPerDayInNormalRate;

    public double getRate()
    {
        return rate;
    }

    public double getOverTimeRate()
    {
        return overTimeRate;
    }

    public double getMaxHoursPerDayInNormalRate;()
    {
        return maxHoursPerDayInNormalRate;
    }

    public double getProductType()
    {
        return ProductType.Service;
    }
}

interface IProductCalculator
{
    double calculate(double units);
}

class PhysicalProductCalculator implements IProductCalculator
{
    private PhysicalProduct product;

    public PhysicalProductCalculator(IProduct product)
    {
        this.product = (PhysicalProduct) product;
    }

    double calculate(double units)
    {
        //calculation logic goes here
    }
}

class ServiceProductCalculator implements IProductCalculator
{
    private ServiceProduct product;

    public ServiceProductCalculator(IProduct product)
    {
        this.product = (ServiceProduct) product;
    }

    double calculate(double units)
    {
        //calculation logic goes here
    }
}

class ProductCalculatorFactory
{
    public static IProductCalculator createCalculator(IProduct product)
    {
        switch (product.getProductType)
        {
            case Physical:
                return new PhysicalProductCalculator ();
            case Service:
                return new ServiceProductCalculator ();
        }
    }
}

//this can be used to execute the business logic
ProductCalculatorFactory.createCalculator(product).calculate(value);


回答3:

Due to Java's quite baffling decision to use the declared type when deciding which overloaded method to use

Whoever gave you that idea? Java would be a worthless language if it were like that!

Read this: Java Tutorial > Inheritance

Here's a simple test program:

public class Tester{
    static class Foo {
        void foo() {
            System.out.println("foo");
        }
    }
    static class Bar extends Foo {
        @Override
        void foo() {
            System.out.println("bar");
        }
    }
    public static void main(final String[] args) {
        final Foo foo = new Bar();
        foo.foo();
    }
}

The Output is of course "bar", not "foo"!!



回答4:

I think there is a confusion of concerns here. SOA is an architectural way to solve interaction between components. Each component within a SOA solution will handle a context within a larger domain. Each context is a domain of it self. In other words, SOA is something that allows for lose coupling in between domain contexts, or applications.

Object Orientation in Java, when working in this kind of an environment, will apply to each domain. So hierarchies and rich domain objects modelled using something like domain driven design will live on a level below the services in a SOA solution. There is a tier between the service exposed to other contexts and the detailed domain model which will create rich objects for the domain to work with.

To solve each context/applications architecture with SOA will not provide a very good application. Just as solving the interaction between them using OO.

So to try to answer the bounty question more specifically: It's not a matter of engineering around the issue. It's a matter of applying the correct pattern to each level of design.

For a large enterprise ecosystem SOA is the way I would solve interaction in between systems, for example HR system and payroll. But when working with HR (or probably each context within HR) and payroll I would use the patterns from DDD.

I hope that clears the waters a bit.



回答5:

Having thought about this a bit more I've thought on an alternative approach that makes for a simpler design.

abstract class Animal {
}

class Cat extends Animal {
    public String meow() {
        return "Meow";
    }
}

class Dog extends Animal {
    public String  bark() {
        return "Bark";
    }
}

class AnimalService { 
    public String getSound(Animal animal) {
        try {
            Method method = this.getClass().getMethod("getSound", animal.getClass());
            return (String) method.invoke(this, animal);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public String getSound(Cat cat) {
        return cat.meow();
    }
    public String getSound(Dog dog) {
        return dog.bark();
    }
}

public static void main(String[] args) {
    AnimalService animalService = new AnimalService();
    List<Animal> animals = new ArrayList<Animal>();
    animals.add(new Cat());
    animals.add(new Dog());

    for (Animal animal : animals) {
        String sound = animalService.getSound(animal);
        System.out.println(sound);
    }
}