Free Essay

Fluent Programming vs Law of Demeter

In:

Submitted By b947254
Words 1444
Pages 6
Fluent or Law of Demeter?
Serban Gavrus

Abstract
The Law of Demeter is one of the most widely known programming principle, it‟s easy to respect and it assures some important code quality aspect. It can be briefly defined as “use only one dot”. Fluency is a popular choice for implementing interfaces because it adds readability and ease of use. Method chaining and fluency are in practice inseparable. These two aspects of programming seem to be contradictory, one can‟t have both. This essay argues that fluency and LoD can coexist and in the case where the developer must sacrifice one for the other, there is no clear rule to follow.

1.1 Law of Demeter The Law of Demeter was proposed by Ian Holland in 1987. It‟s a programming rule that applies to how methods are written, whose purpose is to assure a good programming style. It‟s been created as a metric to asses the quality of an object-orientated program. The direct purpose of the law is to condense several OOP principles(coupling control, information hiding, information restriction, information localization, structural induction) into a simple and easy to follow rule. The indirect purpose is to ensure loose coupling and stricter modularity. [1]

The Law of Demeter is intended to be a guideline, not an absolute restriction. Misunderstanding and blindly following this law can lead to poorer code. [1] The law states that an object “A” should not access an object “B”, retrieved by calling a method of another object “C”, of which “A” has a direct reference to. Instead, “C” should offer an interface that covers the needs of object “A” so it doesn‟t need to access “B”. The law can be greatly simplified by the following rule, “use only one dot”.

