day5
DESCRIPTION
TRANSCRIPT
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
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.
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
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
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
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
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
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
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
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
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)
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
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
UML Review 1
private
public
"A" is a class
"A" is an interfaceor abstract class
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
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?
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.
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).
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
Break Time
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
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
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
Creational Patterns
Factory Singleton Prototype (skip) Abstract Factory (skip) Builder (skip)
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)
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()
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
Creational - Singleton Code
only one instance
C# interview question
Structural Design Patterns
Decorator Proxy Adapter Facade Bridge (skip) Composite (skip) Flyweight (skip)
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
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
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
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
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()
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.
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.
Behavioral Pattern
Strategy Chain of Responsibility Iterator (skip - you have seen this in C#
lecture “enumerator”) Skip: Observer, Command, Mediator,
Memento, State, others…
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
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
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
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
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.
Demo Code
Business Logic Layer Domain Objects Error Logging implementation (factory
pattern) Data Transfer Object
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
References
.NET : Architecting Applications for the Enterprise
Design Patterns: Elements of Re-usable Object-Oriented Software
C# Design Patterns