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.
validate() performs relayout. It means invalid content is asked for all the sizes and all the subcomponents' sizes are set to proper values by LayoutManager. revalidate() is just sum of both. It marks the container as invalid and performs layout of the container.
Validation verifies the definitions of both data objects and ETL objects and identifies any problems or possible errors that could occur during deployment. If objects are invalid, generation and deployment is not possible. You can validate objects and generate scripts for objects at any point in the design process.
A class in Java can be declared as a subclass of another class using the extends keyword. A subclass inherits variables and methods from its superclass and can use them as if they were declared within the subclass itself: class Animal { float weight ; ...
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With