1.2 Fluency Fluency, introduced by Eric Evans and Martin Fowler, is a type of interface that allows for more readable code [2]. By using method chaining, fluent APIs provide a better context of the method called for the reader of the code. A better description of fluency can be made via examples. Here we have an example of fluency using Jquery, the popular JavaScript library. $(„#hidden-div‟).show().width(200).height(300).addClass(„box‟); As suggested by the ID of the element(„hidden-div‟), we have a hidden div which we make visible(show), then set it‟s width and height to 200 pixels respectively 300 pixels and lastly we add the class „box‟ to it. This line of code is easy to read and interpret and shows the power of this type of programming. Writing a fluent API is a difficult task and requires some uncommon practices such as writing setters that return a value. Doing this is against the command-query separation programming principle which states that a method should either perform and action or return a value to the caller. The proponents of fluency however suggest “suspending” this principle for the cause of readability. Fluency also causes the existence of methods that make little sense on their own, the user of the API must understand that these methods were written with fluency in mind as they only make sense in that context. [2] Although method chaining is an integral part of this type of interfaces, simply writing an API that allows method chaining does not make it fluent. A fluent API‟s main concern should be code readability. In fact, method chaining is regarded as “train-wreck programming” and is often sign that the code is inflexible to change. In the context of Fluency however, method chaining does no make extensive use of variables.[4] Another important aspect about fluency and method chaining is that the latter is just a means of making the interface more practical, fluency can be achieved without method chaining. “Fluency isn't as much about the style of syntax you use as it is about the way you name and factor the methods themselves”. [4]

2. Fluency and the Law of Demeter

2.1 Can fluent interfaces respect the LoD? If taking into consideration the simplified version of the Law of Demeter, “use only one dot” it suggests that fluent interfaces and the Law of Demeter are two antagonizing principles, one cannot build a fluent API without the Law of Demeter being broken. However, looking at the issue in more detail reveals that this is not the case. According to a slightly more elaborate definition of LoD, an object can call it‟s own methods, methods of the arguments it receives and methods of it‟s own properties. [3] Creating a fluent API that respects these conditions is not difficult. Let‟s take the previous example used in section 1.2. $(„#hidden-div‟).show().width(200).height(300).addClass(„box‟); The first method returns an object, “show” is called on that object, performs it‟s actions and returns it again, “width” does the same and so on. Although we used more than one dot, LoD was not broken because all the methods called were the object‟s own methods, which is in accordance with the law. [3] Writing methods that return their host object(this) is a common technique used when developing fluent APIs or DSLs, but this is not a rule. [2] doesn‟t present any guidelines in regards to software qualities(coupling, cohesion, information hiding, etc.) in developing fluent interfaces, the developer‟s only goal is to make a language that is easily readable and that is more similar to natural language.

2.2 Example of Law of Demeter and fluency [5] presents an accessible example of the basic benefits of LoD, it shows the scenario where a paperboy after delivering the paper, takes the customer‟s wallet and takes out the money. Wallet theWallet = myCustomer.getWallet(); if (theWallet.getTotalMoney() > payment) { theWallet.subtractMoney(payment); } else { // come back later and get my money } Obviously this is wrong, the paperboy should receive the money from the customer directly, and not have access to their wallet. Because the paperboy gets the wallet object from the customer and calls it‟s methods to get payment, this violated the Law of Demeter. To fix this, as mentioned earlier, the customer should pay himself. So now, the paperboy receives payment as follows: payment = myCustomer.getPayment(payment);

This is of course in accordance with LoD as the paperboy does not access the wallet object, but the customer offers the payment service in his interface. What if we wanted to make the customer interface fluent, would this have any effect on LoD? No. In the following example, receivePaper() and receiveBill() are customer methods that return the customer object slightly altered. The LoD is respected.

payment = myCustomer.receivePaper(myPaper) .receiveBill(myBill) .getPayment(); 2.3 Should fluent interfaces respect the Law of Demeter? In the previous sections it was shown that LoD can be respected in the context of fluent interfaces, however some interfaces‟ fluency may be hindered by respecting the LoD. Is it a good idea to do this? In [1], the original paper where LoD was defined, and in [3], a followup if the original paper, the authors stress the fact that this law should not be enforced, but it‟s merely a guideline for assuring good quality code, albeit, it‟s an important guideline. So not following this law is not necessarily bad, the developer can freely chose what they consider to be best practice. Somewhat analogous to the previous paragraph, the proponent of fluency, says in [4] that it‟s important for DSL developers not to focus too much on making the programmming language they‟re creating very similar to natural language, as that leads to “syntactic sugar” and other unwanted complications. Perhaps this can be interpreted as, it is a bad idea to sacrifice code quality for superficial readability.

3. Conclusion The Law of Demeter and fluency can coexist peacefully in the same program, as shown in section 2.1, but this is not always the case. When the situation forces the developer to chose between one or the other it seems both sides([1], [3] respectively [2], [4]) suggest that there is no clear action to be taken. It‟s the developer‟s responsibility to asses the consequences of each option and make a decision based on their analysis.

[1] Karl J. Lieberherr, Ian M. Holland, Assuring Good Style for Object-Oriented Programs, 1989. [2] M. Fowler, FluentInterface, 2005 [3] Karl J. Lieberherr, Ian M. Holland, Formulations and Benefits of the Law of Demeter, 1992 [4] M. Fowler, Domain Specific Languages, p 42, 68, 69. 70, 2010

[5] Bock, D. The paperboy, the wallet, and The Law of Demeter, 2000

Similar Documents

Free Essay

Test2

...62118 0/nm 1/n1 2/nm 3/nm 4/nm 5/nm 6/nm 7/nm 8/nm 9/nm 1990s 0th/pt 1st/p 1th/tc 2nd/p 2th/tc 3rd/p 3th/tc 4th/pt 5th/pt 6th/pt 7th/pt 8th/pt 9th/pt 0s/pt a A AA AAA Aachen/M aardvark/SM Aaren/M Aarhus/M Aarika/M Aaron/M AB aback abacus/SM abaft Abagael/M Abagail/M abalone/SM abandoner/M abandon/LGDRS abandonment/SM abase/LGDSR abasement/S abaser/M abashed/UY abashment/MS abash/SDLG abate/DSRLG abated/U abatement/MS abater/M abattoir/SM Abba/M Abbe/M abbé/S abbess/SM Abbey/M abbey/MS Abbie/M Abbi/M Abbot/M abbot/MS Abbott/M abbr abbrev abbreviated/UA abbreviates/A abbreviate/XDSNG abbreviating/A abbreviation/M Abbye/M Abby/M ABC/M Abdel/M abdicate/NGDSX abdication/M abdomen/SM abdominal/YS abduct/DGS abduction/SM abductor/SM Abdul/M ab/DY abeam Abelard/M Abel/M Abelson/M Abe/M Aberdeen/M Abernathy/M aberrant/YS aberrational aberration/SM abet/S abetted abetting abettor/SM Abeu/M abeyance/MS abeyant Abey/M abhorred abhorrence/MS abhorrent/Y abhorrer/M abhorring abhor/S abidance/MS abide/JGSR abider/M abiding/Y Abidjan/M Abie/M Abigael/M Abigail/M Abigale/M Abilene/M ability/IMES abjection/MS abjectness/SM abject/SGPDY abjuration/SM abjuratory abjurer/M abjure/ZGSRD ablate/VGNSDX ablation/M ablative/SY ablaze abler/E ables/E ablest able/U abloom ablution/MS Ab/M ABM/S abnegate/NGSDX abnegation/M Abner/M abnormality/SM abnormal/SY aboard ...

Words: 113589 - Pages: 455