SlideShare a Scribd company logo
Vodafone Proprietary classified as C2 - Internal
1 November 20192
Vodafone Proprietary classified as C2 - Internal
MVVM With Dependency
Injection
Yahya Saddiq
13 October 2019
Vodafone Proprietary classified as C2 - Internal
1 November 20194
• Now, after working for a few years in this area, cooperating with many excellent
engineers, I realized that the product design doesn’t really make the code so
complex. It’s me who makes it so complicated.
• We have the experience writing spaghetti code which significantly hurts the
performance of our projects. The question is how can we fix it?
A good architecture pattern might help.
Vodafone Proprietary classified as C2 - Internal
1 November 20195
• The term “good architecture” may sound way too abstract. It’s also difficult to know
where to start. Here’s a tip:
Instead of focusing on the definition of the architecture, we can focus on how to
improve the testability of the code
Vodafone Proprietary classified as C2 - Internal
1 November 20196
• We might not be able to master all of different types of architectures. However, we
are still able to keep a simple rule in mind:
no matter what architecture we decide to use, the ultimate goal is to
make test simpler
Vodafone Proprietary classified as C2 - Internal
1 November 20197
• Using “Make test simpler” approach helps us to:
– Start thinking before writing code
– Put emphasis on how to separate responsibility intuitively
– have a clear and reasonable mindset toward the design of the architecture.
– not stuck in trivial details anymore.
Vodafone Proprietary classified as C2 - Internal
1 November 20198
• I’ll talk about:
– The reason we choose the MVVM over the Apple MVC
– How to adapt MVVM to design a clearer architecture
– How to write a simple real-world app based on the MVVM
• I won’t talk about::
– The comparison between MVVM, and other architecture
– A silver bullet that will solve all problems
Vodafone Proprietary classified as C2 - Internal
1 November 20199
• Model
– Responsible for the business logic of the application.
– Reading and writing data
– Persisting application state
– May even include tasks related to data management, such as networking and data validation.
MVC (Model-View-Controller)
Vodafone Proprietary classified as C2 - Internal
1 November 201910
• View
– Should have two important tasks:
– presenting data to the user
– handling user interaction
– A core principle of the MVC pattern is the view layer's ignorance with respect to the model layer.
– Views are dumb objects.
– They only know how to present data to the user.
– They don't know or understand what they are presenting.
MVC (Model-View-Controller)
Vodafone Proprietary classified as C2 - Internal
1 November 201911
• Controller
– The view and model layers are glued together by one viewContoller.
– A controller knows about the view layer as well as the model layer.
– This often results in tight coupling, making controllers the least reusable component of an application based on the
MVC pattern.
MVC (Model-View-Controller)
Vodafone Proprietary classified as C2 - Internal
MVC Advantages
1 November 201912
• Separation of concerns
– In most applications, there is no confusion about what belongs in the view and model layer.
– What goes into controllers is often less clear.
– The result is that controllers are frequently used for everything that doesn't clearly belong in the view or
model layer.
• Reusability
– Whereas controllers are often not reusable, view and model objects are easy to reuse.
Vodafone Proprietary classified as C2 - Internal
MVC Problems
1 November 201913
• A clear separation of concerns is great.
– It makes our life as a developers easier.
– Projects are easier to architect and structure.
But that is only part of the story.
• If the code we write doesn't belong in the view or model layer. No problem. Dump it
in the controller. Problem solved. Right?
Not really.
Vodafone Proprietary classified as C2 - Internal
MVC Problem Example
1 November 201914
• Data formatting is a common task.
– Imagine that you are developing an invoicing application.
– Each invoice has a creation date.
– Depending on the locale of the user, the date of an invoice needs to be formatted differently.
• The creation date of an invoice is stored in the model layer and the view displays
the formatted date. That is obvious. But who is responsible for formatting the date?
– Remember that the view shouldn't need to understand what it is presenting to the user.
– But why should the model be responsible for a task that is related to the user interface?
Vodafone Proprietary classified as C2 - Internal
MVC Problem Example
1 November 201915
• Wait a minute.
– What about our good old controller?
– That’s why we called it a Massive View Controller.
MVVM is here to rescue
Vodafone Proprietary classified as C2 - Internal
1 November 201916
MVVM is proposed by John Gossman in 2005.
The main purpose of the MVVM is to move the
data state from the View to the ViewModel.
Vodafone Proprietary classified as C2 - Internal
MVVM (Model — View — ViewModel)
1 November 201917
• View
– According to the definition, the View consists of only visual elements.
– In the View, we only do things like layout, animation, initializing UI components, etc.
• ViewModel
– There’s a special layer between the View and the Model called the ViewModel
– The ViewModel is the representation of the View.
– ViewModel provides a set of interfaces, each of which represents a UI component in the View.
Vodafone Proprietary classified as C2 - Internal
MVVM (Model — View — ViewModel)
1 November 201918
• Binding
– We use a technique called “binding” to connect UI components to ViewModel interfaces.
– So, in MVVM, we don’t touch the View directly, we deal with business logic in the ViewModel and thus
the View changes itself accordingly.
• We write presentational things such as converting Date to String in the ViewModel
instead of the View
Therefore, it becomes possible to write a simpler test for the presentational logic
without knowing the implementation of the View.
Vodafone Proprietary classified as C2 - Internal
1 November 201919
Let’s take a higher look at the figure below.
– In general, the ViewModel receives the user interaction from the View,
– fetches data from the Model,
– then process the data to a set of ready-to-display properties.
– The View updates itself after observing the change of the ViewModel.
That’s the whole story of the MVVM.
Vodafone Proprietary classified as C2 - Internal
20 1 November 2019
We are going to see a simple app, in which:
– The app fetches popular photos from 500px API and lists
photos in a UITableView.
– Each cell in the table view shows a title, a description and the
created date of a photo.
– Users are not allowed to click photos which are not labeled
for_sale.
A simple gallery app — MVC
Vodafone Proprietary classified as C2 - Internal
1 November 201921
So what’s wrong with the code?
(The 4 problems)
A simple gallery app — MVC
Vodafone Proprietary classified as C2 - Internal
1 November 201922
• If you plan to write tests for the PhotoListViewController, we’ll find
ourselves stuck since it’s too complicated.
• We have to mock the APIService, mock the table view and mock the
cell to test the whole PhotoListViewController.
A simple gallery app — MVC
Vodafone Proprietary classified as C2 - Internal
1 November 201923
Remember that we want to make writing tests easier?
.
.
.
Let’s try MVVM approach!
Vodafone Proprietary classified as C2 - Internal
1 November 201924
• In order to solve the problem, our first priority is to clean up the view controller
• Split the view controller into two parts: the View and the ViewModel.
• To be specific, we are going to:
– Design a set of interfaces for binding.
– Move the presentational logic and controller logic to the ViewModel.
VCs Comparing Time!
Try MVVM
Vodafone Proprietary classified as C2 - Internal
25 1 November 2019
• Let’s take a look at the UI components
in the View:
– Activity Indicator (loading/finish)
– TableView (show/hide)
– Cells (title, description, created date)
• Each UI component has a
corresponding
property in the ViewModel.
• We can say that what we will see in the
View should be the same as what
we see in the ViewModel.
Vodafone Proprietary classified as C2 - Internal
1 November 201926
But how do we do the binding?
(KVO, RxSwift, DIY)
Vodafone Proprietary classified as C2 - Internal
1 November 201927
• Practically, in the ViewModel an interface/property for binding looks like this:
• On the other hand, in the View, we assign a closure to the propChanged as a callback closure for value
updates.
Vodafone Proprietary classified as C2 - Internal
1 November 201928
Interfaces for binding in ViewModel
(cellViewModels, numberOfCells, state)
Vodafone Proprietary classified as C2 - Internal
1 November 201929
Bind the View with the ViewModel
(callback closures in initVM())
Vodafone Proprietary classified as C2 - Internal
30 1 November 2019
Data Flow
1. The PhotoListViewModel starts to
fetch data.
2. After the data fetched, we
create PhotoListCellViewModel obje
cts and update the cellViewModels.
3. The PhotoListViewController is
notified of the update and then
layouts cells using the
updated cellViewModels.
Vodafone Proprietary classified as C2 - Internal
1 November 201931
Dealing with user interaction
(viewModel.userPressed())
Vodafone Proprietary classified as C2 - Internal
1 November 201932
Inject the dependency
The APIService
(filling cellViewModel)
Vodafone Proprietary classified as C2 - Internal
1 November 201933
Yay, we crafted the MVVM
🎉🎉🎉
Vodafone Proprietary classified as C2 - Internal
1 November 201934
Recap
• Made a binding theme using the closure.
• Removed all controller logic from the View.
• Created a testable ViewModel.
“The secret to getting ahead is getting started.” — Mark Twain

