0% found this document useful (0 votes)
5 views

11 CleanArchitecture

Uploaded by

chdwosjdbdhusis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

11 CleanArchitecture

Uploaded by

chdwosjdbdhusis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

CLEAN ARCHITECTURE

CSC207 SOFTWARE DESIGN

1
Course Overview

Tools (Weeks 1-4)


• Java ▪ Last week we introduced the
• Version Control
SOLID principles and learned
• Software Tools
about Exceptions in Java.
Design (Weeks 5-8)
• Clean Architecture ▪ This week, we will introduce:
• SOLID – Clean Architecture,
• Design Patterns
– Use Cases, and
Professional Topics (Weeks 9-12)
– Sequence Diagrams.
• Ethics
• Internships
• GenAI
Questions to be answered this week...

▪ What is a use case?

▪ What is Clean Architecture (CA)?

▪ What is the CA dependency rule?

▪ What is a sequence diagram?


LEARNING OUTCOMES
• Become more familiar with terminology related to architecture
and design

• Understand clean architecture and its dependency rule

• Understand how sequence diagrams can help us convey flow of


execution in our program.

4
ARCHITECTURE
(Brief Summary of Chapter 15 from Clean Architecture textbook)
Design of the system
• Dividing it into logical pieces and specifying how those pieces communicate
with each other.
• Input and output between layers.
“Goal is to facilitate the development, deployment, operation, and
maintenance of the software system”
• “The strategy behind this facilitation is to leave as many options open as
possible, for as long as possible.”
Good architecture strives to maximize programmer productivity!

5
POLICY AND LEVEL
Brief Summary of Chapter 19 from Clean Architecture textbook

• “A computer program is a detailed description of the policy by


which inputs are transformed into outputs.”
• Software design seeks to separate policies and group them as
appropriate. (Ideally form a directed acyclic dependency graph
between components)
• A policy has an associated level. (e.g. “high level policy”)

6
POLICY AND LEVEL
• Level: “the distance from the inputs and outputs”

• higher level policies are farther from the inputs and


outputs.

• lowest level are those managing inputs and outputs.

7
USE CASES FOR A PROGRAM
Imagine you were asked to write a Bold words are use cases: what will
program that allows users to the user want to do?
• register a new user account (with 1. What data needs to be
a username and password) represented?
• log in to a user account 2. What data structure might you use
while the program is running?
• log out of a user account
3. What should happen if the user
• They’re planning on having a few quits and restarts the program?
different kinds of accounts, but we’ll
start with just one for now.

8
USE CASE: USER REGISTERS NEW ACCOUNT

9
USE CASE: USER REGISTERS NEW ACCOUNT
• The user chooses a username
• The user chooses a password and enters it twice (to help them
remember)
• If the username already exists, the system alerts the user
• If the two passwords don't match, the system alerts the user
• If the username doesn’t exist in the system and the passwords
match, then the system creates the user but does not log them in

10
USE CASE: USER LOGS IN

11
USE CASE: USER LOGS IN
• The user enters a username and password
• If the username exists in the system and the passwords match, then the
system shows that the user is logged in

• If there is no such username, the system alerts the user

• If the password doesn’t match the one in the system, the system alerts
the user

12
USE CASE: USER LOGS OUT
• The system logs the user out and informs the user

13
USE CASE: WHEN LOGGED OUT, CHOOSE USE CASE
• The user chooses between the user registers a new account use
case and the user logs in use case

14
BURNING QUESTIONS
• What is the user interface? • How can you design your program so that
• A webpage? it’s easy to move to a new UI?
• A Java application on your computer? • How can you design your program so that
• A Python command-line program? it’s easy to save data to a different kind of
• A mobile app? storage?

• How to do data persistence? • How can you design your program so that
• A text file? json? as much code as possible stays the same
when you do these things?
• A database?
• Google Drive/OneDrive/etc.?

15
DESIGN CONUNDRUMS
• How can we design the use cases so that they do not directly depend on the UI
and persistence choices?
• Then we can test all the use cases thoroughly without dealing with
input/output!
• What are the use case APIs?
• What is the interface to each use case?
• What public methods do we want to provide to call the use cases from the UI?
• What persistence methods will we need in any storage?
• Saving
• Finding a user by username
• Etc.
16
CLEAN ARCHITECTURE

17
BUSINESS RULES
(Brief Summary of Chapter 20 from Clean Architecture textbook)

• Entity: “An object within our computer system that embodies a


small set of Critical Business Rules operating on Critical Business
Data.”
• Use Case: “A description of the way that an automated system is
used. It specifies the input to be provided by the user, the output
to be returned to the user, and the processing steps involved in
producing that output. A use case describes application-specific
business rules as opposed to the Critical Business Rules within
the Entities.”

