SW Design Principle YoungSu, Son. Microsoft MVP EvaCast Study Leader Devpia Architecture Sysop
Motivation (How to Make Good SW?) Good World Good Software Policy Law Awareness PrinciplePattern Model Rules
Cells vs Cancer Cell cell cancer cell Cancer cells just have unusual behavior rules
Agenda Motivation TSP Solutions Complex Solution Complex Solution Simple Solution Simple Solution S/W Categories Do you think that Pattern is GPS in SW? Do you think that Pattern is GPS in SW? Basic Principle used Patterns OCP OCP SRP/ISP SRP/ISP DIP DIP LSP LSP
The Traveling-Salesmen Problem 51!(6.0828*10^62) different trips N location = (N-1)! Possible route = (N-1)! Possible route NP - Complete High Computational Complexity
Complex Solution (Master-Slave Pattern) Master Slaves Parallel Computing Distributed Computing Grid Computing
Simple Solution (Using Perfume) Starting Point Destination As time go on, Perfume fade !! a Path remained the most heavy perfume is the shortest path !! Experts
S/W Categories DomainIndependent20% DomainSpecific65% AppSpecific15% Software Categories pattern pattern pattern pattern pattern pattern pattern pattern pattern pattern Pattern Basic Principle
Basic Principles used Patterns SingleResponsibilityPrinciple OpenClosePrinciple DependencyInversionPrinciple LiskovSubstitutionPrinciple InterfaceSegregationPrinciple
Chapter 1 Open Close Principle S/W Entities (Classes, Modules, Functions, Etc.) Should be Open for Extension, but Closed for Modification. S/W Entities (Classes, Modules, Functions, Etc.) Should be Open for Extension, but Closed for Modification.
OCP Introduction Mobile Phone Charger Mobile Phone Charger Server/Client System Server/Client System IDEAS Abstraction is Key! Abstraction is Key! Divide mutable things and immutable things Divide mutable things and immutable things Define Interface between mutable things and immutable things Define Interface between mutable things and immutable things Known Uses GCC Compiler / Middleware /Command Pattern GCC Compiler / Middleware /Command Pattern Considerations Shared Module Shared Module Adapter vs Interface Modification Adapter vs Interface Modification Define Abstraction Level Define Abstraction Level
OCP Intro (Mobile Phone Charger) 24 pin 18 pin Mobile Phones When purchase Mobile Phone, Purchase Charger! Re-Buy Use
OCP Intro (Client/Server System) 1 X 1 N X N Server fileRead() Client fileEncode() Server fileRead() byteArrayRead() stringBufRead() Client fileEncode() byteArrayEncode() stringBufEncode()
OCP Intro – cont’d (Client/Server System) InputStream read() byteArray InputStream PipeInputStreamFileInputStream Client encode() 1 X N
IDEAS Abstraction is Key!! Divided moral and immoral. Define Interface between moral and immoral
Abstraction is Key! Abstraction Don’t equate Abstraction to Ambiguous. Don’t equate Abstraction to Ambiguous. In OO, Abstraction means objects are analyzed In OO, Abstraction means objects are analyzed until they are uniquely identified Abstraction is Key!! The abstractions are interfaces (abstract classes). The abstractions are interfaces (abstract classes). The unbounded group of possible behaviors is represented by all the possible derivatives classes. The unbounded group of possible behaviors is represented by all the possible derivatives classes. Such a module can be closed for modification Such a module can be closed for modification since it depends upon an abstraction that is fixed. Yet the behavior of that module can be extended Yet the behavior of that module can be extended by creating new derivatives of the abstraction.
Divide mutable things and immutable thins
ImmutableAttributesNameSSNBirthday MutableAttributesWeightFeatureStyle
Define Interface (Bridge/Dike) InputStream read() byteArray InputStream PipeInputStreamFileInputStream Client encode()
Know Use GCC Compiler Middleware Command Pattern
GCC Compiler SourceCodeLexicalAnalyzer Tokenized SyntacticAnalyzer ParsedCode SemanticAnalyzer Optimizer CodeGenerator QualifiedCode ObjectCode FinalCode IntermediateRepresentation SharedModule Close Open
Middleware (Common ORB Architecture) Client in args operation() out args, return DII IDL STUBS ORB INTERFACE IDL SKEL Object Adapter ORB CORE GIOP/IIOP/ESIOPS InterfaceRepositoryIDLCompilerImplementationRepository OBJREF Object(Servant) DSI
Command Pattern
Consideration Shared Module Adapter vs Interface Modification Define Abstraction Level
Shared Module (gcc Compiler) SourceCodeLexicalAnalyzer Tokenized SyntacticAnalyzer ParsedCode SemanticAnalyzer Optimizer CodeGenerator QualifiedCode ObjectCode FinalCode IntermediateRepresentation SharedModule Close Open
Adapter vs Interface Modification When Client demands new requirement!
Adapter vs Interface Modification Most Great Architects have predictability have predictability The Great Architect
Define Abstraction Level
Summary Experience DomainExpert Predictability Persistent
Summary Related Patterns GOF GOF Template Method PatternTemplate Method Pattern Strategy PatternStrategy Pattern Bride PatternBride Pattern POSA POSA ReactorReactor GOF Principle “Program to an interface, not to an implementation” “Program to an interface, not to an implementation” “Favor Object Composition over Inheritance” “Favor Object Composition over Inheritance”
Chapter 2 Dependency Inversion Principle Don’t Call Us! We Call You. Don’t Call Us! We Call You.
DIP Introduction Hollywood Principle Hollywood Principle IDEAS Inversion Of Control Inversion Of Control Template Method Pattern. Template Method Pattern. Known Uses Client Server Programming Client Server Programming CORBA Event Service CORBA Event Service Summary
DIP Intro (Hollywood Principle) Applicants Manager Don’t Call us!!
DIP Intro (Hollywood Principle) Applicants Manager Don’t Call us! We Call You!!!
IDEAS Inversion Of Control Template Method Pattern
Inversion of Control
Template Method Pattern doQuery(dbName, Query) { string dbCommand; dbCommand = FormatConnect(dbName); dbCommand = FormantSelect(Query); ///….return DataSet } Query Template +doQuery() #FormatConnect() #FormatSelect() OracleQT #FormatConnect() #FormatSelect() SqlSvrQT #FormatConnect() #FormatSelect()
Know Use Client Server Programming Blocking Model Blocking Model Polling Model Polling Model Publisher-Subscriber Model Publisher-Subscriber Model CORBA Event Service Timer Service
requestA() Server Client A_Handler B_Handler requestB() requestA() Client/Server System (Blocking Model - Sync) Client waits When Server arrive Response
requestA() Server Client A_Handler B_Handler requestB() Client/Server System (Polling Model - Async) Check()
Client/Server System (Publisher-Subscriber Model) Publisher(Server) Event Channel (Yellow Book) Subscribers
CORBA Event Service (Publisher-Subscriber Model) Event * Subscriber consume createsreceives Event Channel attachPublisher detachPublisher attachSubscriber detachSubscriber pushEvent Filter filterEvent Publisher produce Structure attachSubscriber produce pushEvent pushEventconsumedetachSubscriber : Event : Subscriber : Event Channel : Publisher event
Summary Related Patterns GOF GOF Command PatternCommand Pattern Observer PatternObserver Pattern POSA POSA Publisher/Subscriber PatternPublisher/Subscriber Pattern Event ChannelEvent Channel DIP simplifies complex communications between objects apply a not-stop talker object apply a not-stop talker object
Chapter 3 Liskov Substitution Principle In any time, In any time, sub-type could substitute base-type.
LSP Introduction Starbucks Coffee Starbucks Coffee IDEA Function Function Class Class Known Uses ODBC/JDBC ODBC/JDBC Considerations Inheritance vs Delegation Inheritance vs Delegation Is-A Relationship != Inheritance Is-A Relationship != Inheritance Summary
LSP Intro (Starbucks Coffee) A Honest Good A Counterfeit Customer
IDEA Function Function that use pointers or references to base classes must be able to use objects of derived classes without knowing it. Function that use pointers or references to base classes must be able to use objects of derived classes without knowing it. Class as argument If a method has an object of a class as an argument, the same method should be able to work with an object of derived class. If a method has an object of a class as an argument, the same method should be able to work with an object of derived class.
Know Use ODBC/JDBC
ODBC/JDBC ODBC(JDBC) API Application ODBC (JDBC) Driver Manager MSSQL Driver Oracle Driver
ODBC/JDBC (Template Method Pattern) doQuery(dbName, Query) { string dbCommand; string dbCommand; dbCommand = FormatConnect(dbName); dbCommand = FormatConnect(dbName); dbCommand = FormantSelect(Query); dbCommand = FormantSelect(Query); ///….return DataSet ///….return DataSet} Query Template +doQuery() #FormatConnect() #FormatSelect() OracleQT #FormatConnect() #FormatSelect() SqlSvrQT #FormatConnect() #FormatSelect()
Consideration Collection Framework in Java Inheritance vs Composition Inheritance vs Composition Is-A Relationship != Inheritance
Collection Framework in Java Set Collection List SortedSet
Collection Framework in Java (Cont’d - Sample Code) … main() { String[] infoValues = new String[]{“info1”,“info2”,“info3”}; List infoList = Arrays.asList(infoValues); infoList = infoHelper.addInfo(infoList); } … class Infohelper { public static java.util.List addInfo(Java.util.List currentInfo) { String info = “new info”; curretList.add(info); return currentinfo } Excpetion in thread “main” java.lang.UnsuppertedOperationException at java.util.AbstractList.add(AbstractList.java:150) LSPViolation
Collection Framework (Inheritance vs Composition) Set Collection List SortedSet SetList SortedSet Collection SetList SortedSet modified unmodified
Class Rectangle { public : public : void SetWidth(double w) { Width = w; } void SetHeight(double h) { Height = h; } double GetHeight() {return Height; } double GetWidth() { return Width; } double GetArea() {return width*height;} private : private : double Width; double Height; } Is-A Relationship (Rectangle & Square)
class Sequre extends Rectangle { public : void SetWidth(double w) { super.SetWidth(w); super.SetHeight(w); } void SetHeight (double h) { super.SetWidth(h); super.SetHeight(h); } public void calc (Rectangle r) { r.setWidth(10); r.setHeight(2); assert(r.getArea() == 20); } LSPViolation
The Tao of LSP (Contract) In order for the LSP to hold, and with it the OCP, and with it the OCP, all derivatives must conform to the behavior that clients expect of the base classes that clients expect of the base classes that they use. that they use.
Design by Contract (DBC) Using the scheme methods of classes declare preconditions and postconditions. The preconditions must be true in order for the method to excute. Upon completion, the method guarantees that the postcondition will be true. Recaangle :: SetWidth(double w) { … Assert((itsWidth == w) && (itsHeight == old.itsHeight)); Assert((itsWidth == w) && (itsHeight == old.itsHeight));}
Summary Related Patterns GOF GOF Chain-Of-Responsibility PatternChain-Of-Responsibility Pattern LSP Considers Design by Contract (IOPE) Considers Design by Contract (IOPE)
References “OO S/W Design Principle”, choi sang-hun et al, 2005 Design Patterns: Elements of Reusable Object-Oriented Software, E. Gamma, R.Helm, R. Johnson, J. Vlissides, Addison-Wesley, 1995 The Open-Closed Principle, Bertrand Meyer, 1998 CORBA, Steve Vinoski, IEEE Communications Magazine, February, Schmidt Home Page