Is it a good practice to implement logic in properties

前端 未结 8 669
傲寒
傲寒 2021-02-05 02:39

we use ASP.NET with C# and based on open source projects/articles I passed through, I found many properties were including a logic but when I did so the team-le

相关标签:
8条回答
  • 2021-02-05 03:20

    A common answer applies here: It Depends.

    Generally, it is not a good idea to implement business logic in getters and setters. If your object is a simple DTO (data transfer object) this would violate Single Responsibility.

    However, state-tracking logic and other housekeeping is often found in properties. For example, Entity Framework 4 self-tracking entities have state management logic in every primitive property setter to allow for tracking.

    An alternative to logic in properties is Aspect-Oriented Programming (AOP.) Using AOP, you can "inject" logic between objects and the hosting process. Access to objects can be "intercepted" and handled conditionally.

    0 讨论(0)
  • 2021-02-05 03:24

    In my opinion business logic is allowed in Setter/Getter only in certain situations. For exaple: it's alowed to put logic that's responsible for validating the input, becase setters are responsible for maintainging object state, so that state should not be violated. So you should cut that business logic to smallest portion of code that is responsible only for one subject.

    The other thing is that your class should be (in best situation) POCO. Why? Because it should be reusable and when class contains logic in Properties reusability can be simply blocked. Think that you have SqlServerPerson with some SQLServer validation in properties then it can be hard to replace it with for example NHibernatePerson when you change the ORM/DB access.

    0 讨论(0)
提交回复
热议问题