18
ENTITIES
• Objects that represent critical business data (variables) and critical
business rules (methods).
• In Clean Architecture, entities are the highest-level policies (core
of the program).
• Some examples
• a Loan in a bank
• a Player in a game
• a set of high scores
• an item in an inventory system
• a part in an assembly line
USE CASE
• A description of the way that an automated system affects Entities
• Use cases manipulate Entities
• Specifies the input to be provided by the user, the output to be
returned to the user, and the processing steps involved in
producing that output.

Use cases know nothing


about the details of the
user interface or the data
storage mechanism — just
that they exist!
CLEAN ARCHITECTURE
User External
Database Web Frameworks & Drivers
Interface Interface

Controllers Gateways Presenters Interface Adapters

Use Cases Application Business Rules

Entities Enterprise Business Rules

21
CLEAN ARCHITECTURE
• Often visualize the layers as
concentric circles.
• Reminds us that Entities are at
the core
• Input and output are both in
outer layers

22
CLEAN ARCHITECTURE – DEPENDENCY RULE
• All dependencies must point inward.
• Dependence within the same layer is allowed (but try to minimize coupling)
• On occasion you might find it unnecessary to explicitly have all four layers, but
you’ll almost certainly want at least three layers and sometimes even more than
four.
• The name of something (functions, classes, variables) declared in an outer
layer must not be mentioned by the code in an inner layer.
• How do we go from the inside to the outside then?

• Dependency Inversion!
• An inner layer can depend on an interface, which the outer layer implements.

23
CLEAN ARCHITECTURE – DEPENDENCY RULE
User External
Database Web Frameworks & Drivers
Interface Interface

Controllers Gateways Presenters Interface Adapters

Use Cases Application Business Rules

Entities Enterprise Business Rules

24
IDENTIFYING VIOLATIONS OF CLEAN
ARCHITECTURE

• Look at the imports at the top of each source file in your


project.
• For example, if you see that you are importing a
Controller class from inside an Entity class, that is a
violation of clean architecture! Likewise, if you see a
Controller referencing an Entity that is also likely a
violation.
• You can also achieve this visually by having IntelliJ
generate a dependency graph for your project.

25
BENEFITS OF CLEAN ARCHITECTURE
• All the “details” (frameworks, UI, Database, etc.) live in
the outermost layer.
• The business rules can be easily tested without worrying
about those details in the outer layers!
• Any changes in the outer layers don’t affect the business
rules!

26
EXAMPLE OF A PROGRAM WITH CLEAN ARCHITECTURE
Interface Adapters < DS > Enterprise Business Rules
Input Data

<I >
Controller Input Boundary
Use Case
Entities
Interactor
<I >
Presenter Output Boundary

< DS >
Output Data <I >
< DS > Data Access
View Model Interface

Application Business Rules

View Frameworks & Drivers Data Access Database

28
HOW THE ENGINE WORKS: THE VIEW
Interface Adapters < DS > Enterprise Business Rules
Input Data

<I >
Controller Input Boundary Use Case
Entities
Interactor
<I >
Presenter Output Boundary
The user interface code for a feature.
Buttons, text areas, scrollbars, panels,
windows, etc. < DS >
Output Data <I >
DS >
<Responsibility: display information and
Data Access
View Model
react to user interaction. Will ask a Interface
Controller to do something the user wants. Application Business Rules

View Frameworks & Drivers Data Access Database

29
EXAMPLE OF A PROGRAM WITH CLEAN ARCHITECTURE
Interface Adapters < DS > Enterprise Business Rules
Input Data

<I >
Controller Input Boundary
Use Case
Entities
Interactor
<I >
Presenter Responsibility:
Output Boundarythe raw user data
convert
to something useful (for example, a string
to a Date object, or a float to a currency
value), create <anDS
Input
> Data object
Output
containing Dataand call a method to
that info, <I >
< DS >start a Use Case, passing in the Input Data Access
View Model Data. Interface

Application Business Rules

View Frameworks & Drivers Data Access Database

30
EXAMPLE OF A PROGRAM WITH CLEAN ARCHITECTURE
Interface Adapters < DS > Enterprise Business Rules
Responsibility: take the Input Data Input Data
and execute
the use case, looking up information in the Data
Access object when necessary and manipulating<I >
Controller
Entities. This Input
might create new data thatBoundary
needs Use Case
Entities
to be saved in the Data Access layer. Interactor
<I >
create an OutputOutput
Presenter
When complete, Data object —
Boundary
the use case result — and pass it to the
Presenter.
< DS >
Output Data <I >
< DS > Data Access
View Model Interface

