Day5
-
Upload
madamewoolf -
Category
Technology
-
view
145 -
download
1
description
Transcript of Day5
![Page 1: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/1.jpg)
CSE 136 - Lecture 5 Part 1
C# Classlibrary
Business Objects/Model set of class definitions
Business Logic: if/else, calculations, loops code in the classes
Process/Flow specialized logic
![Page 2: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/2.jpg)
What is Business Logic Layer
service
asp.netjava client
export to xml
presentationdata is diff than
BL data
you willimplement thesein your project
class objects (more on this later - design patterns)
any logics, rules, calculations
validate user input, incoming data, etc.
![Page 3: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/3.jpg)
What is Business Logic Layer 2 Services
exposing business logic to outside system GPA system can provide graduation status for students
Entities Students taking courses. Courses have schedules and location.
Courses are categorized by departments. Rules, Calculations
Students can only register 20 units maximum per quarter CSE136 must be taken after CSE135, etc.
Validation Is the social security # 9 digits? Is credit card all digits?
Cannot rely JavaScript for validation
![Page 4: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/4.jpg)
Business Layer Patterns
Procedure Pattern Transcript Script pattern - A collection of procedures
(steps of execution). Table Module Pattern
similar to transaction script but operations are grouped by data (dataSet/dataTable)
Object-based Pattern Interrelated & Interconnected objects. Active Record Pattern - record looks like data tables
from the database with additional methods() Domain Model Pattern - not ER diagrams, but OOD
diagrams
1980s
1990s
21th century
![Page 5: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/5.jpg)
Procedure Pattern
Map your business components directly onto required user actions.
Best suited for simple scenarios and unlikely changing spec
Simple and no start-up cost Can not handle large/complex specs As complexity grow, becomes more
costly (not easily extended) CSE 136 will NOT use this design pattern
![Page 6: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/6.jpg)
Table Module Pattern
Remember DataSet in DAL (ADO.NET)
Series of transaction grouped by Data
Grouping the info/table by how data are related
Good for quick presentation display
Built-in in ASP.NET
![Page 7: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/7.jpg)
Table Module Pattern 2
What's wrong with this Pattern?
You must wait for SQL stored procedures to finish
If SQL proc changes, it changes the BL structure remove a column changed a column name You can't catch this error
through unit testing
![Page 8: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/8.jpg)
Object-based Pattern - Active Record Pattern Active Record Pattern is based on
DataSet design but create class object for each DataTable.
Duplication and quite a hassle Better than Table Module Pattern
SQL Proc changes won't affect outcome One step closer to Object Oriented
Design, but not object-oriented yet
![Page 9: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/9.jpg)
Object-based pattern - Active Record Pattern ex
// contains a list of students' ID, first name,// last name, birthday.DataSet.Tables["student"];
// Translate DataSet into Active Recordclass Student{ public string id; public string first_name; public string last_name; public DateTime birthday;
}
class StudentCourse{ public string id; public string course_id; public string courseNumber; public string CourseDescription;}
StudentCourse[] student_courses;
DataSet contains aDataTable with
student info andcourses
DataTable withstudent info
becomes a "class"object
DataTable withstudent courses
becomes an arrayof studentCourse
![Page 10: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/10.jpg)
Object-Based Patterns - Domain Model Pattern
Domain Model is also known as Object-Oriented Design
Define the entities and the relationships & flows between them
Each Entity has data (variables) & behavior (methods)
Consider the issues of “coupling” and “cohesion”. “Reuse”, “Maintainability”, and “Extensibility”
A diagram can be really large (divide & conquer) More Object-oriented design using Design Patterns
![Page 11: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/11.jpg)
Compare the Patterns
DataSet &Data Table
Object-oriented
"Enterprise"large systems
Systems are becoming more complex. Not practical anymore
Easier to expand with complexity and rule changes (obamacare)
![Page 12: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/12.jpg)
Domain Model to ER (DAL)
Data Tranfer between BLand DAL
Objects may be recursive (flow chart withboxes & arrows) or a tree-view list (org-chart)
Database storage is not recursive
Mapping the database data to object-oriented& back to db may be difficult but necessary
![Page 13: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/13.jpg)
Class Objects Design - steps
Start with use case diagram Run thru activity diagram to identify
entities and high-level relationship Run thru sequence diagram again to
identify attributes and methods for each entities. You may skip this step for 136 to save time
![Page 14: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/14.jpg)
UML Review 1
private
public
"A" is a class
"A" is an interfaceor abstract class
![Page 15: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/15.jpg)
UML Review 2
A and B call and access each other's elementObject A and B are linked through a class definition
class AlinkB { A a1; B b1; }
Similar to a join-table in database
A has B, and B can outlive ADestroy A, B still exists
A has a pointer to object B
A has a B, and B depends on A.
Destroy A, B also gets destroyed
A instantiated B object
![Page 16: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/16.jpg)
Domain Model – class diagram ex1
Student
IDFirstLastList<Enrollment>
GetGPA()GetCourses()
Grad_Student
GRE_Score
GetUndergradGPA()
Foreign_Student
TOEFL_ScoreCountry
GetForeignGPA()
Enrollment
Course_IDCourse_TitleQuarterYearGrade
Database ER diagram is hidden awayFrom the Domain Model
How many tables to store student info?
![Page 17: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/17.jpg)
Domain Model – class diagram ex2
Customer
IDFirstLastList<Order>List<Review>
GetOrders(param)GetReviews(param)
Order
Order_IDDateList<Order_Item>TotalTaxGrand_TotalList<Payment>
GetOrderItem()CalculateTotal()
Order_Item
Product_IDProduct_NamePriceQty
Payment
Payment_IDCC_NumberAmountReview
Product_IDRatingDate
Review table in the database may have a order_id, but in Domain Model, it is not used.
![Page 18: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/18.jpg)
Domain Model – class diagram ex3
Vehicle
YearMakeModelSubmodelList<Product>
GetMatchingProduct()
Product
IDNameDescriptionVendor_IDVendor_NameList<Inventory>List<BackOrder>
GetInventory()GetBackOrderInfo()
Inventory
Product_IDLocation_IDLocation_NameQuantity
BackOrder
Vendor_IDVendor_NameVendor_AddressQuantity_OrderedDate
Database ER diagram will have more tables to stored these information (vehicle, make, model, vendor, product, location, back_order, etc).
![Page 19: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/19.jpg)
Domain Model – class diagram ex4
DropBox
UserList<Object>List<SharedObject>
GetMyObjects()GetSharedObjects()
User
User_IDNameEmailDate Object
IDNameDate
Folder
List<Object>
File
Size
SharedObjects
User_IDObject_IDAccess_LevelDate
![Page 20: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/20.jpg)
Break Time
![Page 21: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/21.jpg)
CSE 136 - Lecture 5 Part 2
C# Classlibrary
Business Objects/Model set of class definitions
Business Logic: if/else, calculations, loops code in the classes
Process/Flow specialized logic
![Page 22: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/22.jpg)
Why use Design Patterns
Provide a starting point for a solution Speed up productivity in a team Improves system and application design Carpenter: connector design pattern
![Page 23: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/23.jpg)
Object-oriented Design Patterns Creational
The creational patterns aim to separate a system from how its objects are created, composed, and represented
They increase the system’s flexibility in terms of the what, who, how, and when of object creation
Structural Structural patterns are concerned with how classes and
objects are composed to form larger structures Behavioral
Behavioral patterns identify common communication patterns between objects
They increase flexibility in carrying out this communication
![Page 24: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/24.jpg)
Creational Patterns
Factory Singleton Prototype (skip) Abstract Factory (skip) Builder (skip)
![Page 25: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/25.jpg)
Creational - Factory example
<<interface>>ILog
LogToFile LogToDBCreator
+ FactoryMethod(): Log
FactoryMethod(){ if (log_destination == "file") log = new LogToFile() else log = new LogtoDB()
return log}
log_destination isdetermined by aconfiguration file
Client
+ errorLog:ILog
ILog errorlog = Log.FactoryMethod();
Polymorphism
Logging C# exampleavailable on class homepage (136 project)
![Page 26: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/26.jpg)
Creational - Factory
Letting subclasses decide exactly which class to instantiate
Various subclasses might implement the interface
Factory Method instantiates the appropriate subclass based oninformation supplied by the client or extracted from the current state.
<<interface>>IProduct
ProductA ProductBCreator
+ FactoryMethod(): Product
instantiate object
Client
+ product:IProduct
product =creator.FactoryMethod()
![Page 27: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/27.jpg)
Creational - Singleton
Ensure that there is only one instance of a class/program
All requests are directed to that one and only object
The class itself that is responsible for ensuring this constraint,not the clients of the class
Object should not be created until it is actually needed
![Page 28: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/28.jpg)
Creational - Singleton Code
only one instance
C# interview question
![Page 29: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/29.jpg)
Structural Design Patterns
Decorator Proxy Adapter Facade Bridge (skip) Composite (skip) Flyweight (skip)
![Page 30: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/30.jpg)
Structural - Decorator example
The object does not know it is being “decorated” (makes this a useful patternfor evolving systems)
<<interface>>IStudent
+ GPA()
CollegeStudent
+GPA()
InternationalStudent
- ToeflScore- InternationalStudent : IStudent
+ GPA()+ TOEFL()
InternationalStudent objectcontains CollegeStudent
object
Added behavior
CollegeApplication
CollegeStudent doesnot know it is being
extended byInternationalStudent
![Page 31: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/31.jpg)
Structural - Decorator
Open for extension, close for modification
To provide a way of attaching new state and behavior to an object dynamically.
The object does not know it is being “decorated” (makes this a useful patternfor evolving systems)
Decorators both inherit the original class and contain an instantiation of it
<<interface>>IComponent
+Operation()
Component
+Operation()
implements
Decorator
- addedState- Component : IComponent
+ Operation()+ AddedBehavior
inheritancedecorator has a Component
Client
.NET libraries arebased on decoratorpattern
![Page 32: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/32.jpg)
Structural - Proxy example
Web GUI wants to access a service on the business layer to retrieve student info
Web
Student
+ GetStudentInfo()
<<interface>>IStudent
+GetStudentInfo()
Service onbusiness layer
ProxyOnTheWeb
+GetStudentInfo()
add proxy reference
add proxy reference is simple in VS 2010. Right-click and add service reference
Web hasaccess to
Proxy
Proxy hasaccess to
Student object
Routesrequests to theStudent object
![Page 33: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/33.jpg)
Structural - Proxy
Supports objects that control the creation of and access to other objects
Often a small (public) object that stands in for a more complex (private) object
Client
Subject
+ Request()
Proxy
+Request()
<<interface>>ISubject
+Request()Client hasaccess to
Proxy
Proxy hasaccess toSubject
Routesrequests tothe Subject
![Page 34: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/34.jpg)
Structural - Adapter example
Enables a system to use classes whose interfaces don’t quite match its requirements
This pattern promotes programming to Interfaces, not classes.
LazyStudentMainLastYearsCode
+ CalculateGPA()+ Sort()
pre-compiled libraryfrom last year
Adapter
+GetGPA()
inherit
<<interface>>ITarget
+ GetGPA()
implements
GetGPA() invokesCalculateGPA()
LazyStudentMaincalls GetGPA() whichcalls CalculateGPA()
![Page 35: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/35.jpg)
Structural - Adapter
ClientAdaptee
+ SpecificRequest()
Adapter
+Request()
inherit
<<interface>>ITarget
+ Request()
implements
Client callsRequest()
Request() invokesSpecificRequest()
Enables a system to use classes whose interfaces don’t quite match its requirements
This pattern promotes programming to Interfaces, not classes.
![Page 36: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/36.jpg)
Structural - Facade
To provide different high-level views of subsystems whose details are hidden from users
A remote service call from GUI to business layer service is a "remote facade"
Student.CalculateGPA(student_id)
retrieve grades from GPA systemcalculates overall gradescalculate major GPA
Faculty.GetCoursesStats(faculty_id)
retrieve courses taught in the pastcalculate total units taughtcalculate #A's, B's, C's, etc.
![Page 37: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/37.jpg)
Behavioral Pattern
Strategy Chain of Responsibility Iterator (skip - you have seen this in C#
lecture “enumerator”) Skip: Observer, Command, Mediator,
Memento, State, others…
![Page 38: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/38.jpg)
Behavioral - Strategy exampleIf we want to rank students, there may be different ways/algorithms to ranka student.
Rank a student by GPA alone
Rank a student by progress made
Rank a student by research achievements (inventions, breakthroughs)
<<interface>>IRanking
+ Calculate()
RankByGPA
+ Calculate()
RankByGPA.cs
RankByProgress
+ Calculate()
RankByProgress.cs
RankByBreakThru
+ Calculate()
RankByBreakThru.cs
Award
Award has accessto different waysto rank a student
class Award{IRanking rank;
... if (rankby == "GPA") rank = new RankByGPA() else if (rankby = "progress") rank = new RankByProgress() else rank = new RankByBreakThru() result = rank.Calculate()...}
Polymorphism
![Page 39: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/39.jpg)
Behavioral - Strategy
The algorithms can also be expressed independently of the data they are using
Removing an algorithm from its host class and putting it in a separate class
There may be different algorithms (strategies) that are applicable for agiven problem. If the algorithms are all kept in the host, messy code withlots of conditional statements will result
Enables a client to choose which algorithm to use from a family of algorithmsand gives it a simple way to access it
<<interface>>IStrategy
+ Algorithm()
StrategyA
+ Algorithm()
StrategyA.cs
StrategyB
+ Algorithm()
StrategyB.cs
Client
Client has access toboth StrategyA andStrategyB objects
Polymorphism
Client may come From GUI
![Page 40: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/40.jpg)
Behavioral - Chain example
Only get data from server if local cache is missing
Boeing IRAD project
Required high performance. Caching locally.
RAM Local Disk DB on server
<<interface>>IGetData
#successor:GetData
+ Request()
RAM
+ Request()
LocalDisk
+ Request()
CallToServer
+ Request()
GUIClient
data = RAM.Request();
Request(){if (data == null) data = LocalDisk.Request();}
Requst(){if (data == null) data = CallToServer.Request();}
Request(){if (data == null) data = Server.GetData(...);}
Polymorphism
![Page 41: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/41.jpg)
Behavioral - Chain
At the end of the chain, there can be either default or exceptional behavior
A list of Handler objects that have limitations on the nature of the requests they can deal with
If an object cannot handle a request, it passes it on to the next object in the chain
<<interface>>IHandler
#successor:Handler
+ Request()
Handler1
+ Request()
Handler2
+ Request()
successor is thelink to the nextHandler object
CallsSuccessor ifnecessary
Client
A class thatinitiates aRequest
Polymorphism
![Page 42: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/42.jpg)
Review question
Why does domain model a better pattern at the end?
What are the three categories of OO design pattern?
Why are inheritance and polymorphism the center of OO design pattern? Open/close principal, code flexibility.
![Page 43: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/43.jpg)
Demo Code
Business Logic Layer Domain Objects Error Logging implementation (factory
pattern) Data Transfer Object
![Page 44: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/44.jpg)
Your Assignment
Due next Thursday Design and develop business layer based on
UML UML class diagram for Domain Object Model C# Domain Model classes C# Domain Business Logic Must use creational pattern for error-logging (log
to db or file based on app.config) Must use asynchronous call for error-logging Validations (regular expression – cover in day6)
Developing test cases for your business layer
![Page 45: Day5](https://reader035.fdocuments.us/reader035/viewer/2022081602/548ffc30b47959d3248b45f2/html5/thumbnails/45.jpg)
References
.NET : Architecting Applications for the Enterprise
Design Patterns: Elements of Re-usable Object-Oriented Software
C# Design Patterns