Let’s say I have classes Project, Employee, and ProjectAssignement. I have an enum Role, with two values, LEADER and FOLLOWER. Employees are assigned to Projects via the ProjectAssignment object, which has a member field role of type Role.
I have a business rule that each project can only have one leader but can have many followers. To implement this, I give Role a member field singular, which is true for LEADER and false for FOLLOWER. (I might add more roles in the future.) My server-side Java checks if you try to assign multiple leaders to a project and doesn’t let you.
So far, I don’t think I’m describing anything particularly unusual.
Here is the awkward bit: I have some (handwritten) client-side JavaScript validation to make sure you don’t assign multiple people with the same role to a project. It has a hardcoded exception for followers. Is there any clean way to just give the JavaScript code awareness of the Role enum, so it can access the isSingular method?
(Obviously, anything of the sort would actually have to transcribe the Role enum into JavaScript at some point; I want to avoid doing that manually or even semi-automatically, because that rapidly becomes more effort than it’s worth as I do it for more situations.)
I am not using Spring or any similar framework, just plain .jsps. Rewriting the whole application to use something like that might be a good idea, but is well beyond the scope of the problem.
I usually solve this kind of thing by adding a lookup-table in some dynamically-generated Javascript on the page. Maybe the id of the user is the key and their “singularness” is the value. Or maybe you only list those who are less popular (there are likely fewer LEADERs, so only list those). Then just consult the LUT in the javascript.
Actually accessing the ENUMs is not possible. Instead, you’ll have to bridge the gap yourself, even if it means basically building a Javascript object that fully-models your server-side object description and then copy all the data.