Reputation: 1023
I am writing a java program to validate keys and values in a property map, which could treat as a JSON object. Right now I am using deeply nested if-else to validate that but it's crazy error-prone. Not sure if this could be easily solved in any design pattern.
Take player property map for example:
'player' = {'name': 'player1',
'age': 18,
'race': 'human',
'skills': 'pick pocket',
'misc': { 'hoppy': 'sleep', 'exp': 238459 }
};
I want to validate few things
Some key-value pairs are mandatory: like name
is mandatory in player
property map, misc
is not.
Some values need to be specific type, like value of age
need
to be an integer.
Some values are enum, like race
could be human
, elf
, drawf
but nothing else.
Some keys depend on other keys, if A
key is specified, then B
key also need to be specified. Like if country
depends on 'race': 'human'
, so {'race': 'human', 'country': 'midearth'}
is valid. {'race': 'human', 'enemy': 'ghost'}
, {'race': 'human'}
are not.
Values could be maps as well, values in that map don't need to be same type.
This property map will be extended in the future. What design would make it more extendable?
Upvotes: 0
Views: 1151
Reputation: 7765
Start with the Java class. You can reduce much of your effort by using JSR-303 validation annotaions.
Example :-
class Player{
@NotNull
@Size(min=5,max=200)
private String name;
@Min(value=10)
@Max(value=60)
private int age;
.
.
. // other fields
}
Find available validation annotations here and tutorial here.
Applying the validation on Java bean instead of JSON string/object will be better approach in my opinion.
Converting the bean from and to JSON string is easier using Google's GSON API
Upvotes: 1