Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use same java method for different parameters types?

My problem:

I have 2 defined classes

  • CreateObjectRequest
  • UpdateObjectRequest

that must be verified by an utility method.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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
    //...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading