Law of Demeter (or Principle of Least Knowledge)

Link to this posting

Postby Ursego » 19 Feb 2013, 22:23

A given object should assume as little as possible about the structure or properties of anything else (including its subcomponents) (Wikipedia).

In simpler words: if you want to get data from an object, referenced by a variable, then use a public function, declared in the referenced object itself, but not variables and functions of its nested object(s).

*** BAD code: ***

Code: Select all
age = outerObject.innerObject.getAge() // the current object inserts its "dirty hands" into internal mechanics of another object - outerObject

*** GOOD code: ***

Code: Select all
age = outerObject.getAge() // the code of outerObject.getAge(): "return innerObject.getAge();"

In both the cases we have the same result - the variable age is populated with a same value. But there is a huge difference if we are talking about possible dangers! In the GOOD code, only outerObject is responsible for its internal affairs. If the age's storage method in outerObject will be changed tomorrow (for example, it will be retrieved from DB rather than from innerObject), it will be enough only to change the code of outerObject.getAge() (with no change to the interface), and all the calls to that function all over the application will keep working without any change.

The rest of this post is for PowerBuilder developers only

The described issue doesn't exist if data is properly encapsulated, but PowerBuilder has serious problems in this area: while instance variables can be declared as private or protected, on-window objects (including DataWindows whith their data) are always public. So it's enough to have a pointer to a window to access its DWs:

*** BAD code: ***

Code: Select all
li_age = w_aaa.tab_bbb.tabpage_ccc.dw_ddd.object.age[1]

It's possible technically, but let's avoid that! In the given example, there should be created a public function in the window, and the outer world should deal only with that function:

*** GOOD code: ***

Code: Select all
li_age = w_XXX.uf_get_age()
User avatar
Site Admin
Posts: 140
Joined: 19 Feb 2013, 20:33

IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:

Traffic Counter

free counters

eXTReMe Tracker