Search code examples
c++sqlgostatic-language

Separating vs merging objects made from database tables in static languages


Consider that in the database you have a table called users and a table called wallets. Among other things a user has 0, 1 or more wallets. The relation is one to many, meaning that the wallet has a foreign key pointing at the user.

Now the question is the following: When building a struct or a class for a person I see two possibilities:

1) The user has no sign of wallet. There is a function which takes a user as arguments and will fetch an array of the wallets.

2) The user has as a member which is an array containing the wallets and the wallets are fetched when the object / struct is created.

I think that the first approach may be better, since it's more modular - in the second one the users depend on the wallets, even if the user has no wallets. Still, I am not sure which approach is better so I am looking for a comparison of both approaches.


Solution

  • On the application level you might have a user type like this (Go notation):

    type User interface {
        Wallets() []Wallet
    }
    

    Far beneath, there's a database which in your case is SQL. That should not be obvious by looking at your application, thought.

    Making assumptions about dependencies beyond what they guarantee in the form of interface contracts couples the components irreversibly.

    That means that if you model your application by your database's schema you're doing it wrong because your entire application is now tightly coupled to said database and any change to any part of it will have a big, unpredictable impact.

    A common solution is to use a so called ORM layer, which sits between your database driver and entity models. It will take care of stuff like:

    • how and when should the wallets be fetched?
    • where in the database is a wallet's information stored?
    • when you remove a user, should the wallet also be deleted?

    among other things.

    PS: This answer applies to both, statically and dynamically typed languages.