I am having such a hard time with OOP and databases. Both in C++ with SQL and even more so with Node.js and MongoDB. For this question I will use Node/Mongo.
Let's say we have a user object. Over time user objects can get pretty big..
class User {
constructor(){
this.name = '';
this.id = '';
this.country = '';
this.email = '';
this.password = '';
this.level = 1;
// ... and on
}
isAdmin(){
return this.level === 0;
}
}
In my app the User
object can be constructed to check for authorization among other things. But 90% of its purpose is to just hold data. So when a user is entered into the database, all properties in the class are entered as well. That is where the simplicity ends. Once I need to retrieve a user, I end up with a plain old object that looks exactly like a User
object but without any functions. So what do I do? I can
- Pass the user object retrieved into a
User
constructor that has all 30ish parameters via and object - Call 30 setters such as
User.setName(doc.name)
- Write some intermediary function in the main app like
App.setUserFromDatabase(user, doc)
- Just use the object directly, ie
validatePassword(password, doc.password)
Converting my plain MongoDB object to a User
class object is such a waste of time, yet I feel so dirty about using the MongoDB object directly since it has no definition like the class object. But using the class object seems so pointless just to call one or two functions.
So I am just stuck here trying to understand the right way to user database objects and actual application objects when they are basically the same, but only one (the application object) has a very clearly defined structure.
user
object that includes all this stuff directly isn't really a good object model.)User
class to check for 'authorization among other things' - this sounds to me like User is going to end up being a God object, which is really the antithesis of OO. A more 'OO' approach would involve clean separation of persisted data away from behaviour, then define classes based on their behaviour and not the data they work with - For example, an 'Authenticator' for user identity.