My problem:
I have 2 defined classes
- CreateObjectRequest
- UpdateObjectRequest
that must be verified by an utility method.
As those 2 objects have the same fields, the same verify method can be applied on both types.
Right now I'm just overloading by using 2 methods, but it's verbosy.
public class CreateObjectRequest {
CustomObjectA a;
CustomObjectB b;
}
public class UpdateObjectRequest {
CustomObjectA a;
CustomObjectB b;
}
public void validateRequest(CreateObjectRequest createObjectRequest) {
//long body
//...
}
public void validateRequest(UpdateObjectRequest updateObjectRequest) {
//same long body...
//...
}
How can I reduce the verbosity of this code ?
CodePudding user response:
If those 2 classes share a lot of the same fields and are related to one another, then creating an Abstract parent class would be a solution:
public abstract class ObjectRequest {
CustomObject a;
CustomObject b;
}
then have your other classes extend that class via inheritance:
public class CreateObjectRequest extends ObjectRequest {
// any fields / method that are specific to this class
}
public class UpdateObjectRequest extends ObjectRequest {
// any fields / method that are specific to this class
}
And you can then define your validation method to take the abstract Superclass as an argument:
public void validateRequest(ObjectRequest objectRequest) {
//long body
//...
}
CodePudding user response:
Make one interface and make this objects implements it. Then you can put this interface as argument in your methods.