More Related Content

What's hot

Web worker in your angular application
Web worker in your angular applicationWeb worker in your angular application
Web worker in your angular application
Suresh Patidar
 
Modular Monoliths with Nx
Modular Monoliths with NxModular Monoliths with Nx
Modular Monoliths with Nx
stefanhaasprivat
 
SQL Server效能調校
SQL Server效能調校SQL Server效能調校
SQL Server效能調校
國昭 張
 
Lombok ハンズオン
Lombok ハンズオンLombok ハンズオン
Lombok ハンズオン
Hiroto Yamakawa
 
Service Oriented Architecture & Beyond
Service Oriented Architecture & BeyondService Oriented Architecture & Beyond
Service Oriented Architecture & Beyond
Imesh Gunaratne
 
A Framework Driven Development
A Framework Driven DevelopmentA Framework Driven Development
A Framework Driven Development
정민 안
 
iOS Modular Architecture with Tuist
iOS Modular Architecture with TuistiOS Modular Architecture with Tuist
iOS Modular Architecture with Tuist
정민 안
 
EC-CUBE + PHPUnit で 実践テスト駆動開発
EC-CUBE + PHPUnit で 実践テスト駆動開発EC-CUBE + PHPUnit で 実践テスト駆動開発
EC-CUBE + PHPUnit で 実践テスト駆動開発
Kentaro Ohkouchi
 
