Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to implement logic in properties

Tags:

c#

asp.net

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,

like image 501
Jawad Al Shaikh Avatar asked May 27 '10 16:05

Jawad Al Shaikh


2 Answers

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.

like image 72
Instance Hunter Avatar answered Oct 08 '22 14:10

Instance Hunter


It's fine to have some logic in properties. For example, argument validation in setters and lazy computation in getters are both fairly common.

It's usually a bad idea for a property access to do something expensive such as a database call, however. Developers tend to assume that properties are reasonably cheap to evaluate.

It's a judgement call in the end - but I certainly reject the suggestion that properties should only ever be trivial to the extent that they could be implemented with automatic properties.

like image 25
Jon Skeet Avatar answered Oct 08 '22 14:10

Jon Skeet