34

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,

1
  • actually the team-leader was talking about not to put logic in the getter part! so he refactor my property "extract method" during the task review. May 27, 2010 at 17:20

8 Answers 8

41

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.

4
  • 2
    By consistent do you mean idempotent? May 27, 2010 at 16:57
  • 13
    Exceptions are okay on setters, if someone is trying to set an illegal value.
    – Thorarin
    May 27, 2010 at 17:00
  • Idempotent would apply I think. I would agree with exceptions on setters, but I think you should definitely not throw an exception on a getter. May 27, 2010 at 17:03
  • Of course, there is an exception to consistency too. Things like DateTime.Now and Stopwatch.Elapsed. May 27, 2010 at 17:04
33

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.

3
  • I agree with the answer, but what about data-driven situations where a Product has a Supplier and a Supplier has a collection of Products. Should you load those related entities during object construction? First property access? Or should they not be accessed through properties because of the pitfalls either option presents? May 27, 2010 at 17:01
  • @Anthony -- I don't think loading the properties on the object is the responsibility of the object itself, but rather the responsibility of your data access layer or ORM.
    – tvanfosson
    May 27, 2010 at 17:03
  • @Anthony: That's why I put "usually" :) Things like Linq to Sql may indeed do this sort of thing - but I'd expect developers to be aware that they're dealing with ORM-bound objects. It's not the sort of thing I'd want to see all over the place though.
    – Jon Skeet
    May 27, 2010 at 17:37
7

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.

3
  • 1
    What kind of logic is valid in a getter/setter? May 27, 2010 at 16:55
  • 1
    @Robert - it's hard to give a comprehensive definition, but it should pass the smell test. For example, it's reasonable to expect that changing the price or quantity of an order would change it's cost. You wouldn't expect it to change the supplier from which it's delivered.
    – tvanfosson
    May 27, 2010 at 17:00
  • Agree in principle, although I have written classes that read from text files, where setting a particular property rewound the file to the beginning (because setting that particular property put the file reader in an invalid state otherwise). May 27, 2010 at 17:04
3

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.

1
  • Agreed, you summed up what I was thinking. :) In a small pet project I have, I included some logic in a "Player" class' property to set a player's team in-game. It first checks to make sure the player's current team and the new team value isn't the same and then sends a console command to change the player's team to the value.
    – Zack
    May 27, 2010 at 17:03
2

Placing business logic in a setter can get you in trouble if you ever have the need to serialize/deserialize your objects with JSon, XML or an ORM. An example of this may be when using a NoSql datastore like a document database or an ORM. Some of these (e.g. NHibernate) can be configured to access backing fields instead of the setter.

I find that using a public Getter and Private setter along with a method to set the value with additional logic as required is a good approach. Most serializers can access the private setter so what you end up with is an accurate representation of the persisted object without accidentally firing logic that could potentially change values incorrectly when deserialized.

However, if you don't think there will ever be a need to serialize/deserialize then this shouldnt be an issue.

0

In my opinion this is absolutely ok. The way I see it, the only justification for having properties as a language feature in the first place is that you can have logic in them. Otherwise you may as well just allow direct access to the underlying data members.

1
  • 1
    Kinda always thought the same: access modifiers is one more reason, and explicit declaration to embed logic in it... Obviusly keeping in mind the context of the class ... Dec 20, 2016 at 9:55
-1

Usually, a property only affect 1 variable since it was made mainly for that purpose. But sometime, you want a more high level property that isn't just a 1-to-1 variable. So, in this case, it's normal that it will contains code. But you have to keep in mind that a property is not intended to be used like a function. When you call a function, you know that it will do some processing. When you call a property, you expect it to be fast.

But finally, it's a question of preferences, and like coding standard, following what your superior is telling you is at your discretion. So it's not bad and depends on your judgment.

-1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.