A GraphQL approach to Healthcare Information Exchange with HL7 FHIR
A GraphQL approach to Healthcare Information Exchange with HL7 FHIRA GraphQL approach to Healthcare Information Exchange with HL7 FHIR
A GraphQL approach to Healthcare Information Exchange with HL7 FHIR
Suresh KUMAR Mukhiya
 
Building rich domain models with ddd and tdd ivan paulovich - betsson
Building rich domain models with ddd and tdd   ivan paulovich - betssonBuilding rich domain models with ddd and tdd   ivan paulovich - betsson
Building rich domain models with ddd and tdd ivan paulovich - betsson
Ivan Paulovich
 
Integração de Sistemas utilizando Apache Camel
Integração de Sistemas utilizando Apache CamelIntegração de Sistemas utilizando Apache Camel
Integração de Sistemas utilizando Apache Camel
Pedro Oliveira
 
Criando uma arquitetura de front-end do zero
Criando uma arquitetura de front-end do zeroCriando uma arquitetura de front-end do zero
Criando uma arquitetura de front-end do zeroEduardo Shiota Yasuda
 
Decomposing Applications for Scalability and Deployability (April 2012)
Decomposing Applications for Scalability and Deployability (April 2012)Decomposing Applications for Scalability and Deployability (April 2012)
Decomposing Applications for Scalability and Deployability (April 2012)
Chris Richardson
 
InjectionIII의 Hot Reload를 이용하여 앱 개발을 좀 더 편하게 하기.pdf
InjectionIII의 Hot Reload를 이용하여 앱 개발을 좀 더 편하게 하기.pdfInjectionIII의 Hot Reload를 이용하여 앱 개발을 좀 더 편하게 하기.pdf
InjectionIII의 Hot Reload를 이용하여 앱 개발을 좀 더 편하게 하기.pdf
정민 안
 
