Last active
February 7, 2017 07:10
-
-
Save igorwojda/5e1a75746b41f69cf6e2093388e100fc to your computer and use it in GitHub Desktop.
Kotlin examples of following/violation the Law of Demeter LoD (a.k.a. Principle of Least Knowledge PoLK)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Kotlin examples of following/violation Law of Demeter LoD (a.k.a. Principle of Least Knowledge PoLK) | |
* | |
* Law of Demeter for functions requires that a method m of an object O may only invoke the | |
* methods of the following kinds of objects: | |
* 1. O itself | |
* 2. m's parameters | |
* 3. Any objects created/instantiated within m | |
* 4. O's direct component objects | |
* 5. A global variable, accessible by O, in the scope of m | |
* | |
* Law of Demeter violation example: client.getOrder().getPrice() | |
* Law of Demeter following principle: (LawOfDemeterInKotlin class below) | |
*/ | |
val name:String = "John" | |
class LawOfDemeterInKotlin { | |
private var basket: Basket? = null | |
fun doSomething(order: Order) { | |
// (1) it's okay to call class own methods | |
run() | |
// (2) it's okay to call methods on objects passed in to method | |
val price = order.calculatePrice() | |
// (3) it's okay to call methods on any objects created inside class | |
basket = Basket() | |
val item = basket?.getFirstItem() | |
// (4) it's okay to call methods on any objects created inside method | |
val component = Component() | |
component.init() | |
// (5) it's okay to call methods on global variables | |
val userCode = name.toUpperCase() | |
} | |
fun run(){} | |
} | |
class Order(){ | |
fun calculatePrice(){} | |
} | |
class Basket { | |
fun getFirstItem() = "Banana" | |
} | |
class Component { | |
fun init() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment