Skip Navigation

How do you structure your models save/load code?

I have in mind two options:

  • Code in the class being saved/loaded. The flows for each entity/model are in the same place, so it's easy to just have one file open to see all the functionalities of that class, but this means having more code in a single file.
  • Code in a dedicated class (like a factory)
    This makes each file smaller, but spreads flows of a single model into different parts of the repo, also because I'm thinking of having a directory /src/models and another like /src/export (or serialize)

What do you guys think?
What's your preferred way to organize the save and load flows?

12 comments
  • Models should contain or inherit their own serializers/deserializers.

    Either put the generic serialization in a base Model class, or make the base Model class defer implementation to a reusable Serialization helper class, preferably an off the shelf library.

  • mainly java dev here:

    if i only have few classes i want to serialize/deserilize i implement the logic for that in the class, if they need special logic for that, and implement the serilizable interface. writing objects to somewhere or reading them from somewhere belongs in a different class.

    if i have a lot of classes or use a framework like spring i'll employ whatever they offer for serilization and deserilization or more likely a databinding library like jackson.

    other languages with classes or structs offer simmiliar options(pythons pickling and unpickling or the json package in their standardlib for example) so my approach would stay mostly the same.

  • In python I put my base models in models/__init__.py. The bases have things for managing data behind the scenes, adding common utility methods, etc. If I’m using another library or method to serialize data I’d put it in a separate utility script somewhere, it’s probably going to be useful to more than just data models and it’s easy enough to import.

    Then each file that defines models has a from models import BaseModel or whatever else is needed, keeping each file relatively short and focused to what it needs to do.

12 comments