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()

*** GOOD code: ***

Code: Select all
age = outerObject.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 BAD code, the calling method (where the BAD code is) inserts its "dirty hands" into internal mechanics of another object - outerObject. In the GOOD code, only the referenced object itself is responsible for its internal affairs. If the age's storing method in outerObject has been changed (for example, now it will be stored not in innerObject), it's enough to change only implementation of outerObject.getAge() (with no change to the interface), and all the calls to that function all over the application will keep working.

The rest of this posting 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: 113
Joined: 19 Feb 2013, 20:33

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

free counters

eXTReMe Tracker