Refactoring the Country Repository in Android

Sep 12, 2024

Notes on Solid with Android - Video 2

Introduction

  • Presented by: Anil Deshpande
  • Focus: Refactoring code in Android, specifically looking beyond the model to the repository.

Recap of Previous Video

  • Refactored DAO, model, and app database with the database provider.
  • Encouraged viewers to revisit the previous video for context.

Current Focus

  • Refactoring the Country Repository.

Country Repository Overview

  • Implements iCountryRepository.
  • Initial code commented out for filtering countries.

Dispatcher Usage

  • All functions currently use withContext(Dispatchers.IO).
  • Dispatcher: Controls where the suspend function executes (in this case on IO dispatcher).
  • OCP Violation: Using an explicit dispatcher in multiple locations.

Proposed Changes

  • Introduce a dispatcher as an argument to the CountryRepository class.
  • Create a variable dispatcher of type CoroutineDispatcher to be used throughout the class.

Implementing Filter Criteria

  • Current filtering methods are rigid (e.g., filtering by continent or drive side).
  • Need for flexibility to add more filters without modifying existing code.

Open/Closed Principle (OCP)

  • Code should be open for extension but closed for modification.
  • Goal: Introduce new filter criteria without altering existing code.

Strategy Pattern Explained

  • Analogy of cooking: Cutting tasks vary based on the object (vegetable, bread, pizza).
  • In coding, filtering should vary depending on the criteria (continent, drive side, language).

Implementation Steps

  1. Create an Interface:
    • Define a FilterCriteria interface with a suspend fun filter(countries: List<Country>): List<Country>.
  2. Implement Filter Criteria Classes:
    • FilterByContinent: Implements filtering by continent.
    • FilterByDriveSide: Implements filtering by drive side.
    • Future filters can be added by creating new classes that implement the FilterCriteria interface.

Updating the Repository

  • Enable the filterCountries function in the CountryRepository.
  • It will receive a FilterCriteria object, which decides how to filter the list of countries.

Next Steps

  • Plan to refactor the ViewModel next.

Conclusion

  • Summary of refactoring repository to adhere to SOLID principles.
  • Encouragement to engage with the video: like, comment, share, and subscribe.
  • Closing remarks: Take care and goodbye.