I am trying to make a library that accesses an online RESTful API. The API has defined a list of implemented methods, and allowed parameters for each method and (in some cases) allowed values for given parameters. I was thinking I would like to ensure that (A) only implemented methods can be called; (B) only allowed parameters can be defined for a given method; and (C) where only certain values are allowed for a given parameter, only allow those values.
(A) is relatively easy just using an enum “Method”:
public enum Method {
getObjectById,
getObjectBySearch,
...
}
for (B) I was thinking each instance of Method then needs to have it’s own enum of allowed parameters and for (C) some parameters, an enum of allowed values, sort of like (I’m sorry if this makes anybody cringe):
NOTE: THE FOLLOWING CODE IS NOT VALID JAVA; IT IS ONLY HERE AS A CONCEPTUAL EXAMPLE.
public enum Method {
getObjectById () {
enum Parameter {
objectId;
},
getObjectBySearch () {
enum Parameter {
query,
queryType () {
enum Type { type1, type2 }
}
}
}
}
Obviously, local enumerations are not allowed in Java, so this can’t be done; and I imagine there are more elegant ways to achieve my end goal, but I’ve been out of practice for over 5 years, so I’m struggling to find them.
Or perhaps I’m overthinking this and trying to achieve this kind of type safety in parameters and values of my request is really bad practice (again I’m not very experienced) – if this is the case, I would appreciate an explanation as to why it is bad practice.
Thanks,
– Igor
Why don’t you just wrap every method call inside a service object which validates its arguments?