Reputation: 23
I'm building a small application to learn Java that has different types of user. At first, I thought that It was a hierarchy, where user is the superclass and the other three (customer, admin and worker) subclasses. Also, this three user types have different methods and GUIs, but they all have user and password.
My problem is that I have a class called Application and the method login that returns an user object and I don't know how to see if this object is an admin, worker or customer without using instanceof. Also, all the methods are in each subclass because they don't have functionality in common, except the login (that is in another class), then if I have an object of type user I would need to cast it to another subclass, but, again, I don't want to use instanceof. Another idea that I had is to make all the methods in user class and an role enum that I would check to see If the user has permission. But, If I need to do an enum for this, I don't see the point in having subclasses.
Is there any solution to this?
Note: It's a small app, without databases or online connection, only a college project.
Upvotes: 2
Views: 636
Reputation: 2588
From all my experience, it's quite a bad idea to have multiple classes for the User:
Another point which has proven to make implementation harder: one enum reference for the current role. Although this is quite a good solution, think about special permissions and a mixture of roles (Set<MyRoleEnum>
or Set<MyRoleClass>
).
This (user has a list/set of enum roles), so far, has proven the best, fail-safe (compile-time safe) model I have implemented up to date, for smaller projects.
User.Set<MyRoleEnum>
is that you have to recompile+redeploy the whole code for an additional role. But additional roles usually always come with new features, so the code would have to be re-compiled/deployed anyway...If your project is meant to be used by thousands of users and an army of admins, go for the User.Set<MyRoleClass>
implementation.
MyRoleClass
Upvotes: 2