Tariq
Tariq

Reputation: 51

Should an object ever have a property thats result is based on business logic?

Or should they always be a function when business logic is invloved ?

Example: Order.RequiresPayment

property or function ? There are business rules as for when it is true or not

IS there a pattern that may determine this?

Upvotes: 2

Views: 199

Answers (6)

cbp
cbp

Reputation: 25638

A pet-hate of mine is when access to a property causes the state of an object to change. Properties should reveal something about the existing state of an object, whereas functions can be used to cause something about the object to change.

Causing an object's state to change when accessing properties makes debugging very difficult - a developer usually expects a function to cause something to happen and when using the debugger won't let a function run, unless they are ready for the results. On the other hand, most debuggers will automatically access the public properties on an object, not expecting the object's state to change merely by accessing the properties.

Upvotes: 1

Brody
Brody

Reputation: 2074

Generally, a property should not require complex calculations.

A property promises to be really fast while a function (or method) does not. So a value that is calculated or could take some time to retrieve should be a method and a value that is instantly ready can be a property.

Upvotes: 1

David Robbins
David Robbins

Reputation: 10046

I agree with Adam. Usually a property will contain a value such Count, Length, etc.

Upvotes: 0

dkretz
dkretz

Reputation: 37655

You can usually decide by whether it makes more sense to think of it as a Business Property or a Business Function. The level of abstraction doesn't change the way you think about things.

Upvotes: 0

S.Lott
S.Lott

Reputation: 391952

This is a language-specific question.

In Python, for example, business rules can (and often are) both.

Principally, they're method functions.

However, Python allows them to appear as properties if that's easier on the eyes when reading the code.

Note that

  1. Business rules are -- generally -- method functions. Sometimes they're relationships among objects. Method functions are easy to expand and modify. Starting with a property is a mistake when you need to add features and change a property to a method function.

  2. Properties are best used as syntactic sugar to make a method function look like a property because it makes code simpler or easier to read.

Upvotes: 1

Adam Liss
Adam Liss

Reputation: 48310

When in doubt, consider maintenance of your code as a guideline.

If OrderRequiresPayment is determined very simply (for example, set true on order creation, false when payment is received), a property is fine.

If it's determined by a formula, or if it's updated in many places, it's probably best to encapsulate it in a function.

Upvotes: 4

Related Questions