AWS Webcast - High Availability with Route 53 DNS Failover
AWS Webcast - High Availability with Route 53 DNS FailoverAWS Webcast - High Availability with Route 53 DNS Failover
AWS Webcast - High Availability with Route 53 DNS Failover
Amazon Web Services
 
OpenStreetMap Geocoder Based on Solr
OpenStreetMap Geocoder Based on SolrOpenStreetMap Geocoder Based on Solr
OpenStreetMap Geocoder Based on Solr
lucenerevolution
 
[COSCUP 2022] Kotlin Collection 遊樂園
[COSCUP 2022] Kotlin Collection 遊樂園[COSCUP 2022] Kotlin Collection 遊樂園
[COSCUP 2022] Kotlin Collection 遊樂園
Shengyou Fan
 
React Interview Questions and Answers | React Tutorial | React Redux Online T...
React Interview Questions and Answers | React Tutorial | React Redux Online T...React Interview Questions and Answers | React Tutorial | React Redux Online T...
React Interview Questions and Answers | React Tutorial | React Redux Online T...
Edureka!
 
Accel series 2022_winter
Accel series 2022_winterAccel series 2022_winter
Accel series 2022_winter
NTTDATA INTRAMART
 

What's hot (20)

Web worker in your angular application
Web worker in your angular applicationWeb worker in your angular application
Web worker in your angular application
 
Modular Monoliths with Nx
Modular Monoliths with NxModular Monoliths with Nx
Modular Monoliths with Nx
 
SQL Server效能調校
SQL Server效能調校SQL Server效能調校
SQL Server效能調校
 
Lombok ハンズオン
Lombok ハンズオンLombok ハンズオン
Lombok ハンズオン
 
Service Oriented Architecture & Beyond
Service Oriented Architecture & BeyondService Oriented Architecture & Beyond
Service Oriented Architecture & Beyond
 
Introducing ELK
Introducing ELKIntroducing ELK
Introducing ELK
 
A Framework Driven Development
A Framework Driven DevelopmentA Framework Driven Development
A Framework Driven Development
 
iOS Modular Architecture with Tuist
iOS Modular Architecture with TuistiOS Modular Architecture with Tuist
iOS Modular Architecture with Tuist
 
EC-CUBE + PHPUnit で 実践テスト駆動開発
EC-CUBE + PHPUnit で 実践テスト駆動開発EC-CUBE + PHPUnit で 実践テスト駆動開発
EC-CUBE + PHPUnit で 実践テスト駆動開発
 
A GraphQL approach to Healthcare Information Exchange with HL7 FHIR
A GraphQL approach to Healthcare Information Exchange with HL7 FHIRA GraphQL approach to Healthcare Information Exchange with HL7 FHIR
A GraphQL approach to Healthcare Information Exchange with HL7 FHIR
 
Building rich domain models with ddd and tdd ivan paulovich - betsson
Building rich domain models with ddd and tdd   ivan paulovich - betssonBuilding rich domain models with ddd and tdd   ivan paulovich - betsson
Building rich domain models with ddd and tdd ivan paulovich - betsson
 
Integração de Sistemas utilizando Apache Camel
Integração de Sistemas utilizando Apache CamelIntegração de Sistemas utilizando Apache Camel
Integração de Sistemas utilizando Apache Camel
 
Criando uma arquitetura de front-end do zero
Criando uma arquitetura de front-end do zeroCriando uma arquitetura de front-end do zero
Criando uma arquitetura de front-end do zero
 
Decomposing Applications for Scalability and Deployability (April 2012)
Decomposing Applications for Scalability and Deployability (April 2012)Decomposing Applications for Scalability and Deployability (April 2012)
Decomposing Applications for Scalability and Deployability (April 2012)
 
InjectionIII의 Hot Reload를 이용하여 앱 개발을 좀 더 편하게 하기.pdf
InjectionIII의 Hot Reload를 이용하여 앱 개발을 좀 더 편하게 하기.pdfInjectionIII의 Hot Reload를 이용하여 앱 개발을 좀 더 편하게 하기.pdf
InjectionIII의 Hot Reload를 이용하여 앱 개발을 좀 더 편하게 하기.pdf
 
