Avoid Switch Cases In TableView And Collection View — Chain Of Responsibility

Avoid Switch Cases In TableView And Collection View — Chain Of Responsibility

In my previous article, “Avoiding Switch Cases with TableView and CollectionView in iOS”, I discussed why relying too heavily on switch statements can make your code harder to maintain and scale. However, some readers pointed out that I still included some switch statements to demonstrate the concepts, which seemed contradictory.

In this follow-up, I want to clarify my stance, address that feedback, and showcase a more refined, pattern-driven approach to handling multiple cell types in a UITableView or UICollectionView. If you’re revisiting from the first article or just jumping in now, I hope to provide clear, actionable strategies for writing cleaner, more flexible code.


How Do You Keep Your TableView Scalable with Multiple Cell Types?

While this code is straightforward and works well for small projects, it quickly becomes unwieldy in larger ones.

What’s the Issue?

1. Violation of SOLID Principles

  • Single Responsibility Principle (SRP): The ViewController handles too much responsibility, including the configuration of cells, their selection logic, and even their layout. This leads to a Massive View Controller.

  • Open-Closed Principle (OCP): Every time a new cell type is added, you must modify the ViewController code, making it harder to maintain and extend.

2. Scalability Challenges

  • The growing number of switch cases increases complexity and makes the code harder to debug and read.

  • Adding a new cell type requires changes in multiple places, increasing the likelihood of errors.

The Chain of Responsibility Solution

To overcome the challenges of maintaining a UITableView (or UICollectionView) with multiple cell types while adhering to SOLID principles, the Chain of Responsibility design pattern is a powerful approach. Instead of using switch cases for each cell type, you distribute responsibilities among multiple “handlers,” each specializing in a specific cell type.

Benefits

Eliminate Large Switch Statements: Each handler decides whether it can handle a particular cell type.

Open-Closed Principle Compliance: You can add new cell handlers for additional cell types without modifying existing handlers.

Single Responsibility Principle Compliance: The view controller delegates cell configuration and actions to specialized handlers, reducing its responsibilities.

How Does the Chain of Responsibility Work in a TableView?

  1. Define a Protocol: Create a protocol that each cell handler will implement to determine if it can handle a specific cell type.

2. Create Handlers: Each handler is responsible for a specific cell type.

You would then create similar classes (SecondCellHandler, ThirdCellHandler, etc.) for each cell type.

3. Chain the Handlers: Implement a chain class that iterates through the handlers. Each handler checks whether it can handle the given cell type, and if so, it performs the appropriate logic.

4. Integrate with the ViewModel: Use the view model to provide the cell types and to house a CellHandlerChain instance, decoupling the logic from the view controller.

5. Update ViewController: Finally, the view controller can simply delegate to the chain without maintaining any switch statements of its own.

Adding a New Cell Type (e.g., fourthType)

One of the biggest advantages of the Chain of Responsibility pattern is how easy it is to introduce a new cell type without touching existing code. Suppose you now need to add a fourthType for your table view:

1. Add the New Case to Your Enum

2. Create the FourthCellHandler

3. Add the New Handler to the Chain

Update the DefaultHomeViewModel (or wherever you initialize the chain) to include FourthCellHandler:

4. Use the New Cell Type

Your view model can now populate cellData with .fourthType as needed, and the chain will automatically handle it:

With these simple steps, you’ve added a brand-new cell type without modifying any existing handlers or the view controller. This is the essence of the Open-Closed Principle: your existing code remains closed to modification but open to extension.


Conclusion

By leveraging the Chain of Responsibility design pattern, you can avoid large switch statements while keeping your code organized and adherent to SOLID principles. Each handler class remains focused on a single cell type, simplifying testing and maintenance. When you need to add or modify a cell type, you only touch the relevant handler, leaving the rest of the codebase unchanged. As a result, your application becomes more flexible, your controllers remain cleaner, and your team can scale the project with greater ease and confidence.

If you found this article helpful, be sure to check out the first part of the series, Avoiding Switch Cases with TableView and CollectionView in iOS, and stay tuned for future articles where we delve even deeper into design patterns and best practices in Swift.

Acknowledgment

A special thanks to Essam Fahmy for reviewing this article and providing invaluable suggestions to enhance its content. Your insights have contributed significantly to improving the clarity and depth of the ideas presented here.

Mahmoud Mohamed

Software Engineer (iOS) @ Moddakir

7mo

It's a perfect article, I've got lots of information from it, but I'm wondering what is the best way to inject different type of model for each handler ?

Nabeel Mehfooz Ahmed

Mobile Lead | 13+ years of expertise in Designing, Mentoring and Building robust iOS apps from Ground Zero. Good hands-on experience with Design Patterns, Swift.

7mo

Isn't looping through the cell handlers in various places a bad practice here?

Like
Reply
Mohamed Zaki

Senior iOS developer

7mo

جامد جدا. معلومات مفيدة

جامد كنت اشتغلت على حاجة شبه كده، وكنت مستخدم نفس الفكرة،و زودت عليها مفهوم Fail Fast عشان أتجنب كتابة ـ if-else فى كل handler لكل case عشان اتأكد إن كل handler بيستلم القيم صح.

Essam Fahmy

Technical Lead, Mobile @ Deloitte

7mo

لحظة تقدير لهذا التعاون المثمر والمحتوي الرائع 😂💙 الله ينور عليك يا كريم ومبسوط جدا بالنقاشات بتاعتنا وال inputs اللي بناخدها من بعض ومن مقال للتاني وللتالت باذن الله 💙

To view or add a comment, sign in

Others also viewed

Explore topics