I have a spring boot rest application where i am getting player information as JSON in a POST request to persist into database. In total, we have 16 fields but in future more fields will be added.
{
"jerseyNumber": "1",
"firstName": "Sachin",
"lastName": "Tendulkar",
"age": "35",
"country": "India",
"playerType": "Batsmen",
"score": "101",
"ballsFaced": "110",
"strikeRate": "90",
"fours": "15",
"sixes": "1",
"oversBowled": "", '
"runsGiven": "",
"maidenOvers": "",
"wicketsTaken": "",
"economy": ""
}
if playerType = Batsmen, below 11 fields are mandatory, other fields specific to bowler can be null/empty.
{
"jerseyNumber": "1",
"firstName": "Sachin",
"lastName": "Tendulkar",
"age": "35",
"country": "India",
"playerType": "Batsmen",
"score": "101",
"ballsFaced": "110",
"strikeRate": "90",
"fours": "15",
"sixes": "1",
}
if playerType = Bowler, below 11 fields are mandatory.
{
"jerseyNumber": "10",
"firstName": "Zaheer",
"lastName": "Khan",
"age": "38",
"country": "India",
"playerType": "Bowler",
"oversBowled": "10", '
"runsGiven": "39",
"maidenOvers": "1",
"wicketsTaken": "3",
"economy": "3.9"
}
Pojo Class
public class CricketPlayer {
private String jerseyNumber;
private String firstName;
private String lastName;
private String age;
private String country;
private String playerType;
private String score;
private String ballsFaced;
private String strikeRate;
private String fours;
private String sixes;
private String oversBowled;
private String runsGiven;
private String maidenOvers;
private String wicketsTaken;
private String economy;
// Getter Methods
}
On receiving the request, i need to perform validation based on playerType value, if all the mandatory fields are given (not empty or null) in the json request. Going forward, the number of mandatory fields can increase to 25-30 fields. I can write the validation using if else statement based on player type value.
if(cricketPlayer.getPlayerType.equals("Batsmen")
{
// writelogic to check if all mandatory fields are not null or empty
} else if(cricketPlayer.getPlayerType.equals("Bowler")
{
}
But multiple if else block doesn't look good if we have more than 20-25 mandatory fields to validate. What is the optimized and best approach to follow in this scenario so that it is more readable and easy to add or remove any validations.
Aucun commentaire:
Enregistrer un commentaire