Click here to Skip to main content
15,889,281 members
Articles / Programming Languages / C#

Encapsulating code in business objects almost always means better code

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
18 Jan 2012CPOL1 min read 14.5K   3   2
Good examples of better coding are not always easy to find, but here is one.

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:

C#
1: buttonDelete_click()
2: {
3:     If myObject.HasChildren then
4:         ShowMessage("You can't delete an object with children.")
5:     End if
6: }
7:
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:

C#
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 small additional amount of time to do so.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Kraft Software LLC
United States United States
Rob Kraft is an independent software developer for Kraft Software LLC. He has been a software developer since the mid 80s and has a Master's Degree in Project Management. Rob lives near Kansas City, Missouri.

Comments and Discussions

 
Generallike !!!!! Pin
raananv27-Jan-12 12:21
raananv27-Jan-12 12:21 
Smile | :)
GeneralI could not agree more Pin
PopeDarren18-Jan-12 4:54
PopeDarren18-Jan-12 4:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.