SlideShare a Scribd company logo
1
Adapting clean architecture
in Android apps
Matso Abgaryan
@AbgaryanMr
linkedin.com/in/matsoab
2
Part one: Clean Architecture
Part two: Clean Architecture in Android
3
What is architecture
4
● Testable
● Independent of the data sources
● Independent of libraries & frameworks
● Independent of the UI
Why should one use a Clean Architecture
5
“Clean Architecture separates the application code into layers and these layers define the
Separation of Concerns inside the codebase.”
Uncle Bob
What is clean architecture
6
Characteristics of a Clean Architecture
Entities
Use Cases
Controllers
G
ateways
P
r
e
s
e
n
t
e
r
s
DB
UI
Web
External
Interfaces
Devices
■ Enterprise Business Rules
■ Application Business Rules
■ Interface Adapters
■ Framework & Drivers
7
● Single Responsibility Principle
● Open-Closed Principle
● Liskov Substitution Principle
● Interface Segregation Principle
● Dependency Inversion Principle
What are SOLID design principles
8
■ A class should have only one reason to change.
What is Single-Responsibility principle
9
fun onBind(trip: Trip) {
itemView.start_name.text = trip.start
itemView.destination_name.text = trip.destination
val formattedDate = DateFormat.getDateInstance().format(
trip.departureTime,
StringBuffer("departure Time : "),
FieldPosition(0)
)
itemView.departure_time.text = formattedDate
}
Bad Example
10
fun onBind(trip: Trip) {
with(itemView) {
start_name.text = trip.start
destination_name.text = trip.destination
departure_time.text = dateUtil.formatDate(trip.departureTime)
}
}
Good Example
11
■ Software entities such as classes, functions, modules should be open
for extension but not modification.
What is Open-closed principle
12
class TimeGreeting(val time :String) {
fun greetingFromTimeOfDay(): String = when (time) {
"Morning" -> {
"Good Morning, sir."
}
"Afternoon" -> {
"Good Afternoon, sir."
}
"Evening" -> {
"Good Evening, sir."
}
else -> {
"Good Night, sir."
}
}
}
Bad Example
13
Good Example
interface Time {
fun greet(): String
}
class Morning : Time {
override fun greet(): String {
return "Good morning, sir."
}
}
class Afternoon : Time {
override fun greet(): String {
return "Good afternoon, sir."
}
}
class Evening : Time {
override fun greet(): String {
return "Good evening, sir."
}
}
class Night : Time {
override fun greet(): String {
return "Good night, sir."
}
}
class TimeGreeting(val time: Time) {
fun greetingFromTimeOfDay(): String =
time.greet()
}
14
■ Child classes should never break the parent class’ type definitions.
What is Liskov Substitution principle
15
open class Rectangle {
private var width: Int = 0
private var height: Int = 0
open fun setWidth(newWidth: Int) {
width = newWidth
}
open fun setHeight(newHeight: Int) {
height = newHeight
}
fun getArea(): Int = width * height
}
Bad Example
val rectangle : Rectangle = Square()
rectangle.setWidth(3)
rectangle.setHeight(5)
rectangle.getArea()
class Square : Rectangle() {
override fun setWidth(newWidth: Int) {
super.setWidth(newWidth)
super.setHeight(newWidth)
}
override fun setHeight(newHeight: Int) {
super.setWidth(newHeight)
super.setHeight(newHeight)
}
}
16
interface Shape {
fun getArea(): Int
}
class Square: Shape {
private var diameter: Int = 0
fun setDiameter(diameter: Int) {
this.diameter = diameter
}
override fun getArea(): Int {
return diameter * diameter
}
}
class Rectangle: Shape {
private var width: Int = 0
private var height: Int = 0
fun setWidth(width: Int) {
this.width = width
}
fun setHeight(height: Int) {
this.height = height
}
override fun getArea(): Int {
return width * height
}
}
Good Example
17
■ The interface-segregation principle (ISP) states that no client should be forced
to depend on methods it does not use.
What is Interface segregation principle
18
interface OnClickListener {
fun onClick()
fun onLongClick()
}
class Button: OnClickListener {
override fun onClick() {}
override fun onLongCLick() {
//does not support Long clicks
}
}
class LongClickButton: OnClickListener{
override fun onClick() {
// does not support short clicks
}
override fun onLongCLick() {}
}
Bad Example
19
interface OnClickListener {
fun onClick()
}
interface OnLongClickListener {
fun onLongCLick()
}
class Button: OnClickListener {
override fun onClick() {}
}
class LongClickButton: OnLongClickListener {
override fun onLongCLick() {}
}
Good Example
20
■ High-level modules should not depend on low-level modules. Both should depend on
abstractions. Abstractions should not depend upon details. Details should depend upon
abstractions.
What is Dependency Inversion principle
21
class WhatsUpMessage {
var whatsUpText:String = ""
}
class MessageBoard {
var message: WhatsUpMessage? = null
fun printMessage() {
println(message?.whatsUpText)
}
}
Bad Example
22
interface IMessage {
fun printMessage()
}
class WhatsUpMessage:IMessage{
override fun printMessage() {}
}
class FaceBookMessage:IMessage{
override fun printMessage() {}
}
class MessageBoard {
var message: IMessage? = null
fun printMessage(){
message?.printMessage()
}
}
Good Example
23
● RRP: The Reuse/Release Equivalence Principle
● CCP: The Common Closure Principle
● CRP: The Common Reuse Principle
What are RRP, CCP, and CRP component principles
24
❏ The granularity of reuse is the granularity of release
What is The Reuse/Release Equivalence Principle
25
❏ Gather into components those classes that change for the same reasons and at the same times
(related to SRP)
What is The Common Closure Principle
26
❏ Don't force users of a component to depend on things they don't need (related to ISP)
What is The Common Reuse Principle
27
The Tension Diagram For Component Cohesion
REP CCP
CRP
To many unneeded releases
To many
components change
Hard to reuse
28
Part one: Clean Architecture
Part two: Clean Architecture in Android
29
What are Clean Architecture layers in Android
■ Domain layer
■ Data layer
■ Presentation layer
Use Cases
Entities
Data Sources
ViewModels
Fragm
ents
A
c
t
i
v
i
t
i
e
s
Repository implementations
30
How to organize Modules in clean way
Package by feature
Package by layer
31
Domain layer
Use Cases
Entities
Interactors
Data Sources
ViewModels
Fragm
ents
A
c
t
i
v
i
t
i
e
s
Repository implementations
32
sealed class Result<out T : Any> {
data class Success<out T : Any>(val data: T) : Result<T>()
data class Failure(val exception: Exception) : Result<Nothing>()
}
Domain layer in Android
Entities
data class User( val userId: String,
val displayName: String)
33
abstract class UseCase<out Type, in Params> where Type : Any {
abstract suspend operator fun invoke(params: Params): Result<Type>
}
Domain layer in Android
Use Cases
class LoginUseCase(private val loginRepository
: LoginRepository) :
UseCase<User, LoginUseCase.Params>() {
override suspend operator fun invoke(params: Params): Result<User> =
loginRepository
.login(password = params
.password, userName = params
.userName)
data class Params(val userName: String, val password: String)
}
34
interface LoginRepository {
suspend fun login(userName: String,
password: String): Result<User>
}
Domain layer in Android
Repositories
35
data class LoginInteractors(
val loginUseCase: LoginUseCase,
val validateUserNameUseCase: ValidateUserNameUseCase,
val validatePasswordUseCase: ValidatePasswordUseCase
)
Domain layer in Android
Interactors
36
Data layer
Use Cases
Entities
Interactors
Data Sources
ViewModels
Fragm
ents
A
c
t
i
v
i
t
i
e
s
Repository implementations
M
a
p
p
e
r
s
37
interface UserMapper {
fun mapToUser(loggedInUser: LoggedInUser): User
}
Data layer in Android
Data layer in Android
Mappers
class UserMapperImpl() : UserMapper {
override fun mapToUser(loggedInUser: LoggedInUser): User {
return User(
userId = loggedInUser.userId,
displayName = loggedInUser.displayName
)
}
}
38
class LoginDataSource {
fun login(username: String, password: String): LoggedInUser {
return LoggedInUser(UUID.randomUUID(), "Jane Doe")
}
}
Data layer in Android
Data Sources
39
class LoginRepositoryImpl
(
private val dataSource: LoginDataSource
,
private val userMapper: UserMapper
) : LoginRepository {
override suspend fun login(userName: String, password: String): Result<User> {
return try {
val loggedInUser = dataSource.login(userName, password)
val user = userMapper.mapToUser(loggedInUser)
Result.Success(user)
} catch (e: Throwable) {
Result.Failure(IOException("Error logging in"
, e))
}
}
...
}
Data layer in Android
Repository implementations
40
Presentation layer
Use Cases
Entities
Interactors
Data Sources
ViewModels
Fragm
ents
A
c
t
i
v
i
t
i
e
s
Repository implementations
M
a
p
p
e
r
s
41
data class LoginViewState(
val loginFormState: LoginFormState? = null,
val loginResult: LoginResult? = null
)
Presentation layer in Android
ViewState Entities
42
class LoginViewModel(
private val loginInteractors: LoginInteractors
) : ViewModel() {
private val viewState = MutableStateFlow(LoginViewState())
fun login(username: String, password: String) {
viewModelScope.launch {
val result = loginInteractors.loginUseCase.invoke(
LoginUseCase.Params(username,password)
)
val loginResult = when (result) {
is Result.Success ->
LoginResult(success = LoggedInUserView(displayName = result.data.displayName))
else -> LoginResult(error = result.error)
}
viewState.value = viewState.value.copy(loginResult = loginResult)
}
}
}
Presentation layer in Android
ViewModel
43
class LoginFragment : Fragment() {
...
override fun onViewCreated(view: View, savedInstanceState
: Bundle?) {
super.onViewCreated(view, savedInstanceState
)
...
loginViewModel
.collectLatest(lifecycleScope,::collectViewState
)
}
private fun collectViewState
(viewState: LoginViewState
) {
with(viewState.loginResult){
error
?.let{showLoginFailed
(it)}
success?.let{updateUiWithUser
(it)}
}
}
}
Presentation layer in Android
Fragment
44
Data flow between layers
Data layer
LoginRepositoryImpl LoginDataSource
UserMapper
Presentation layer
LoginViewModel
LoginFragment
Domain layer
LoginInteractors LoginUseCase
Result
LoginRepository
Many ways to implement
Boilerplate code
Not suitable for small projects
Learning curve
Pros and Cons Clean Architecture
Pros and Cons Clean Architecture
Testable
Independent of the data sources
Independent of libraries & frameworks
Independent of the UI
Pros Cons
46
What is Clean Architecture
Layers of a Clean Architecture
What are SOLID design principles
What are RRP,CCP and CRP component principles
The tension Diagram for component cohesion
Clean Architecture layers in Android
How to organize modules in Android
Data flow between layers in Android
Summary
Summary
47
Any questions ?
48
● https://www.blog.cleancoder.com
● Clean Architecture book by Robert Cecil Martin
● Working Effectively with Legacy Code Book by Michael C. Feathers
References
Matso Abgaryan
@AbgaryanMr
linkedin.com/in/matsoab

