i'm facing a problem with a wrong designed java Object with 34 parameters.
This object can sometime has 3 filled values and the others must be null . In a second case 15 fields are filled, the others must be null etc...
I can't change this object now as it's linked to the repository model.
Is there a way to check if a list of field names are empty ? I was also thinking of creating a sub-object to create an isEmpty() method in order to split the size of the check.
For example this class "Guy" :
public class Guy {
private String name;
private String haveCar;
private String carBrand;
private String isRentedCar;
private String rentCarCompany;
public checkGuy(Guy guy){
if(guy.getHaveCar.equals("YES")){
// check if car brand exist
if ( guy.isRentedCar.equals("YES")){
// check if rent car company in db ...
}
}
}
// ...
}
When someone POST this object, i want to avoid this object to be saved :
"Guy": {
"name": "guy",
"haveCar": "NO",
"carBrand": "Renault", // nonsense
"isRentedCar":"NO",
"rentCarCompany":"RentACarCompany" // nonsense
}
This is a good question, because it happens a lot and a lot of people don't know how to deal with it.
Here's the question I think you're asking. We have a pre-existing class that we don't control.
And we want our API to use this class intelligently. There's lots of footguns and ways to use the class badly that this poorly-written class doesn't help us deal with.
The answer, then, is to deal with
TerribleClassas little as humanly possible. Your own code should deal with a wrapper class 99% of the time and only deal withTerribleClasswhen it absolutely has to.Now you mention getting this from the network via a POST request. If your code currently looks something like
Now you write this instead.
The only function that has to deal with that messy, unchecked
TerribleClassobject ismakePostRequest. Everybody who calls your function gets a nice friendly object whose invariants are checked.The way to protect yourself and your downstream users from bad code is to insulate yourself from it. Class badly designed? Write a wrapper and only expose that. Are there API functions that return the bad class? Make an adaptor class that returns your nice instances. Make it so the all of your business logic sees the nice objects and, at worst, you have a few wrappers that have to make messy decisions. But all of the mess is centralized in one place.