Courtesy of : https://www.flickr.com/photos/25182350@N03/2604778522

Don’t talk to strangers!

Yotam Golomb
2 min readJul 9, 2019

Every child knows : Don’t talk to strangers! but then that child grows up, finishes high school, goes to college/university, learns computer science / software engineering and forgets. That child, now an iOS Developer, got a task. He needs to implement a UITableView for ToDo items. And this is what he wrote using the delegates needed :

Sure. this of course works. Some of you will stop here. BUT! This implementation violates a law. The “Don’t talk to Strangers” Law — also knows as the Law of Demeter.

The main principles are :

  • Each unit should have only limited knowledge about other units: only units “closely” related to the current unit.
  • Each unit should only talk to its friends; don’t talk to strangers.
  • Only talk to your immediate friends.

In the code example above you should notice the following :

  • In numberOfRowsInSection method we go to count property on toDoItemsarray in ToDoItemsModel class.
  • In cellForRowAt method we go to names of toDoItems in toDoItems array of ToDoItemsModel class.
  • ToDoItemsListDataProvider class has too much knowledge of ToDoItemsModel. That leads to tighter coupling, which is always a bad thing.

So now after a few fixes, it looks like this :

So here we have an improvement which is exactly the Law of Demeter in practice. we are using a new layer of abstractions provided by ToDoItemsModel class. We can get what we need without direct access to toDoItems array on ToDoItemsModel. After these changes we have much cleaner separation, and, as a result, much flexible system.

--

--

Yotam Golomb

Black-Belted Mobile Architect and Leader, Certified LeSS Practitioner. Head of Mobile Guild & RnD Manager @ Augury