Law Of Demeter Speaks Only With Friends
The law of Demeter, is one of those essential practices that must know and apply any software developer (at least so I think). It is a rule that guides us to reduce the coupling of components/classes/modules of our systems by avoiding an object known to B, a B object known to C and to not know C then to not should be able to manipulate or send me messages to C via B, doing so violates the law of Demeter, in words more simple, means that a method of a class m or only should be able to send you messages to these types of objects: – or – objects parameter that receives the method m from the object itself – any object that instancie m – of any attribute or prevents (.b) type call () .c () .d () which clearly indicate a problem with our code. Looking as exemplify found the example of the chico-diariero (paperBoy, seems to be a classic example of this law). For more information see Ali Partovi. The example is based on the relationship between the Argentine and the client of the journal at the time that you want to collect only a delivered journal. Let’s look at a example that violates the law of Demeter: (clarified that these codes did them on-the-fly, are not tested and may generate errors, are only for example) class Argentine static protected $costoDiario = 5; public function cobrarDiario(Cliente $cliente) return $client-> getBilletera()-> extraer(static::$c ostoDiario); class client protected $wallet; public function __construct() $this-> wallet = new wallet (100); public function getBilletera() return $this-> wallet; Obviously the Argentine class ends by manipulating the wallet class without any need. A correct example would be: class Argentine static protected $costoDiario = 5; public function cobrarDiario(Cliente $cliente) return $-> cobrar(static::$costoDiario) customer; class client protected $wallet; public function __construct($billetera) $this-> wallet = new wallet (100); public function collect ($amount) return $-> billetera()-> extraer($monto) this; In this example we see that the method charge daily sends a message to an object passed by parameter and the method charge invokes an object of a class attribute, both comply with the law of Demeter. Disadvantages – it sometimes requires writing many small methods of sheath (called sometimes Demeter Transmogrifiers) to propagate method calls to the components. Martin Fowler says that it would be more correct to call this rule the suggestion of Demeter, which is not absolute. For more information you can visit: – the website of the law of Demeter – law of Demeter – Introducing Demeter and its Laws – POO examples of the law of Demeter – the law of Demeter: definition and examples – law of Demeter, or good style: elegance in POO source: mostofreddy original author and source of the article.