Rob Kraft's Software Development Blog

Software Development Insights

Encapsulating code in business objects almost always means better code

Posted by robkraft on December 3, 2011

Good examples of better coding are not always easy to find, but here is one.  A good coding principal is to encapsulate business logic in business objects instead of including business logic in the user interface.  This is the foundation of coding using object oriented principles.  One specific example is to compare these two ways to write the same code:

 1: buttonDelete_click()
 2: {
 3:     If myObject.HasChildren then
 4:         ShowMessage("You can't delete an object with children.")
 5:     End if
 6: }
 8: buttonDelete_click()
 9: {
 10:     If myObject.AllowDelete = False then
 11:         ShowMessage(myObject.ReasonDeleteNotAllowedMessage)
 12:     End if
 13: }

The first code sample may be the first to come to mind, but the first solution that comes to mind is often not the best.  The second code sample is superior because it places the logic for AllowDelete inside the business object, and thus it makes that logic re-usable in other places.  Perhaps you have an import utility that could use the same logic, or perhaps you want to write unit tests.  In the second example, you can write unit tests to make sure that the AllowDelete property is being set correctly; but the first example would require UI testing to confirm this.

In my example, the code inside of the .AllowDelete property probably looks like this:

 1: Public bool AllowDelete()
 2: {
 3:     If (this.HasChildren == true)
 4:         Return false;
 5:     End if
 6: }

By placing this logic in the business object, it would be easy to expand it later and the additional logic would apply to all user interface and batch processing code that uses it.

Any time you can encapsulate some logic within an object, it is probably worth the smalladditional amount of time to do so.

One Response to “Encapsulating code in business objects almost always means better code”

  1. I will right away snatch your rss as I can not in finding your e-mail subscription link or e-newsletter service. Do you have any? Please allow me know in order that I could subscribe. Thanks.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: