Is it a good practice to implement logic in proper

2020-05-29 22:17发布

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-leader told me it's not good at all to place logic inside properties but to call the logic through methods...

is that really bad? and why not to use logic in the properties?

thanks,

标签: c# asp.net
8条回答
该账号已被封号
2楼-- · 2020-05-29 22:40

Property access is expected to be instantaneous (no long waits), consistent (no changing values), and safe (no exceptions). If you can make those guarantees, I think putting logic in properties is OK.

查看更多
Summer. ? 凉城
3楼-- · 2020-05-29 22:48

Properties are methods. They are just short-cuts for getter/setters. Any logic that would be valid in a getter/setter is reasonable to put in a property. Any logic that you would normally not put in a getter/setter would be inappropriate to put in a property. Generally speaking, if you (as a consumer of the class) couldn't reaonsably expect that setting a property value, or even worse, getting a property value might cause a behavior to take place, then that logic probably belongs elsewhere. In other words, the logic should be related and consistent with getting or setting the property.

Quoting from the linked article above:

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.

查看更多
登录 后发表回答