More Related Content

What's hot

Existentialism is a Humanism - Sartre
Existentialism is a Humanism - SartreExistentialism is a Humanism - Sartre
Existentialism is a Humanism - Sartre
Avril Gutierrez
 
Epistemologia isaac newton
Epistemologia isaac newtonEpistemologia isaac newton
Epistemologia isaac newton
Fernando Huayta
 
Plato’s allegory of the cave
Plato’s allegory of the cavePlato’s allegory of the cave
Plato’s allegory of the caveJennylove87
 
The Beginning of Philosophy
The Beginning of PhilosophyThe Beginning of Philosophy
The Beginning of Philosophy
JorjieNepangue2
 
Fallacy of Particular Premises
Fallacy of Particular PremisesFallacy of Particular Premises
Fallacy of Particular Premises
Mary Grace Mancao
 

What's hot (7)

Existentialism is a Humanism - Sartre
Existentialism is a Humanism - SartreExistentialism is a Humanism - Sartre
Existentialism is a Humanism - Sartre
 
Empiricist Epistemology
Empiricist EpistemologyEmpiricist Epistemology
Empiricist Epistemology
 
Epistemologia isaac newton
Epistemologia isaac newtonEpistemologia isaac newton
Epistemologia isaac newton
 
Plato’s allegory of the cave
Plato’s allegory of the cavePlato’s allegory of the cave
Plato’s allegory of the cave
 