AWS Webcast - High Availability with Route 53 DNS Failover
AWS Webcast - High Availability with Route 53 DNS FailoverAWS Webcast - High Availability with Route 53 DNS Failover
AWS Webcast - High Availability with Route 53 DNS Failover
 
OpenStreetMap Geocoder Based on Solr
OpenStreetMap Geocoder Based on SolrOpenStreetMap Geocoder Based on Solr
OpenStreetMap Geocoder Based on Solr
 
[COSCUP 2022] Kotlin Collection 遊樂園
[COSCUP 2022] Kotlin Collection 遊樂園[COSCUP 2022] Kotlin Collection 遊樂園
[COSCUP 2022] Kotlin Collection 遊樂園
 
React Interview Questions and Answers | React Tutorial | React Redux Online T...
React Interview Questions and Answers | React Tutorial | React Redux Online T...React Interview Questions and Answers | React Tutorial | React Redux Online T...
React Interview Questions and Answers | React Tutorial | React Redux Online T...
 
Accel series 2022_winter
Accel series 2022_winterAccel series 2022_winter
Accel series 2022_winter
 

Similar to MVVM with Dependency Injection

Android MVVM
Android MVVMAndroid MVVM
Mvvm
MvvmMvvm
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVM
Mudasir Qazi
 
Architectural Design Pattern: Android
Architectural Design Pattern: AndroidArchitectural Design Pattern: Android
Architectural Design Pattern: Android
Jitendra Kumar
 
Task 2 - Educational Article – Model View Controller (MVC)
Task 2 - Educational Article – Model View Controller (MVC)Task 2 - Educational Article – Model View Controller (MVC)
Task 2 - Educational Article – Model View Controller (MVC)Shubham Goenka
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patterns
allanh0526
 
Models used in iOS programming, with a focus on MVVM
Models used in iOS programming, with a focus on MVVMModels used in iOS programming, with a focus on MVVM
Models used in iOS programming, with a focus on MVVM
Andrei Popa
 
Unit Testing and Why it Matters
Unit Testing and Why it MattersUnit Testing and Why it Matters
Unit Testing and Why it Matters
yahyaSadiiq
 
MVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,MobileMVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,Mobile
naral
 
RESUME BUILDER WEB APPLICATION
RESUME BUILDER WEB APPLICATIONRESUME BUILDER WEB APPLICATION
RESUME BUILDER WEB APPLICATION
IRJET Journal
 
реалии использования Mv в i os разработке
реалии использования Mv в i os разработкереалии использования Mv в i os разработке
реалии использования Mv в i os разработке
Provectus
 
Automating Screenshot Testing Component Library
Automating Screenshot Testing Component LibraryAutomating Screenshot Testing Component Library
Automating Screenshot Testing Component Library
Applitools
 
Knockout js
Knockout jsKnockout js
Workshop on Sencha Touch - Part 3 - MVC in sencha touch
Workshop on Sencha Touch - Part 3 - MVC in sencha touchWorkshop on Sencha Touch - Part 3 - MVC in sencha touch
Workshop on Sencha Touch - Part 3 - MVC in sencha touch
Nithya Sivakumar
 
Adopting MVVM
Adopting MVVMAdopting MVVM
Adopting MVVM
John Cumming
 
Patterns of evolution from monolith to microservices
Patterns of evolution from monolith to microservicesPatterns of evolution from monolith to microservices
Patterns of evolution from monolith to microservices
Karina Mora
 
MV(C, mvvm) in iOS and ReactiveCocoa
MV(C, mvvm) in iOS and ReactiveCocoaMV(C, mvvm) in iOS and ReactiveCocoa
MV(C, mvvm) in iOS and ReactiveCocoa
Yi-Shou Chen
 
Code Camp 06 Model View Presenter Architecture
Code Camp 06   Model View Presenter ArchitectureCode Camp 06   Model View Presenter Architecture
Code Camp 06 Model View Presenter Architecture
bitburner93
 
Why MVC?
Why MVC?Why MVC?
Why MVC?
Wayne Tun Myint
 
