89
Software Design Fundamentals Cristi Salcescu @2012 V5.1

Software Design Fundamentals

Embed Size (px)

DESCRIPTION

 

Citation preview

  • 1. Software Design Fundamentals Cristi Salcescu @2012 V5.1
  • 2. QuestionHow to create software that is ? Easy to read and understand Easy to change Easy to test
  • 3. UML Unified Modeling Language The most basic of UML diagrams is the Class Diagram. It describes classes and shows the relationships among them.
  • 4. UMLUML Notation for Relationships Inheritance class Relations A generalizes B A B derives from A Class A {} B Class B : A {}
  • 5. UMLUML Notation for Relationships Association class Relations A uses B A B Class field Methode parameter Methode Return Type class A Local variable { void Methode1() { B var1 = new B(); } }
  • 6. UMLUML Notation for Relationships Aggregation class Relations Shared Association A B A aggregates B B is part of A class RelationsClass B {}Class A Airport Aircraft{B FieldB;}
  • 7. UMLUML Notation for Relationships Composition class Relations Not-Shared Association A B A is composed of BClass B {} class RelationsClass A Person Leg{B FieldB;}
  • 8. Resource http://aviadezra.blogspot.com/2009/05/uml-associ
  • 9. Content System-Quality Attributes Code Qualities Design Principles Design Patterns Enterprise Patterns
  • 10. System-Quality Attributes Maintainability Flexibility Reusability Readability Testability
  • 11. System-Quality Attributes Maintainability A measure of how easy it is to modify the software to correct faults, improve performance or other attributes. Flexibility A measure of how easy it is to change software in response to different requirements
  • 12. System-Quality Attributes Reusability the capability for components and subsystems to be uses in other applications and in other scenarios Readability A measure of how easy it is to read and understand code. Testability A measure of how easy it is to create test criteria
  • 13. Resources http://msdn.microsoft.com/en-us/library/ee658094 http://msdn.microsoft.com/en-us/library/bb402962
  • 14. Code Qualities Encapsulation Cohesion No Redundancy Coupling
  • 15. Code Qualities Encapsulation Information hiding Means any kind of hiding Encapsulation of data Encapsulation of methods Encapsulation of type (behind an abstract class or interface)
  • 16. Code QualitiesEncapsulation Type Encapsulation Polymorphism class Encapsulation interface Cli ent IProduct ProductA Prod uctB
  • 17. Code Qualities Cohesion Cohesion refers to how much (or how little) the internal parts of something are working on the same issue No Redundancy Anything that could change should be in a single place in the system
  • 18. Code Qualities Coupling Coupling refers to the degree of direct knowledge that one class has of another. Strong coupling occurs when a dependent class contains a pointer directly to a concrete class Loose coupling occurs when the dependent class contains a pointer only to an interface that the concrete class implements
  • 19. Code QualitiesCoupling Strong/tight coupling class Coupling Cli ent Conc rete Loose coupling class Coupling interface Cli ent Abstraction Concr eate
  • 20. Code QualitiesCoupling Strong/tight coupling
  • 21. Code QualitiesCoupling Loose coupling
  • 22. Code QualitiesCoupling Strong coupling - Keyboard - Sound
  • 23. Code QualitiesCoupling Loose coupling - Keyboard - Sound
  • 24. Resources Addison Wesley - Emergent Design @2008, Chapter 7 http://www.netobjectives.com/files/resources/Code Wikipedia
  • 25. Design Principles SOLID Design Principles were introduced by Robert Martin in the book Agile Principles, Patterns, and Practices in C# @2002 Code becomes more flexible and adaptable to change, as well as more maintainable
  • 26. Design Principles SOLID Principles Single Responsibility Principle Open-Closed Principle Liskov Substitution Principle Interface Segregation Principle Dependency Inversion Principle Other Principles Dont Repeat Yourself (DRY) Separation of Concerns (SoC)
  • 27. Design Principles Single Responsibility Principle The principle states that every object should only have one reason to change and a single focus of responsibility
  • 28. Design Principles Open-Closed Principle Open for extension, but closed for modification Extend softwares capabilities without changing it
  • 29. Design PrinciplesOPC. class OPC interface Cli ent IProduct ProductA ProductB ProductC
  • 30. Design PrinciplesOCP.
  • 31. Design Principles Liskov Substitution Principle The principle dictates that you should be able to use any derived class in place of a parent class and have it behave in the same manner without modification.
  • 32. Design PrinciplesLSP.
  • 33. Design PrinciplesLSP.
  • 34. Design Principles Interface Segregation Principle States that clients should not be forced to depend on interfaces they dont use. Is all about separating fat interfaces into small, specific groups of related functionality.
  • 35. Design PrinciplesDIP Dependency Inversion Principle (DIP) 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. => DIP Is about isolating your classes from concrete implementations and having them depend on abstract classes or interfaces.
  • 36. Design PrinciplesDIP.cmp DIP Serv ice IRepository IService IGateway
  • 37. Design PrinciplesDI Dependency Injection (DI) is a technique that is used to allow calling code to inject the dependencies the class needs when is instantiated 3 Primary techniques : constructor injection, method injection, property injection
  • 38. Design PrinciplesDIP.
  • 39. Design PrinciplesDIP.
  • 40. Design PrinciplesDIP.cmp DIP IRepository IGateway Contr oller Serv ice Gatew ay Repository IGateway IRepository IService IService FakeGatew ay IGateway
  • 41. cmp DIPDIP Contr oller Presentation IService. Servi ce Serv ice IRepository IServi ce IGateway Resource Access IGateway IRepository Gatew ay Repository
  • 42. Design PrinciplesIoC Inversion of Control Container (IoC) an implementation of DIP and DI responsible for object graph instantiation initiated at application startup via code or configuration an "assembler that makes object coupling a run-time
  • 43. Automotive Industry . class IoC Component1Prov iderA Component1 Component1 Prov iderB Ca r Component2Prov iderA Component2 Component2 Prov iderB IoC Configuration
  • 44. Design PrinciplesIoC.
  • 45. Design PrinciplesIoC.
  • 46. Design PrinciplesIoC .class MVC Repository Controller Serv ice IRepository IGateway flow IService IService Us er IRepository Gateway IGateway
  • 47. Design PrinciplesTesting Testing in isolation using Mock objectsclass Coupling class Coupling interface interface IDependecyA IDependencyA MockDependecyA ConcreteDependecyA interface interface IDependecyB Module IDependencyB MockDependecyB Module ConcreteDependecyB interface interface IDependecyC ConcreteDependecyC IDependencyC MockDependecyC
  • 48. Design Principles Dont Repeat Yourself (DRY) Variation: "One rule, one place Have only one place where a rule is implemented. Separation of Concerns (SoC) Is the process of divide your application into distinct features. Modularity A software can be divided into separate elements called modules and that are integrated to solve the problem.
  • 49. Resources Wrox - Professional ASP.NET Design Patterns @2010 Wikipedia http://lostechies.com/derickbailey/2009/02/11/solid
  • 50. Design Patterns Introduced by The Gang of Four in the book Design Patterns: Elements of Reusable Object-Oriented Software @1994 Reusable solution to a commonly occurring problem
  • 51. Design Patterns Strategy Adapter Bridge Factory
  • 52. Design Patterns GOF Design Principles Design to interfaces Favor aggregation over inheritance Find what varies and encapsulate it (behind an abstract class or interface) Separate use from construction
  • 53. Design Patterns Strategy define a family of algorithms lets the algorithm vary independently from clients that use it Case Study Compute primes for different insurer companies
  • 54. Design PatternsStrategy .class Strategy class Strategy InusurerAGatew ay InsurerAGatew ay + +ComputePrim e()e() : void ComputePrim : void Serv ice Serv ice Serv ice InsurerGateway InsurerGateway + + ComputePrim e() : void ComputePrimComputePrime() : :void ++ ComputePrim e() void e() : void gateway.ComputePrime() InsurerBGatew ay InsurerBGatew ay + ComputePrim e() : void + ComputePrim e() : void
  • 55. Design PatternsStrategy . class Strategy interface Context IStrategy Concre teStra tegy1 ConcreteS trategy2
  • 56. Design PatternsStrategy Case Study interchange between 3rd party logging libraries
  • 57. Design PatternsStrategy . class Strategy class Strategy Serv ice class Strategy + MethodeA() : void Serv ice Serv ice ILogger Ilogger log() + Log() : void + MethodeA() : void + Log() : void logger.Log() Log4NetLogger EnterpriseLi braryLogger + Log() : void + Log() : void Log4NetLogger EnterpriseLi braryLogger + Log() : void + Log() : void
  • 58. Design Patterns Adapter converts the interface of a class into another interface that the clients expect
  • 59. Design PatternsAdapter Case Study Develop a system that communicates with an external device Integrate a 3rd party object that communicates with the device at the end of the project
  • 60. Design Patterns . class Adapter class Adapter Cli ent IGateway Cli ent IGateway + GetMeasure() : double + GetMeasure () : void FakeGatew ay RealGatew ayAdapter + GetMeasure() : double + GetMeasure() : double FakeGatew ay 3rdPartyObject.MeasureMethode() RealGatew ay + GetMeasure () : void + GetMeasure () : void 3rdPartyObj ect + MeasureMetho de() : void
  • 61. Design PatternsAdapter . class Adapter interface Cli ent ITarget + methodA() : void Adapter Adaptee + methodA() : void + methodB() : void
  • 62. Design PatternsAdapter Adapt a 3 party library interface to an existing interface used in the project
  • 63. Design PatternsAdapter . class Adapter class Adapter Cli ent Cli ent ILogger ILogger + + log() : void Log() : void Log4NetAdapter EnterpriseLi braryAdapter + Log4NetLogger log() : void + log() : void EnterpriseLi braryLogger + Log() : void + Log() : void Log4NetLogger EnterpriseLi braryLogger + logMethodA () : void + logMethodB () : void
  • 64. Design PatternsAdapter .
  • 65. Design Patterns Bridge Separate an abstraction from its implementation so that the two can vary independently Separate a varying entity from a varying behavior so that the two can vary independently
  • 66. Design PatternsBridge Case Study Creat a system that send notifications :email, sms Use different providers that offer services to send sms, emails
  • 67. Design PatternsBridge. class Bridge class Bridge class Bridge class Bridge Notifi cation Serv iceAgentA Serv iceAgentA Notification + +SendEmail () : : void SendEmail () void + Send() : void Notification IServiceAgent + +SendSms() : :void SendSms() void IServ ic eAgent +Notifi cation void Send() : + SendEmail () : void + SendSms() : void + Send() : void + SendEmail () : void Serv ice AgentB Email Sms + SendSms() : void + SendEmail () : void + Serv ice AgentB SendSms() : void Em ai l Sm s + SendEmail () : void + Send()l : void Em ai + Sm s Send() : void + SendSms() : void Emai l EmailAgentA : void EmailAgentB + Send() Sms SmsAgentA + Send() : void SmsAgentB + Send() : void + Send() : void serviceAgent.SendEmail() serviceAgent.SendSms()
  • 68. Design PatternsBridge. class Bridge interface Abstraction Implementor ConcreteAbstraction ConcreteIm plementor
  • 69. Design Patterns Factory hides the complexities of creating objects
  • 70. Design PatternsFactory class Factory interface Cli ent IProduct Factory Concrete Product + createProduct() : IProduct
  • 71. Design PatternsFactory . class Factory interface Cli ent IProduct Factory Concrete ProductB ConcreteProductA + createProduct(char) : IProduct reflection parameters(xml, database, flat file)
  • 72. Resources Design Patterns Explained A New Perspective on Object-Oriented Design, 2nd Edition @2004 http://www.oodesign.com http://www.cours.polymtl.ca/inf3700/divers/n
  • 73. Enterprise Patterns Introduced by Martin Fowler in the book Patterns of Enterprise Application Architecture @November 2002
  • 74. Enterprise Patterns Layers / SoC Horizontal Separation deployment SoC Presentation Layer Busines s Layer Resource Ac cess Layer
  • 75. Enterprise Patterns Presentation Layer MVP (Model View Presenter) Model : holds the data to show on the View View : displays the model data obtained via the presenter and delegates user input to the presenter. Presenter : coordinates the updates between View and Model MVC (Model View Controller) Model : holds the data to show on the View View : displays the model data supplied from the controller. Controller : It is the initial contact for a request handling It interacts with the model based on the request and selects the appropriate view to render.
  • 76. Enterprise Patterns Service Layer Services the service layer simply coordinates the business use case transaction and delegates work to the business objects for all the lower-level implementation details
  • 77. Enterprise PatternsService Layer Messaging Patters The Document Message simplifies the communication by encapsulating all information within an object (DTO) The Request-Response ensures that responses as well as requests use the Document Message pattern Data Tranfer Objects (DTOs) An object used to transfer data between subsystems
  • 78. Enterprise PatternsResource Access Layer Repository retrieve and persist your business entities typically includes CRUD methods Query Object an object that represent a database query
  • 79. Enterprise PatternsResource Access Layer Gateway An object that encapsulates access to an external system or resource. Service Agent a component acting as the front-end of communications towards Web Services. It should be solely responsible for actions of direct consumption of Web Services.
  • 80. Enterprise Patterns Domain Layer Introduced by Eric Evans, in his book Domain Driven Design Tackling Complexity in the Heart of Software @2003
  • 81. Enterprise PatternsModels pkg Models Doma in M odel Enti ties ValueObj ects flow flow Relati onal Model Dimens ional Model Fac ts Tables flow Dimensions
  • 82. Enterprise PatternsDomain Layer Entities An object that is not defined by its attributes, but rather by its identity Value Objects An object that contains attributes but has no conceptual identity
  • 83. .Invoices Id IdContract Contracts Id Number Clients Id Name ContractDescription Description IdIndustry IdStatus IdClient IdType Number IdGenericContract IdGroup IssueDate IdRefContract CorporateFunds IdType Address1 PaymentDue Address2 IdCurrency ZipCode ExchangeRate City IdPlaceOfSupply IdCountry SubscriberName Phone SubscriberPhone Fax aspnet_Users ApplicationId UserId UserName LoweredUserName MobileAlias IsAnonymous LastActivityDate
  • 84. . .
  • 85. Enterprise PatternsDomain Layer Aggregate groups logical entities and value objects Aggregate Root an entity, which is the only member of the aggregate that any object outside the aggregate is allowed to hold a reference to
  • 86. Domain Layer class DDD. A1 A2 A3 E1 B5 E2 B1 E3 B4 E4 B2 B3
  • 87. DDD N-Layered Architecture - Use Case : User Authenticationpkg DDD N Layered - Use writes credentials and Presentation Layer submits the request - Controller receives the request View s and delegates the responsibility to Controllers /Presenters Service - Service coordinates the use case - Step1 : delegate AD Service Layer authentication to Repository - Step 2: delegate logging to Serv ices Repository - Service returns that the Use case was completed successfully - The Controller gets the response Business/Domain Layer and decides what view to display Enti ties - The User see the View Resource Access Layer Reposi tories Gate w ays
  • 88. Use Case : User Authentication .sd Class Model 1: authenticate() 1.2: authenticate() 1.3: authenticateAD() Controller Serv ice Gateway Actor3 flow 1.1: create() 1.4: log() View Repository
  • 89. Resources Wrox - Professional ASP.NET Design Patterns @September, 2010 Patterns of Enterprise Application Architecture @November 2002 Wikipedia