Checking value objects (inheritance) in java

I want to check my domain objects before transferring them to another part of the system. All the objects I want to check use the same interface. The problem is that I cannot figure out how to write this in a good way. I do not want to move the check inside my value object. But I don’t want to be forced to check the instances.

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 do something similar to http://debasishg.blogspot.se/2010/06/scala-implicits-type-classes-here-i.html But these language constructs are not possible in Java.

+8
java inheritance design-patterns validation
source share
3 answers

This is the classic case for the Double Dispatch design template.

You need to add a tiny bit of callback code in the vehicle that will be dynamically bound to the appropriate validator method 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); } 
+2
source share

As Oli Charlworth wrote in his commentary, this is usually done using a visitor template. http://en.wikipedia.org/wiki/Visitor_pattern

There is a good java example on this wiki page.

0
source share

Your best bet is an imo strategy template, but that will not help you avoid instanceof / isAssignableFrom checks. However, if you build it well, at least you can abstract it, handle it in general, and not worry about adding extra checks if you add additional types of vehicles.

I could continue explaining the strategy templates, but here it was better: http://www.javacodegeeks.com/2012/04/strategy-pattern.html (with spring)

Out of the box classes will be created on many infrastructures to facilitate this.

0
source share

All Articles