The Beginning of Philosophy
The Beginning of PhilosophyThe Beginning of Philosophy
The Beginning of Philosophy
 
Fallacy of Particular Premises
Fallacy of Particular PremisesFallacy of Particular Premises
Fallacy of Particular Premises
 
Documento de mate
Documento de mateDocumento de mate
Documento de mate
 

Similar to Adapting clean architecture in android apps

Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
RatnaJava
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
Seok-joon Yun
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
Naveen Sagayaselvaraj
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need it
Alexey Fyodorov
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
VishalKumarJha10
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Palak Sanghani
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
Hitesh-Java
 
Object Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;sObject Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;s
vivek p s
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
WebStackAcademy
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with FindbugsCarol McDonald
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
Shivam Singh
 
AngularJS in large applications - AE NV
AngularJS in large applications - AE NVAngularJS in large applications - AE NV
AngularJS in large applications - AE NV
AE - architects for business and ict
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
Adam Stephensen
 

Similar to Adapting clean architecture in android apps (20)

Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need it
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Litwin linq
Litwin linqLitwin linq
Litwin linq
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
 
Object Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;sObject Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;s
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
 
JavaProgrammingManual
JavaProgrammingManualJavaProgrammingManual
JavaProgrammingManual
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
AngularJS in large applications - AE NV
AngularJS in large applications - AE NVAngularJS in large applications - AE NV
AngularJS in large applications - AE NV
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 