1040 ibm worklight delivering agility to mobile cloud deployments
1040 ibm worklight  delivering agility to mobile cloud deployments1040 ibm worklight  delivering agility to mobile cloud deployments
1040 ibm worklight delivering agility to mobile cloud deploymentsTodd Kaplinger
 

Similar to MVVM with Dependency Injection (20)

Android MVVM
Android MVVMAndroid MVVM
Android MVVM
 
Mvvm
MvvmMvvm
Mvvm
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVM
 
Architectural Design Pattern: Android
Architectural Design Pattern: AndroidArchitectural Design Pattern: Android
Architectural Design Pattern: Android
 
Task 2 - Educational Article – Model View Controller (MVC)
Task 2 - Educational Article – Model View Controller (MVC)Task 2 - Educational Article – Model View Controller (MVC)
Task 2 - Educational Article – Model View Controller (MVC)
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patterns
 
Models used in iOS programming, with a focus on MVVM
Models used in iOS programming, with a focus on MVVMModels used in iOS programming, with a focus on MVVM
Models used in iOS programming, with a focus on MVVM
 
Unit Testing and Why it Matters
Unit Testing and Why it MattersUnit Testing and Why it Matters
Unit Testing and Why it Matters
 
MVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,MobileMVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,Mobile
 
RESUME BUILDER WEB APPLICATION
RESUME BUILDER WEB APPLICATIONRESUME BUILDER WEB APPLICATION
RESUME BUILDER WEB APPLICATION
 
реалии использования Mv в i os разработке
реалии использования Mv в i os разработкереалии использования Mv в i os разработке
реалии использования Mv в i os разработке
 
Automating Screenshot Testing Component Library
Automating Screenshot Testing Component LibraryAutomating Screenshot Testing Component Library
Automating Screenshot Testing Component Library
 
Knockout js
Knockout jsKnockout js
Knockout js
 
Workshop on Sencha Touch - Part 3 - MVC in sencha touch
Workshop on Sencha Touch - Part 3 - MVC in sencha touchWorkshop on Sencha Touch - Part 3 - MVC in sencha touch
Workshop on Sencha Touch - Part 3 - MVC in sencha touch
 
Adopting MVVM
Adopting MVVMAdopting MVVM
Adopting MVVM
 
Patterns of evolution from monolith to microservices
Patterns of evolution from monolith to microservicesPatterns of evolution from monolith to microservices
Patterns of evolution from monolith to microservices
 
MV(C, mvvm) in iOS and ReactiveCocoa
MV(C, mvvm) in iOS and ReactiveCocoaMV(C, mvvm) in iOS and ReactiveCocoa
MV(C, mvvm) in iOS and ReactiveCocoa
 
Code Camp 06 Model View Presenter Architecture
Code Camp 06   Model View Presenter ArchitectureCode Camp 06   Model View Presenter Architecture
Code Camp 06 Model View Presenter Architecture
 
Why MVC?
Why MVC?Why MVC?
Why MVC?
 
1040 ibm worklight delivering agility to mobile cloud deployments
1040 ibm worklight  delivering agility to mobile cloud deployments1040 ibm worklight  delivering agility to mobile cloud deployments
1040 ibm worklight delivering agility to mobile cloud deployments
 

Recently uploaded

OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 

Recently uploaded (20)

OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 