Application Business Rules

View Frameworks & Drivers Data Access Database

31
EXAMPLE OF A PROGRAM WITH CLEAN ARCHITECTURE
Interface Adapters < DS > Enterprise Business Rules
Input Data
Responsibility: Each entity represents something
from the problem domain, < Ilike
> a bank account.
There is very little
Controller Inputlogic here other than fancy data
Boundary
Use Case
structures like sets, lists, trees, and dictionaries. Entities
Interactor
<I >
Presenter Output Boundary

< DS >
Output Data <I >
< DS > Data Access
View Model Interface

Application Business Rules

View Frameworks & Drivers Data Access Database

32
EXAMPLE OF A PROGRAM WITH CLEAN ARCHITECTURE
Interface Adapters < DS > Enterprise Business Rules
Input Data

<I >
Controller Input Boundary
Use Case
Entities
Interactor
<I >
Presenter Output Boundary

< DS >
Output Data <I >
< DS > Data Access
View Model Interface

Application Business Rules


Responsibility: manage access to persistent
data (reading from and writing to files or
View Frameworks & Drivers Data Access Database
databases), creating temporary Entities that the
Use Case uses to do its work.
33
EXAMPLE OF A PROGRAM WITH CLEAN ARCHITECTURE
Interface Adapters < DS > Enterprise Business Rules
Input Data
Responsibility: take the Output Data and turn it
< I >and numbers to be displayed.
into raw strings
Controller Input Boundary
Update the View Model withUse
thisCase
information.
Entities
Interactor
<I >
Presenter Output Boundary

< DS >
Output Data <I >
< DS > Data Access
View Model Interface

Application Business Rules

View Frameworks & Drivers Data Access Database

34
EXAMPLE OF A PROGRAM WITH CLEAN ARCHITECTURE
Interface Adapters < DS > Enterprise Business Rules
Input Data

<I >
Controller Input Boundary
Use Case
Entities
Interactor
<I >
Presenter Output Boundary

< DS >
Output Data <I >
< DS > Data Access
View Model Interface
Responsibility: when the View Model is
updated the View is alerted through a Application Business Rules
callback. The View then displays the new
information to the user, possibly activating
View Frameworks
another View. & Drivers Data Access Database

35
EXAMPLE OF A PROGRAM WITH CLEAN ARCHITECTURE
Interface Adapters < DS > Enterprise Business Rules
Input Data These are Java interfaces that help you plug
everything together and that make this engine
<I > testable (more about this later!)
Controller Input Boundary
Use Case
Entities
Interactor
<I >
Presenter Output Boundary

< DS >
Output Data <I >
< DS > Data Access
View Model Interface

Application Business Rules

View Frameworks & Drivers Data Access Database

36
TERMINOLOGY (OH DEAR ME!)
• Entity: a basic bit of data that we’re storing in our • Output boundary: the public interface that the
program (like a user with a username and Interactor will call when the use case is complete
password). Often called a “model” of the real
world. • Data Access Object (DAO): involves persistence
(a file or database). Often called a Gateway or a
• Factory: an object that knows how to instantiate a Repository. Reads data and creates Entities
class or a collection of interrelated classes.
• Controller: the object that the UI asks to run a
• Use case: something a user wants to do with the use case
program.
• Presenter: the object that tells the UI what to do
• Interactor: the object that responds to a user when a use case finishes
interaction, usually part of a use case (implements
the input boundary) • Model: a model of a concept from the problem
domain. A collection of data representing a
• Input boundary: the public interface for calling concept from the problem domain. Entities are
the use case often called models.

37
DOES CLEAN ARCHITECTURE FOLLOW SOLID?
• Take a few minutes to think about each principle, then check the following
slides for some thoughts. Continue the conversation on piazza!

38
CLEAN ARCHITECTURE FOLLOWS SOLID
• Single Responsibility Principle – Each role divides up the responsibilities for each class.
o Only gateway classes are responsible to other hardware or software that is outside of your
program.
o Only Presenters are responsible to whomever decides which information is displayed to
the user
o Each entity is responsible for storing information about one building block of the program
(example: user class in a program that allows users to login and save their session)
• Open/Closed Principle – Clean Architecture separates layers of code based on how close or
far they are from the details. For example: what does the user see, which hardware/operating
system is running the program, where are we store persistent data, etc.
o It is easy to reuse the backend in an app for a different system (web app, Android, etc)
o It is easy to reuse entities across different apps that follow the same Enterprise Business
Rules.
o It is possible to add new Use Cases without changing much of the orginial code.

