Home > Enterprise >  Are fromXYZ methods inside entities an antipattern?
Are fromXYZ methods inside entities an antipattern?

Time:11-19

I am developing a Symfony-Application but I guess my question is mostly independent of framework-usage.

This is the situation:

I got a very lightweight entity that is actually not even managed by the ORM as it is just used to aggregate and communicate information of another entity.

I read that we should keep business-logic out of the model but I also thought that it would proof quite useful to me if I had a fromXYZ-method in my lightweight-entity to create a SPOC for instanciation based off of the "big entity". But technically this from-method performs logic which contradicts what I read to be good practice.

So would this be an antipattern? How would I resolve this in a more suitable way, if yes?

CodePudding user response:

What are you talking about is static factory method. It's pretty ok to use it, but it shouldn't do anything fancy because it will be hard to test your code since you can't mock it.

If you feel that your method won't create any problems in testing, you can create it without any doubt. Otherwise, you can encapsulate your creation logic in a separate factory.

CodePudding user response:

Your "lightweight entity" could be referred to as a DTO.

One way to keep the terminology straight.

  1. Entities are managed by the ORM.
  2. DTOs are unmanaged. Often used to convey a subset or aggregation of entities.

Constructing one object from another by copying its fields is not something I would consider business logic, unless there are complex transformations prescribed by business requirements.

The real problem with fromXYZ methods is that they implement a dependency on XYZ. You have to be careful about which direction such dependencies are pointing. For example, if you construct a DTO by passing it an Entity, that DTO now has a dependency on the persistence layer of your application. If you then use that DTO in a service, your service layer now has a (transitive) dependency on your persistence layer. This is referred to as tight coupling.

One way to keep business logic decoupled from persistence, view, etc., is to point dependencies in the other direction: into the services rather than out of them.

  • Related