what are entity objects?

Entity... it's a word that it's often related with Domain Driven Design, but I won't write specifically about DDD. What I want to write, can be used without DDD approach. I think DDD is somewhat conceptual heavy and it's often useful to use terms popularized by DDD but without all this weight.

So. What's entity? Let's assume it's a JavaScript class (actually it doesn't have to be a class, it's more conceptual term, but now I assume some specific implementation of this).

So... each JavaScript class?

No. It's more like something that has specific identity. e.g. User, Product. Usually you have many things of some type (e.g. many users), but this concrete user (represents in database by specific row, but in app you would create instance of User class for example).

On the other hand if you have something that is more of a utility class - e.g. imagine that you have Theme class with colors, backgrounds - this thing is probably not entity (though it can be. It can be blury sometimes).

Something singletonish (some global object you use across the aplication) also would not be entity.

Overally entity is something that has some identity. But also I think entity is domain object. Ideally you won't have any code in it which is to specific of concrete implementation. You usually don't want to mess your rendering/GUI code withing entities or fetching data from inside entity.

How would do it anyway?

You can treat entity objects like some data-container and get data from it and pass to GUI. Or other way around. Fetch data from internet and put into entity object. So entity object in this scenario is somewhat open.


class User {}

const user = new User();
const data = await fetchData(url);
user.data = data;

But you can also do this in other way. Hollywood principle. Inversion of control. Maybe entity should be smart enough to realize that it needs data, but won't fetch itself, instead it will invoke callback.


class User {
   async login() {
      this.data = await this.onLogin();
   }
}

const user = new User();
user.onLogin = () => await fetchData(url);
user.login();

This way entity code is not dealing with specification details, but rather rely on abstraction.

Comments

Popular posts from this blog

First steps with Plotly.js

How to be a modern front-end dev?