Is it a good practice to implement logic in properties

前端 未结 8 670
傲寒
傲寒 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题