Are you looking for a better architecture that fits your complex Android apps? Have you heard about Clean Architecture but don’t know if it will fit your Android app?
In my talk, you will learn how to Adapting clean architecture in Android apps including:
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 principles?
Clean Architecture layers in Android
How to organize modules in Android?
Data flow between layers in Android?
Isaac Newton (Woolsthorpe, Lincolnshire; 25 de diciembre de 1642jul./ 4 de enero de 1643greg.-Kensington, Londres; 20 de marzojul./ 31 de marzo de 1727greg.) fue un físico, filósofo, teólogo, inventor, alquimista y matemático inglés. Es autor de los Philosophiæ naturalis principia mathematica, más conocidos como los Principia, donde describe la ley de la gravitación universal y estableció las bases de la mecánica clásica mediante las leyes que llevan su nombre. Entre sus otros descubrimientos científicos destacan los trabajos sobre la naturaleza de la luz y la óptica (que se presentan principalmente en su obra Opticks) y el desarrollo del cálculo matemático.
Newton comparte con Gottfried Leibniz el crédito por el desarrollo del cálculo integral y diferencial, que utilizó para formular sus leyes de la física. También contribuyó en otras áreas de la matemática, desarrollando el teorema del binomio y las fórmulas de Newton-Cotes.
Entre sus hallazgos científicos se encuentran el descubrimiento de que el espectro de color que se observa cuando la luz blanca pasa por un prisma es inherente a esa luz, en lugar de provenir del prisma (como había sido postulado por Roger Bacon en el siglo XIII); su argumentación sobre la posibilidad de que la luz estuviera compuesta por partículas; su desarrollo de una ley de convección térmica, que describe la tasa de enfriamiento de los objetos expuestos al aire; sus estudios sobre la velocidad del sonido en el aire; y su propuesta de una teoría sobre el origen de las estrellas. Fue también un pionero de la mecánica de fluidos, estableciendo una ley sobre la viscosidad.
Java 8 is coming soon. In this presentation I have outlined the major Java 8 features. You get information about interface improvements, functional interfaces, method references, lambdas, java.util.function, java.util.stream
In this session you will learn:
Deep dive into coding OOP with Java… with practical examples.
How to create a class
How to create objects
How to create instance variables
How to create class variables
Constructors
For more information: https://www.mindsmapped.com/courses/software-development/become-a-java-developer-hands-on-training/
In this chapter we will understand how to define custom classes and their elements. We will learn to declare fields, constructors and properties for the classes. We will revise what a method is and we will broaden our knowledge about access modifiers and methods.
In this core java training session, you will learn OOP with Java Contd. Topics covered in this session are:
• Review of last class concepts
• Types of Inheritance and a look at Aggregation
• Polymorphism
• Method overloading
• Method overriding
For more information about this course visit on this link: https://www.mindsmapped.com/courses/software-development/learn-java-fundamentals-hands-on-training-on-core-java-concepts/
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...WebStackAcademy
A collection is essentially a group of objects of a similar type. The collection framework in Java (commonly known as the Java Collection Framework) is comprised of a collection of types that enable you to implement complex data structures seamlessly. The collection interfaces in the Java Collections Framework include: Collection, List, Set, Map, and so on. And, the major classes in this framework are: ArrayList, LinkedList, HashSet, HashMap, and the like. The Java Collections Framework is contained inside the java.util.Collection package.
To iterate over a collection, we need an iterator. The java.util.Iterator package contains methods such as hasNext(), next(), and remove(). The hasNext() method returns true if there are more elements in the collection. The next() method returns the next element in the collection. The remove() method removes the last element from a collection.
Generics is a feature of the Java Language that promotes type safety, code manageability and efficiency and, most importantly, much cleaner and reduced code. You can use generics to create type safe collections with no boxing and un-boxing overhead; this is also known as parametric polymorphism.
Isaac Newton (Woolsthorpe, Lincolnshire; 25 de diciembre de 1642jul./ 4 de enero de 1643greg.-Kensington, Londres; 20 de marzojul./ 31 de marzo de 1727greg.) fue un físico, filósofo, teólogo, inventor, alquimista y matemático inglés. Es autor de los Philosophiæ naturalis principia mathematica, más conocidos como los Principia, donde describe la ley de la gravitación universal y estableció las bases de la mecánica clásica mediante las leyes que llevan su nombre. Entre sus otros descubrimientos científicos destacan los trabajos sobre la naturaleza de la luz y la óptica (que se presentan principalmente en su obra Opticks) y el desarrollo del cálculo matemático.
Newton comparte con Gottfried Leibniz el crédito por el desarrollo del cálculo integral y diferencial, que utilizó para formular sus leyes de la física. También contribuyó en otras áreas de la matemática, desarrollando el teorema del binomio y las fórmulas de Newton-Cotes.
Entre sus hallazgos científicos se encuentran el descubrimiento de que el espectro de color que se observa cuando la luz blanca pasa por un prisma es inherente a esa luz, en lugar de provenir del prisma (como había sido postulado por Roger Bacon en el siglo XIII); su argumentación sobre la posibilidad de que la luz estuviera compuesta por partículas; su desarrollo de una ley de convección térmica, que describe la tasa de enfriamiento de los objetos expuestos al aire; sus estudios sobre la velocidad del sonido en el aire; y su propuesta de una teoría sobre el origen de las estrellas. Fue también un pionero de la mecánica de fluidos, estableciendo una ley sobre la viscosidad.
Java 8 is coming soon. In this presentation I have outlined the major Java 8 features. You get information about interface improvements, functional interfaces, method references, lambdas, java.util.function, java.util.stream
In this session you will learn:
Deep dive into coding OOP with Java… with practical examples.
How to create a class
How to create objects
How to create instance variables
How to create class variables
Constructors
For more information: https://www.mindsmapped.com/courses/software-development/become-a-java-developer-hands-on-training/
In this chapter we will understand how to define custom classes and their elements. We will learn to declare fields, constructors and properties for the classes. We will revise what a method is and we will broaden our knowledge about access modifiers and methods.
In this core java training session, you will learn OOP with Java Contd. Topics covered in this session are:
• Review of last class concepts
• Types of Inheritance and a look at Aggregation
• Polymorphism
• Method overloading
• Method overriding
For more information about this course visit on this link: https://www.mindsmapped.com/courses/software-development/learn-java-fundamentals-hands-on-training-on-core-java-concepts/
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...WebStackAcademy
A collection is essentially a group of objects of a similar type. The collection framework in Java (commonly known as the Java Collection Framework) is comprised of a collection of types that enable you to implement complex data structures seamlessly. The collection interfaces in the Java Collections Framework include: Collection, List, Set, Map, and so on. And, the major classes in this framework are: ArrayList, LinkedList, HashSet, HashMap, and the like. The Java Collections Framework is contained inside the java.util.Collection package.
To iterate over a collection, we need an iterator. The java.util.Iterator package contains methods such as hasNext(), next(), and remove(). The hasNext() method returns true if there are more elements in the collection. The next() method returns the next element in the collection. The remove() method removes the last element from a collection.
Generics is a feature of the Java Language that promotes type safety, code manageability and efficiency and, most importantly, much cleaner and reduced code. You can use generics to create type safe collections with no boxing and un-boxing overhead; this is also known as parametric polymorphism.
This presentation was featured on the third AngularJS Meetup in Belgium and presented by Glenn Dejaeger, Thomas Anciaux and Pieter Herroelen, who have been working on a large AngularJS application for almost a year now.
This presentation features the many challenges they have encountered and also ways to solve them, including:
- structuring a large AngularJS application (and building it with grunt)
- writing reusable components
- using AngularJS with a hypermedia API
Enjoy!
AE nv
Hierarchical Digital Twin of a Naval Power SystemKerry Sado
A hierarchical digital twin of a Naval DC power system has been developed and experimentally verified. Similar to other state-of-the-art digital twins, this technology creates a digital replica of the physical system executed in real-time or faster, which can modify hardware controls. However, its advantage stems from distributing computational efforts by utilizing a hierarchical structure composed of lower-level digital twin blocks and a higher-level system digital twin. Each digital twin block is associated with a physical subsystem of the hardware and communicates with a singular system digital twin, which creates a system-level response. By extracting information from each level of the hierarchy, power system controls of the hardware were reconfigured autonomously. This hierarchical digital twin development offers several advantages over other digital twins, particularly in the field of naval power systems. The hierarchical structure allows for greater computational efficiency and scalability while the ability to autonomously reconfigure hardware controls offers increased flexibility and responsiveness. The hierarchical decomposition and models utilized were well aligned with the physical twin, as indicated by the maximum deviations between the developed digital twin hierarchy and the hardware.
HEAP SORT ILLUSTRATED WITH HEAPIFY, BUILD HEAP FOR DYNAMIC ARRAYS.
Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to the selection sort where we first find the minimum element and place the minimum element at the beginning. Repeat the same process for the remaining elements.
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdffxintegritypublishin
Advancements in technology unveil a myriad of electrical and electronic breakthroughs geared towards efficiently harnessing limited resources to meet human energy demands. The optimization of hybrid solar PV panels and pumped hydro energy supply systems plays a pivotal role in utilizing natural resources effectively. This initiative not only benefits humanity but also fosters environmental sustainability. The study investigated the design optimization of these hybrid systems, focusing on understanding solar radiation patterns, identifying geographical influences on solar radiation, formulating a mathematical model for system optimization, and determining the optimal configuration of PV panels and pumped hydro storage. Through a comparative analysis approach and eight weeks of data collection, the study addressed key research questions related to solar radiation patterns and optimal system design. The findings highlighted regions with heightened solar radiation levels, showcasing substantial potential for power generation and emphasizing the system's efficiency. Optimizing system design significantly boosted power generation, promoted renewable energy utilization, and enhanced energy storage capacity. The study underscored the benefits of optimizing hybrid solar PV panels and pumped hydro energy supply systems for sustainable energy usage. Optimizing the design of solar PV panels and pumped hydro energy supply systems as examined across diverse climatic conditions in a developing country, not only enhances power generation but also improves the integration of renewable energy sources and boosts energy storage capacities, particularly beneficial for less economically prosperous regions. Additionally, the study provides valuable insights for advancing energy research in economically viable areas. Recommendations included conducting site-specific assessments, utilizing advanced modeling tools, implementing regular maintenance protocols, and enhancing communication among system components.
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...ssuser7dcef0
Power plants release a large amount of water vapor into the
atmosphere through the stack. The flue gas can be a potential
source for obtaining much needed cooling water for a power
plant. If a power plant could recover and reuse a portion of this
moisture, it could reduce its total cooling water intake
requirement. One of the most practical way to recover water
from flue gas is to use a condensing heat exchanger. The power
plant could also recover latent heat due to condensation as well
as sensible heat due to lowering the flue gas exit temperature.
Additionally, harmful acids released from the stack can be
reduced in a condensing heat exchanger by acid condensation. reduced in a condensing heat exchanger by acid condensation.
Condensation of vapors in flue gas is a complicated
phenomenon since heat and mass transfer of water vapor and
various acids simultaneously occur in the presence of noncondensable
gases such as nitrogen and oxygen. Design of a
condenser depends on the knowledge and understanding of the
heat and mass transfer processes. A computer program for
numerical simulations of water (H2O) and sulfuric acid (H2SO4)
condensation in a flue gas condensing heat exchanger was
developed using MATLAB. Governing equations based on
mass and energy balances for the system were derived to
predict variables such as flue gas exit temperature, cooling
water outlet temperature, mole fraction and condensation rates
of water and sulfuric acid vapors. The equations were solved
using an iterative solution technique with calculations of heat
and mass transfer coefficients and physical properties.
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
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
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
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)
}
35. 35
data class LoginInteractors(
val loginUseCase: LoginUseCase,
val validateUserNameUseCase: ValidateUserNameUseCase,
val validatePasswordUseCase: ValidatePasswordUseCase
)
Domain layer in Android
Interactors
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
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