Entity

3 min read

Our first building block has actually two key features:

A good and simple example for this kind of object would be a User. You know, a typical representation of a human in a computer system, containing name, email, login and password to protect against unauthorized usage. It will have some ID which will never change, and the rest of properties, which in fact can be changed anytime.

Immutable Identifier

Immutable in other words means unchangeable. Once ID was bind to the user’s object it must remain the same to the end of the world. Literally. If it ever changes there will be a catastrophy because other Entities refer to this particular object by its Identifier. Imagine what would happen with database holding billions of records split to hundreds of tables during such operation. Ouch.

Mutable Properties

So, in this imaginary system, you as a user need to change your email. Your previous provider decided to close his business and left you high and dry. And you have forgotten your password as well. What a bad luck. Fortunately, these both properties are mutable, and you can easily change them.

Comparing Entities

When Entity is equal to another one? When their identifiers match. You will likely create a special method which allows passing identifier of another Entity, and it will decide if objects are identical. We cannot rely on IDs given to the object by program runtime, because it may run on different machines located in separate datacenters.

Behaviours Instead of Setters

And last but not least - avoid defining setter methods in your Entities. It tells that a given property can be updated, but it doesn’t tell why it is allowed. Also, it may delegate some logic behind altering property’s value outside the scope. Example? Password can be changed by the User himself or by the system administrator, it also must contain at least ten characters. You will probably agree with me that it’s better to have validation encapsulated in User’s object than outside it and being called in many places. Of course there will be cases when setters are inevitable but remember to keep their quantity as low as possible.

Example

Look at the example User Entity below. It contains all properties and behaviours mentioned earlier.

Summary

As you can see, altering the ID is not an option. When it comes to Python it’s possible to do such thing of course, but underscored properties are “private” by convention, so it clearly states that re-assignment is not desired.