Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The Law of Demeter

Hieu Vu
January 19, 2023

The Law of Demeter

My first lightning talk in 2023. Presented to Android developers at weekly Android Huddle

Hieu Vu

January 19, 2023
Tweet

More Decks by Hieu Vu

Other Decks in Programming

Transcript

  1. Definition The Law of Demeter (LoD) or principle of least

    knowledge is a design guideline for developing software, particularly object-oriented programs. - “Wikipedia”
  2. Statement Method m of an object O may only invoke

    the methods of the following kinds of objects: • O itself • m’s parameters • Any objects created/instantiated within m • O’s direct component objects
  3. Example class OClass() { private val helper: Object fun someMethod()

    {} fun methodM(param1: Any, param2: Any) { // Valid helper.doSomething() // Valid val result = param1.revert() // Valid val resultHandler = Handler() resultHandler.resolve(result) // Valid someMethod()
  4. Advantages • Dependencies between classes & coupling are reduced •

    Cleaner tests • Code is easier to be analyzed
  5. Violation class CreditCardManager() { fun charge(creditCard: CreditCard): Result { val

    processor: CreditCardProcessor = CreditCardProcessor() processor.extractCardNumber(creditCard) val info = processor.getCardInfoManager().processPrechargeInfo() (*) return this.updateChargeInfo(info) } fun updateChargeInfo(info: PrechargeInfo): Result { ... } }
  6. Testing class CreditCartManagerTest() { // Given this testee already setted

    up private val testee: CreditCardManager @Test fun givenCreditCard_whenCharge_thenReturnSuccess() { // given val creditCard = CreditCard(balance = 12) // when val result = testee.charge(creditCard = creditCard) // then assertResultSuccess(result = result) } }
  7. Testing Exception in thread "main" java.lang.NullPointerException at FileKt.main (File.kt:3) at

    FileKt.main (File.kt:-1) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2) When build: When run test:
  8. Refactor Code class CreditCardManager() { fun charge(creditCard: CreditCard, cardInfoManager: CardInfoManager):

    Result { val processor: CreditCartProcessor = CreditCardProcessor() processor.extractCardNumber(creditCard) val info = cardInfoManager.processPrechargeInfo() return this.updateChargeInfo(info) } fun updateChargeInfo(info: PrechargeInfo): Result { ... } }
  9. Refactor Test @Test fun givenCreditCard_whenCharge_thenReturnSuccess() { // given val creditCard

    = CreditCard(balance = 12) val cardInfoManager = CardInfoManager(dependencies = easyToMockDependencies) // when val result = testee.charge(creditCard = creditCard, cardInfoManager = cardInfoManager) // then assertResultSuccess(result = result) }
  10. References The Law of Demeter in the area of microservices

    Breaking the Law of Demeter - Google Testing blog The Beautiful Law of Demeter