Skip to content

Commit b885f37

Browse files
committed
Add hint about Law Of Demeter
1 parent e746ceb commit b885f37

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
---
2+
layout: post
3+
title: "Law Of Demeter"
4+
date: 2015-08-03 13:24:06 +0200
5+
comments: false
6+
author: rafa
7+
categories:
8+
---
9+
You may haven't heard about this law or if you have, you may have wondered [who's this Demeter guy](http://homepages.cwi.nl/~storm/teaching/reader/LieberherrHolland89.pdf). Regardless of it, the Law Of Demeter (LoD) is a foundation concept that's used among several design patterns, to wit: Delegate, Proxy, Façade, Adapter and Decorator. Therefore, you probably are already taking advantage of this Law, knowing it or not.
10+
11+
There's a particular situation that occurs with iOS, that's perfect for applying the LoD. Sometimes it's needed to call method in our `UIApplicationDelegate`. The common way of doing that is the following:
12+
13+
```swift
14+
let sharedApplication = UIApplication.sharedApplication()
15+
let delegate = sharedApplication.delegate
16+
if let delegate = delegate as? AppDelegate {
17+
delegate.doSomething()
18+
}
19+
```
20+
There are too many temporary objects, and presumably, there's no reason why this class should know about `AppDelegate` casting and so on.
21+
22+
Using the `Decorator` pattern, is a way to wrap up this logic and decouple stuff.
23+
24+
```swift
25+
extension UIApplication {
26+
class func myDelegate() -> AppDelegate {
27+
return (self.sharedApplication().delegate as! AppDelegate)
28+
}
29+
class func doSomething() {
30+
myDelegate().doSomething()
31+
}
32+
}
33+
34+
extension AppDelegate {
35+
class func doSomething() {
36+
UIApplication.doSomething()
37+
}
38+
}
39+
``
40+
41+
Now the class would just call `UIApplication.doSomething()` or `AppDelegate.doSomething()`.
42+
43+
Another situation that's a claimer for LoD is when you have chained 'get' statements, for example:
44+
45+
```swift
46+
let myDesire = Metallica().gimmeFuel().gimmeFire().gimmeThatWhichIDesire()
47+
``
48+
49+
In such a case, the `Metallica` class should be refactored and provide it with a mean of calling `Metallica().gimmeThatWhichIDesire()`, for example:
50+
51+
```swift
52+
class Metallica {
53+
func fuelSetOnFire(fuel: Fuel) -> Fire {
54+
return Fire.setFuelOnFire(fuel)
55+
}
56+
57+
func gimmeThatWhichIDesire() -> Desire {
58+
return Desire.fromFire(fuelSetOnFire(metallicasFuel))
59+
}
60+
}
61+
```
62+
63+
Wrapping up method calls, separating concerns and decoupling classes are the spine of LoD. Some can say that objects become more complex, but one thing is for sure, your software components will be more testable, and that is a big win!
64+
65+
Now go ahead and follow the rule!

0 commit comments

Comments
 (0)