MVVM with Dependency Injection

  • 1.
  • 2. Vodafone Proprietary classified as C2 - Internal 1 November 20192
  • 3. Vodafone Proprietary classified as C2 - Internal MVVM With Dependency Injection Yahya Saddiq 13 October 2019
  • 4. Vodafone Proprietary classified as C2 - Internal 1 November 20194 • Now, after working for a few years in this area, cooperating with many excellent engineers, I realized that the product design doesn’t really make the code so complex. It’s me who makes it so complicated. • We have the experience writing spaghetti code which significantly hurts the performance of our projects. The question is how can we fix it? A good architecture pattern might help.
  • 5. Vodafone Proprietary classified as C2 - Internal 1 November 20195 • The term “good architecture” may sound way too abstract. It’s also difficult to know where to start. Here’s a tip: Instead of focusing on the definition of the architecture, we can focus on how to improve the testability of the code
  • 6. Vodafone Proprietary classified as C2 - Internal 1 November 20196 • We might not be able to master all of different types of architectures. However, we are still able to keep a simple rule in mind: no matter what architecture we decide to use, the ultimate goal is to make test simpler
  • 7. Vodafone Proprietary classified as C2 - Internal 1 November 20197 • Using “Make test simpler” approach helps us to: – Start thinking before writing code – Put emphasis on how to separate responsibility intuitively – have a clear and reasonable mindset toward the design of the architecture. – not stuck in trivial details anymore.
  • 8. Vodafone Proprietary classified as C2 - Internal 1 November 20198 • I’ll talk about: – The reason we choose the MVVM over the Apple MVC – How to adapt MVVM to design a clearer architecture – How to write a simple real-world app based on the MVVM • I won’t talk about:: – The comparison between MVVM, and other architecture – A silver bullet that will solve all problems
  • 9. Vodafone Proprietary classified as C2 - Internal 1 November 20199 • Model – Responsible for the business logic of the application. – Reading and writing data – Persisting application state – May even include tasks related to data management, such as networking and data validation. MVC (Model-View-Controller)
  • 10. Vodafone Proprietary classified as C2 - Internal 1 November 201910 • View – Should have two important tasks: – presenting data to the user – handling user interaction – A core principle of the MVC pattern is the view layer's ignorance with respect to the model layer. – Views are dumb objects. – They only know how to present data to the user. – They don't know or understand what they are presenting. MVC (Model-View-Controller)
  • 11. Vodafone Proprietary classified as C2 - Internal 1 November 201911 • Controller – The view and model layers are glued together by one viewContoller. – A controller knows about the view layer as well as the model layer. – This often results in tight coupling, making controllers the least reusable component of an application based on the MVC pattern. MVC (Model-View-Controller)
  • 12. Vodafone Proprietary classified as C2 - Internal MVC Advantages 1 November 201912 • Separation of concerns – In most applications, there is no confusion about what belongs in the view and model layer. – What goes into controllers is often less clear. – The result is that controllers are frequently used for everything that doesn't clearly belong in the view or model layer. • Reusability – Whereas controllers are often not reusable, view and model objects are easy to reuse.
  • 13. Vodafone Proprietary classified as C2 - Internal MVC Problems 1 November 201913 • A clear separation of concerns is great. – It makes our life as a developers easier. – Projects are easier to architect and structure. But that is only part of the story. • If the code we write doesn't belong in the view or model layer. No problem. Dump it in the controller. Problem solved. Right? Not really.
  • 14. Vodafone Proprietary classified as C2 - Internal MVC Problem Example 1 November 201914 • Data formatting is a common task. – Imagine that you are developing an invoicing application. – Each invoice has a creation date. – Depending on the locale of the user, the date of an invoice needs to be formatted differently. • The creation date of an invoice is stored in the model layer and the view displays the formatted date. That is obvious. But who is responsible for formatting the date? – Remember that the view shouldn't need to understand what it is presenting to the user. – But why should the model be responsible for a task that is related to the user interface?
  • 15. Vodafone Proprietary classified as C2 - Internal MVC Problem Example 1 November 201915 • Wait a minute. – What about our good old controller? – That’s why we called it a Massive View Controller. MVVM is here to rescue
  • 16. Vodafone Proprietary classified as C2 - Internal 1 November 201916 MVVM is proposed by John Gossman in 2005. The main purpose of the MVVM is to move the data state from the View to the ViewModel.
  • 17. Vodafone Proprietary classified as C2 - Internal MVVM (Model — View — ViewModel) 1 November 201917 • View – According to the definition, the View consists of only visual elements. – In the View, we only do things like layout, animation, initializing UI components, etc. • ViewModel – There’s a special layer between the View and the Model called the ViewModel – The ViewModel is the representation of the View. – ViewModel provides a set of interfaces, each of which represents a UI component in the View.
  • 18. Vodafone Proprietary classified as C2 - Internal MVVM (Model — View — ViewModel) 1 November 201918 • Binding – We use a technique called “binding” to connect UI components to ViewModel interfaces. – So, in MVVM, we don’t touch the View directly, we deal with business logic in the ViewModel and thus the View changes itself accordingly. • We write presentational things such as converting Date to String in the ViewModel instead of the View Therefore, it becomes possible to write a simpler test for the presentational logic without knowing the implementation of the View.
  • 19. Vodafone Proprietary classified as C2 - Internal 1 November 201919 Let’s take a higher look at the figure below. – In general, the ViewModel receives the user interaction from the View, – fetches data from the Model, – then process the data to a set of ready-to-display properties. – The View updates itself after observing the change of the ViewModel. That’s the whole story of the MVVM.
  • 20. Vodafone Proprietary classified as C2 - Internal 20 1 November 2019 We are going to see a simple app, in which: – The app fetches popular photos from 500px API and lists photos in a UITableView. – Each cell in the table view shows a title, a description and the created date of a photo. – Users are not allowed to click photos which are not labeled for_sale. A simple gallery app — MVC
  • 21. Vodafone Proprietary classified as C2 - Internal 1 November 201921 So what’s wrong with the code? (The 4 problems) A simple gallery app — MVC
  • 22. Vodafone Proprietary classified as C2 - Internal 1 November 201922 • If you plan to write tests for the PhotoListViewController, we’ll find ourselves stuck since it’s too complicated. • We have to mock the APIService, mock the table view and mock the cell to test the whole PhotoListViewController. A simple gallery app — MVC
  • 23. Vodafone Proprietary classified as C2 - Internal 1 November 201923 Remember that we want to make writing tests easier? . . . Let’s try MVVM approach!
  • 24. Vodafone Proprietary classified as C2 - Internal 1 November 201924 • In order to solve the problem, our first priority is to clean up the view controller • Split the view controller into two parts: the View and the ViewModel. • To be specific, we are going to: – Design a set of interfaces for binding. – Move the presentational logic and controller logic to the ViewModel. VCs Comparing Time! Try MVVM
  • 25. Vodafone Proprietary classified as C2 - Internal 25 1 November 2019 • Let’s take a look at the UI components in the View: – Activity Indicator (loading/finish) – TableView (show/hide) – Cells (title, description, created date) • Each UI component has a corresponding property in the ViewModel. • We can say that what we will see in the View should be the same as what we see in the ViewModel.
  • 26. Vodafone Proprietary classified as C2 - Internal 1 November 201926 But how do we do the binding? (KVO, RxSwift, DIY)
  • 27. Vodafone Proprietary classified as C2 - Internal 1 November 201927 • Practically, in the ViewModel an interface/property for binding looks like this: • On the other hand, in the View, we assign a closure to the propChanged as a callback closure for value updates.
  • 28. Vodafone Proprietary classified as C2 - Internal 1 November 201928 Interfaces for binding in ViewModel (cellViewModels, numberOfCells, state)
  • 29. Vodafone Proprietary classified as C2 - Internal 1 November 201929 Bind the View with the ViewModel (callback closures in initVM())
  • 30. Vodafone Proprietary classified as C2 - Internal 30 1 November 2019 Data Flow 1. The PhotoListViewModel starts to fetch data. 2. After the data fetched, we create PhotoListCellViewModel obje cts and update the cellViewModels. 3. The PhotoListViewController is notified of the update and then layouts cells using the updated cellViewModels.
  • 31. Vodafone Proprietary classified as C2 - Internal 1 November 201931 Dealing with user interaction (viewModel.userPressed())
  • 32. Vodafone Proprietary classified as C2 - Internal 1 November 201932 Inject the dependency The APIService (filling cellViewModel)
  • 33. Vodafone Proprietary classified as C2 - Internal 1 November 201933 Yay, we crafted the MVVM 🎉🎉🎉
  • 34. Vodafone Proprietary classified as C2 - Internal 1 November 201934 Recap • Made a binding theme using the closure. • Removed all controller logic from the View. • Created a testable ViewModel. “The secret to getting ahead is getting started.” — Mark Twain