39
CLEAN ARCHITECTURE FOLLOWS SOLID
• Liskov Substitution Principle – The various interfaces introduced should help
us write code consistent with this principle, but we still need to ensure our code
consistently uses the interfaces and that they are designed and documented
properly.
• Interface Segregation Principle – Each interface has a specific role and is
associated with one Use Case, so no unnecessary methods are implemented.
• Dependency Inversion Principle – In Clean Architecture, this is closely
related to the Dependency Rule. The principle is applied to remove
dependencies on the low-level details of the program!

40
USER LOGIN EXAMPLE
• Recall the specification for a user login system we talked about
earlier.
• We had started to develop a design for it in terms of use cases.
• You can find a partial implementation at
https://github.com/paulgries/UserLoginCleanArchitecture
• We’ll refer to this code during lecture, but on the final coding
homework you’ll work with a slightly different codebase — the
overall structure will look similar though.

41
AN EXAMPLE: REGISTER A NEW USER
As part of a program, we want to allow a new user to register an
account by specifying their username and password — getting them
to enter their password twice to avoid typos and help them commit it
to memory.

42
USE CASE APIS
A class for each use case
UserRegisterInteractor
• Public API: a method called create (perhaps with the username and
password as parameters, or maybe they’re wrapped up in a data
class)
• Needs to tell the UI to prepare a success view or a failure view
• Needs to know how to make a new user
• Needs to ask the persistence layer whether a username exists
• Needs to tell the persistence layer to save a new user

43
REGISTER NEW USER USE CASE SKETCH
class UserFactory {

public User create(String name, String password) { ... }

class UserRegisterInteractor {

private UserFactory userFactory; # a class to create User objects

private UserPresenter userPresenter; # controls the UI

private UserRegisterGateway userRegisterGateway; # persisting data

public UserRegisterResultModel create(String name, String password: str) {


# On success, this method returns an object with the
# username and creation time, but not the password (why?) }

44
UML
SEQUENCE
DIAGRAMS
CSC 207 SOFTWARE DESIGN
45
EXAMPLE OF A PROGRAM WITH CLEAN ARCHITECTURE
Interface Adapters < DS > Enterprise Business Rules
Input Data

<I >
Controller Input Boundary
Use Case
Entities
Interactor
<I >
Presenter Output Boundary

< DS >
Output Data <I >
< DS > Data Access
View Model Interface

Application Business Rules

View Frameworks & Drivers Data Access Database

47
HOW DATA FLOWS IN THE CLEAN ARCHITECTURE
• In the Clean Architecture, data flows from the user to an action method then
through the Controller to the Use Case Interactor. The Interactor will create,
read, update, and delete any appropriate Entities for that interaction, using DAOs
to create, read, update, and delete the corresponding data in a database or a set
of files.
• When the Interactor is done, the resulting data needs to flow from the Interactor
through the Presenter back to the View.
• Each View may contain several user actions, each of which has 1 action method.
Each action method has 1 Controller. Each Controller has 1 Interactor. Each
Interactor has 1 to several Data Access Objects and 1 Presenter. The Presenter
has 1 to several View Models. The various Views are observing the appropriate
View Models so that each knows when to update itself.
• Let’s draw all that!

48
A FIRST SEQUENCE DIAGRAM

https://developer.ibm.com/articles/the-sequence-diagram/ 49
PLANTUML FOR THE PREVIOUS EXAMPLE
@startuml
'https://plantuml.com/sequence-diagram

mainframe sd BalanceLookup (int accountNumber) : int

[-> "buyersBank : Bank" : getBalance(accountNumber)


activate "buyersBank : Bank"

"buyersBank : Bank" -> "ledger : AccountLedger" : retrieveAccount(accountNumber)


activate "ledger : AccountLedger"
return buyersAccount

"buyersBank : Bank" -> "buyersAccount : CheckingAccount" : getBalance()


activate "buyersAccount : CheckingAccount"
return balance

return balance

@enduml

50
ANOTHER
SEQUENCE
DIAGRAM

https://www.uml-diagrams.org/online-shopping-uml-
sequence-diagram-example.html

51
WHAT SEQUENCE DIAGRAMS SHOW
• A UML Sequence Diagram tells the story of how and when methods are called
during code execution.
• You can read the code to figure out the sequence of calls and draw one of these,
using as much or as little detail about parameters and return values as you like.
You can indicate variable names, or not.
• The SequenceDiagram plugin in IntelliJ can do these kinds of things too!
• You can also make a Sequence Diagram as part of your design process before
writing any code.

52
EXAMPLE FROM THE LOGIN CODEBASE

Let’s
investigate this
in the Interactor

53
THE OTHER SIDE OF THE BOUNDARY

54
THE PRESENTER’S STORY
• Let’s go to IntelliJ to investigate.

55

You might also like