Recently uploaded

一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
zwunae
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
dxobcob
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
drwaing
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 

Recently uploaded (20)

一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 

Adapting clean architecture in android apps

  • 1. 1 Adapting clean architecture in Android apps Matso Abgaryan @AbgaryanMr linkedin.com/in/matsoab
  • 2. 2 Part one: Clean Architecture Part two: Clean Architecture in Android
  • 4. 4 ● Testable ● Independent of the data sources ● Independent of libraries & frameworks ● Independent of the UI Why should one use a Clean Architecture
  • 5. 5 “Clean Architecture separates the application code into layers and these layers define the Separation of Concerns inside the codebase.” Uncle Bob What is clean architecture
  • 6. 6 Characteristics of a Clean Architecture Entities Use Cases Controllers G ateways P r e s e n t e r s DB UI Web External Interfaces Devices ■ Enterprise Business Rules ■ Application Business Rules ■ Interface Adapters ■ Framework & Drivers
  • 7. 7 ● Single Responsibility Principle ● Open-Closed Principle ● Liskov Substitution Principle ● Interface Segregation Principle ● Dependency Inversion Principle What are SOLID design principles
  • 8. 8 ■ A class should have only one reason to change. What is Single-Responsibility principle
  • 9. 9 fun onBind(trip: Trip) { itemView.start_name.text = trip.start itemView.destination_name.text = trip.destination val formattedDate = DateFormat.getDateInstance().format( trip.departureTime, StringBuffer("departure Time : "), FieldPosition(0) ) itemView.departure_time.text = formattedDate } Bad Example
  • 10. 10 fun onBind(trip: Trip) { with(itemView) { start_name.text = trip.start destination_name.text = trip.destination departure_time.text = dateUtil.formatDate(trip.departureTime) } } Good Example
  • 11. 11 ■ Software entities such as classes, functions, modules should be open for extension but not modification. What is Open-closed principle
  • 12. 12 class TimeGreeting(val time :String) { fun greetingFromTimeOfDay(): String = when (time) { "Morning" -> { "Good Morning, sir." } "Afternoon" -> { "Good Afternoon, sir." } "Evening" -> { "Good Evening, sir." } else -> { "Good Night, sir." } } } Bad Example
  • 13. 13 Good Example interface Time { fun greet(): String } class Morning : Time { override fun greet(): String { return "Good morning, sir." } } class Afternoon : Time { override fun greet(): String { return "Good afternoon, sir." } } class Evening : Time { override fun greet(): String { return "Good evening, sir." } } class Night : Time { override fun greet(): String { return "Good night, sir." } } class TimeGreeting(val time: Time) { fun greetingFromTimeOfDay(): String = time.greet() }
  • 14. 14 ■ Child classes should never break the parent class’ type definitions. What is Liskov Substitution principle
  • 15. 15 open class Rectangle { private var width: Int = 0 private var height: Int = 0 open fun setWidth(newWidth: Int) { width = newWidth } open fun setHeight(newHeight: Int) { height = newHeight } fun getArea(): Int = width * height } Bad Example val rectangle : Rectangle = Square() rectangle.setWidth(3) rectangle.setHeight(5) rectangle.getArea() class Square : Rectangle() { override fun setWidth(newWidth: Int) { super.setWidth(newWidth) super.setHeight(newWidth) } override fun setHeight(newHeight: Int) { super.setWidth(newHeight) super.setHeight(newHeight) } }
  • 16. 16 interface Shape { fun getArea(): Int } class Square: Shape { private var diameter: Int = 0 fun setDiameter(diameter: Int) { this.diameter = diameter } override fun getArea(): Int { return diameter * diameter } } class Rectangle: Shape { private var width: Int = 0 private var height: Int = 0 fun setWidth(width: Int) { this.width = width } fun setHeight(height: Int) { this.height = height } override fun getArea(): Int { return width * height } } Good Example
  • 17. 17 ■ The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use. What is Interface segregation principle
  • 18. 18 interface OnClickListener { fun onClick() fun onLongClick() } class Button: OnClickListener { override fun onClick() {} override fun onLongCLick() { //does not support Long clicks } } class LongClickButton: OnClickListener{ override fun onClick() { // does not support short clicks } override fun onLongCLick() {} } Bad Example
  • 19. 19 interface OnClickListener { fun onClick() } interface OnLongClickListener { fun onLongCLick() } class Button: OnClickListener { override fun onClick() {} } class LongClickButton: OnLongClickListener { override fun onLongCLick() {} } Good Example
  • 20. 20 ■ High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend upon details. Details should depend upon abstractions. What is Dependency Inversion principle
  • 21. 21 class WhatsUpMessage { var whatsUpText:String = "" } class MessageBoard { var message: WhatsUpMessage? = null fun printMessage() { println(message?.whatsUpText) } } Bad Example
  • 22. 22 interface IMessage { fun printMessage() } class WhatsUpMessage:IMessage{ override fun printMessage() {} } class FaceBookMessage:IMessage{ override fun printMessage() {} } class MessageBoard { var message: IMessage? = null fun printMessage(){ message?.printMessage() } } Good Example
  • 23. 23 ● RRP: The Reuse/Release Equivalence Principle ● CCP: The Common Closure Principle ● CRP: The Common Reuse Principle What are RRP, CCP, and CRP component principles
  • 24. 24 ❏ The granularity of reuse is the granularity of release What is The Reuse/Release Equivalence Principle
  • 25. 25 ❏ Gather into components those classes that change for the same reasons and at the same times (related to SRP) What is The Common Closure Principle
  • 26. 26 ❏ Don't force users of a component to depend on things they don't need (related to ISP) What is The Common Reuse Principle
  • 27. 27 The Tension Diagram For Component Cohesion REP CCP CRP To many unneeded releases To many components change Hard to reuse
  • 28. 28 Part one: Clean Architecture Part two: Clean Architecture in Android
  • 29. 29 What are Clean Architecture layers in Android ■ Domain layer ■ Data layer ■ Presentation layer Use Cases Entities Data Sources ViewModels Fragm ents A c t i v i t i e s Repository implementations
  • 30. 30 How to organize Modules in clean way Package by feature Package by layer
  • 31. 31 Domain layer Use Cases Entities Interactors Data Sources ViewModels Fragm ents A c t i v i t i e s Repository implementations
  • 32. 32 sealed class Result<out T : Any> { data class Success<out T : Any>(val data: T) : Result<T>() data class Failure(val exception: Exception) : Result<Nothing>() } Domain layer in Android Entities data class User( val userId: String, val displayName: String)
  • 33. 33 abstract class UseCase<out Type, in Params> where Type : Any { abstract suspend operator fun invoke(params: Params): Result<Type> } Domain layer in Android Use Cases class LoginUseCase(private val loginRepository : LoginRepository) : UseCase<User, LoginUseCase.Params>() { override suspend operator fun invoke(params: Params): Result<User> = loginRepository .login(password = params .password, userName = params .userName) data class Params(val userName: String, val password: String) }
  • 34. 34 interface LoginRepository { suspend fun login(userName: String, password: String): Result<User> } Domain layer in Android Repositories
  • 35. 35 data class LoginInteractors( val loginUseCase: LoginUseCase, val validateUserNameUseCase: ValidateUserNameUseCase, val validatePasswordUseCase: ValidatePasswordUseCase ) Domain layer in Android Interactors
  • 36. 36 Data layer Use Cases Entities Interactors Data Sources ViewModels Fragm ents A c t i v i t i e s Repository implementations M a p p e r s
  • 37. 37 interface UserMapper { fun mapToUser(loggedInUser: LoggedInUser): User } Data layer in Android Data layer in Android Mappers class UserMapperImpl() : UserMapper { override fun mapToUser(loggedInUser: LoggedInUser): User { return User( userId = loggedInUser.userId, displayName = loggedInUser.displayName ) } }
  • 38. 38 class LoginDataSource { fun login(username: String, password: String): LoggedInUser { return LoggedInUser(UUID.randomUUID(), "Jane Doe") } } Data layer in Android Data Sources
  • 39. 39 class LoginRepositoryImpl ( private val dataSource: LoginDataSource , private val userMapper: UserMapper ) : LoginRepository { override suspend fun login(userName: String, password: String): Result<User> { return try { val loggedInUser = dataSource.login(userName, password) val user = userMapper.mapToUser(loggedInUser) Result.Success(user) } catch (e: Throwable) { Result.Failure(IOException("Error logging in" , e)) } } ... } Data layer in Android Repository implementations
  • 40. 40 Presentation layer Use Cases Entities Interactors Data Sources ViewModels Fragm ents A c t i v i t i e s Repository implementations M a p p e r s
  • 41. 41 data class LoginViewState( val loginFormState: LoginFormState? = null, val loginResult: LoginResult? = null ) Presentation layer in Android ViewState Entities
  • 42. 42 class LoginViewModel( private val loginInteractors: LoginInteractors ) : ViewModel() { private val viewState = MutableStateFlow(LoginViewState()) fun login(username: String, password: String) { viewModelScope.launch { val result = loginInteractors.loginUseCase.invoke( LoginUseCase.Params(username,password) ) val loginResult = when (result) { is Result.Success -> LoginResult(success = LoggedInUserView(displayName = result.data.displayName)) else -> LoginResult(error = result.error) } viewState.value = viewState.value.copy(loginResult = loginResult) } } } Presentation layer in Android ViewModel
  • 43. 43 class LoginFragment : Fragment() { ... override fun onViewCreated(view: View, savedInstanceState : Bundle?) { super.onViewCreated(view, savedInstanceState ) ... loginViewModel .collectLatest(lifecycleScope,::collectViewState ) } private fun collectViewState (viewState: LoginViewState ) { with(viewState.loginResult){ error ?.let{showLoginFailed (it)} success?.let{updateUiWithUser (it)} } } } Presentation layer in Android Fragment
  • 44. 44 Data flow between layers Data layer LoginRepositoryImpl LoginDataSource UserMapper Presentation layer LoginViewModel LoginFragment Domain layer LoginInteractors LoginUseCase Result LoginRepository
  • 45. Many ways to implement Boilerplate code Not suitable for small projects Learning curve Pros and Cons Clean Architecture Pros and Cons Clean Architecture Testable Independent of the data sources Independent of libraries & frameworks Independent of the UI Pros Cons
  • 46. 46 What is Clean Architecture Layers of a Clean Architecture What are SOLID design principles What are RRP,CCP and CRP component principles The tension Diagram for component cohesion Clean Architecture layers in Android How to organize modules in Android Data flow between layers in Android Summary Summary
  • 48. 48 ● https://www.blog.cleancoder.com ● Clean Architecture book by Robert Cecil Martin ● Working Effectively with Legacy Code Book by Michael C. Feathers References Matso Abgaryan @AbgaryanMr linkedin.com/in/matsoab