All Articles

An inconclusive explanation about ORMs, Active Record and Service Layers

Photo by Roman Kraft on Unsplash unsplash-logoRoman Kraft

After some time I learnt a valuable skill: never be totally sure about you side on huge discussions. Certainty is expensive, and if you do have it, probably you fail to to see about other important point; after all, why people are disagreeing with you in the first place?

That’s why I’m have some mixed feelings about approaches suitable for the most common pattern on any application: Object-relational Mapping, fondly called ORM. First I’m going to put some concepts on the table, then expose each approach, with the common usages and pitfalls. Of course, there’ll be some links to people more opinionated against or in favour of each one. Then you, smart and rational reader, can decide for yourself which one is more adequate to the context you’re picturing about.

The most important layer of any application

Well, in the end of the day, applications basically get stuff from users and put in databases. Then they’re retrieved and displayed when asked (nicely, manners are important). We develop stuff that fetch and put information in databases, with all care and diligence needed. It is not a surprise that handling data is at the very core of any system. We usually call it ORMs since these components serve as a proxy between the data and the program. From your (developer) side, all you see are objects, standard OO code. But at the end we are talking about tables and other data structures. They are notably less friendly, but that’s not what they were designed for: they ought to be fast and reliable. So ORMs help you keep talking with familiar faces (objects) and handle the communication with the real data (database systems, such PostgreSQL).

Common Approaches

How this layer will behave? Well, there are two most common patterns. The Active Record pattern assume you will have a Class representing basically each table. Each object will be a record from that table. The object expose all the methods you need to fetch, create, update and query the related data. More on that later.

Using service layers, called storages as well, you will also have classes and objects representing (or mapping?) tables and records. The main difference they will be plain, trivial representations of those. They will be dumb and straightforward models, whereas specific services are responsible for handling the data manipulation. You ask what you want for the storage, it will give you the response in the form of one or more models. Again, more on that later.

Active Record - Each object knows his stuff

Service Layer - Let me handle that query for you

What are the real differences here?

They diverge not on how to represent the data, but how to handle it. A object from the Car class should know how to

Common pitfalls

How people usually decide?

Conclusion