Objektorienterad Systemutveckling 2

Relevanta dokument
Objektorienterad Systemutveckling Period 3

Support Manual HoistLocatel Electronic Locks

A metadata registry for Japanese construction field

Design. Vad lärde jag mig förra lekfonen? Hur bidrog jag Fll lärandet? Kravhantering sammanfa0ning 13/04/14

Isometries of the plane

Mönster. Ulf Cederling Växjö University Slide 1

6 th Grade English October 6-10, 2014

Health café. Self help groups. Learning café. Focus on support to people with chronic diseases and their families

Förändrade förväntningar

FÖRBERED UNDERLAG FÖR BEDÖMNING SÅ HÄR

Isolda Purchase - EDI

Michael Q. Jones & Matt B. Pedersen University of Nevada Las Vegas

Preschool Kindergarten

Writing with context. Att skriva med sammanhang

Kursplan. IK1004 Java - Grafiska användargränssnitt med Swing. 7,5 högskolepoäng, Grundnivå 1. Java - GUI Programming with Swing - Undergraduate Level

Stad + Data = Makt. Kart/GIS-dag SamGIS Skåne 6 december 2017

Designmönster för sociala användningssituationer

CHANGE WITH THE BRAIN IN MIND. Frukostseminarium 11 oktober 2018

Problem som kan uppkomma vid registrering av ansökan

Examensarbete Introduk)on - Slutsatser Anne Håkansson annehak@kth.se Studierektor Examensarbeten ICT-skolan, KTH

Beijer Electronics AB 2000, MA00336A,

Senaste trenderna inom redovisning, rapportering och bolagsstyrning Lars-Olle Larsson, Swedfund International AB

Materialplanering och styrning på grundnivå. 7,5 högskolepoäng

RUP är en omfattande process, ett processramverk. RUP bör införas stegvis. RUP måste anpassas. till organisationen till projektet

SOA One Year Later and With a Business Perspective. BEA Education VNUG 2006

State Examinations Commission

Vad kännetecknar en god klass. Vad kännetecknar en god klass. F12 Nested & Inner Classes

Make a speech. How to make the perfect speech. söndag 6 oktober 13

Om oss DET PERFEKTA KOMPLEMENTET THE PERFECT COMPLETION 04 EN BINZ ÄR PRECIS SÅ BRA SOM DU FÖRVÄNTAR DIG A BINZ IS JUST AS GOOD AS YOU THINK 05

Software Design Introduction

Viktig information för transmittrar med option /A1 Gold-Plated Diaphragm

Vässa kraven och förbättra samarbetet med hjälp av Behaviour Driven Development Anna Fallqvist Eriksson

Resultat av den utökade första planeringsövningen inför RRC september 2005

Ett hållbart boende A sustainable living. Mikael Hassel. Handledare/ Supervisor. Examiner. Katarina Lundeberg/Fredric Benesch

Kursplan. AB1029 Introduktion till Professionell kommunikation - mer än bara samtal. 7,5 högskolepoäng, Grundnivå 1

Kursutvärderare: IT-kansliet/Christina Waller. General opinions: 1. What is your general feeling about the course? Antal svar: 17 Medelvärde: 2.

Information technology Open Document Format for Office Applications (OpenDocument) v1.0 (ISO/IEC 26300:2006, IDT) SWEDISH STANDARDS INSTITUTE

Swedish adaptation of ISO TC 211 Quality principles. Erik Stenborg

Custom-made software solutions for increased transport quality and creation of cargo specific lashing protocols.

Skattejurist för en dag på Deloitte i Malmö! 26 april 2016

Kursplan. MT1051 3D CAD Grundläggande. 7,5 högskolepoäng, Grundnivå 1. 3D-CAD Basic Course

Lösenordsportalen Hosted by UNIT4 For instructions in English, see further down in this document

DVG C01 TENTAMEN I PROGRAMSPRÅK PROGRAMMING LANGUAGES EXAMINATION :15-13: 15

Webbreg öppen: 26/ /

Kvalitetsarbete I Landstinget i Kalmar län. 24 oktober 2007 Eva Arvidsson

Webbregistrering pa kurs och termin

Sammanfattning. Revisionsfråga Har kommunstyrelsen och tekniska nämnden en tillfredställande intern kontroll av att upphandlade ramavtal följs.

Datasäkerhet och integritet

Objekt-orienterad programmering och design. DIT953 Niklas Broberg, 2018

Kursplan. FÖ3032 Redovisning och styrning av internationellt verksamma företag. 15 högskolepoäng, Avancerad nivå 1

Föreläsning 8. Designmönster

Methods to increase work-related activities within the curricula. S Nyberg and Pr U Edlund KTH SoTL 2017

Biblioteket.se. A library project, not a web project. Daniel Andersson. Biblioteket.se. New Communication Channels in Libraries Budapest Nov 19, 2007

Klicka här för att ändra format

Module 1: Functions, Limits, Continuity

Designmönster/Design patterns

CVUSD Online Education. Summer School 2010

EVALUATION OF ADVANCED BIOSTATISTICS COURSE, part I

Authentication Context QC Statement. Stefan Santesson, 3xA Security AB

Workplan Food. Spring term 2016 Year 7. Name:

Schenker Privpak AB Telefon VAT Nr. SE Schenker ABs ansvarsbestämmelser, identiska med Box 905 Faxnr Säte: Borås

Övning 5 ETS052 Datorkommuniktion Routing och Networking

LARS. Ett e-bokningssystem för skoldatorer.


SWESIAQ Swedish Chapter of International Society of Indoor Air Quality and Climate

endast har ett korrekt alternativ. Om

The Municipality of Ystad

The Swedish National Patient Overview (NPO)

Från extern till intern på tre dagar Erfarenheter från externa lärares pedagogiska kompetensutveckling

Kursplan. FÖ1038 Ledarskap och organisationsbeteende. 7,5 högskolepoäng, Grundnivå 1. Leadership and Organisational Behaviour

Adding active and blended learning to an introductory mechanics course

Module 6: Integrals and applications

Systemutveckling. Historiskt grundad introduktion

Service och bemötande. Torbjörn Johansson, GAF Pär Magnusson, Öjestrand GC

2.1 Installation of driver using Internet Installation of driver from disk... 3

FANNY AHLFORS AUTHORIZED ACCOUNTING CONSULTANT,

MÅLSTYRNING OCH LÄRANDE: En problematisering av målstyrda graderade betyg

Kursplan. NA3009 Ekonomi och ledarskap. 7,5 högskolepoäng, Avancerad nivå 1. Economics of Leadership

Cross sectional planning for pandemic influenza in Sweden

Här kan du checka in. Check in here with a good conscience

Installation Instructions

Enterprise App Store. Sammi Khayer. Igor Stevstedt. Konsultchef mobila lösningar. Teknisk Lead mobila lösningar

Objekt-orienterad Programmering och Design. TDA551 Alex Gerdes, HT-2016

WhatsApp finns för dessa plattformar:

The reception Unit Adjunkten - for newly arrived pupils

Quick-guide to Min ansökan

Alias 1.0 Rollbaserad inloggning

KPMG Stockholm, 2 juni 2016

Boiler with heatpump / Värmepumpsberedare

Objekt-orienterad Programmering och Design. TDA552 Alex Gerdes, HT-2018

Sara Skärhem Martin Jansson Dalarna Science Park

Styrteknik: Binära tal, talsystem och koder D3:1

Hur arbetar vi praktiskt i SAG?

PORTSECURITY IN SÖLVESBORG

The Finite Element Method, FHL064

Designmönster, introduktion. Vad är det? Varför skall man använda mönster?

Transkript:

Objektorienterad Systemutveckling 2 2017 Period 3 kurskod C1OB2B Innehåll Kursintroduktion Introduktion Systemarkitekturer Vad innebär systemarkitektur? Lagerindelning Mönster och stilar Tillvägagångssätt Designmönster GRASP GoF Kursmaterialet finns temporärt även på http://www.gidenstam.org/hb/oosu2 1

KURSINTRODUKTION Kursintroduktion Inblandade lärare Anders Gidenstam, AGD (kursansvarig, examinator) Ny som kursansvarig för OOSU2. Har tidigare undervisat för DE/SV i: Grundläggande programmering med C# (VT09, VT13) Visuell programutveckling med C# (HT09 HT11(/12)) Systemutvecklingsprojekt (HT16) Jens Holgersson, JHO Var med i OOSU2 förra året och OOSU1 nu senast. Johannes Sahlin, JHSA Ny. 2

Kursplan - Innehåll Kursen är en fördjupningskurs som bygger vidare på befintliga kunskaper om objektorienterad problemlösning och programmering i C#. De tre huvudsakliga områdena som behandlas i kursen är systemarkitektur, persistent data och användarinteraktion. Kursen syftar också till att öva er i att tillämpa objektorienterad (analys och) design (OO(A)D). Designmönster och designprinciper enligt GRASP används genomgående för att visa på vad som är standardlösning för olika typer av utvecklingsproblem. Kursplan - Innehåll Kursens uppbyggnad utgår ifrån arkitekturen hos ett objektorienterat informationssystem och behandlar de vanligaste formerna av arkitekturlösningar. Fokus ligger på logiska och driftrelaterade arkitekturaspekter. 3

Kursplan - Innehåll Persistent data utgör en central del i många system och kursen behandlar lösningar för att hantera interaktionen mellan den objektorienterade lösningen av domänlogiken och data som lagras i t ex databaser med utgångspunkt i ramverket Entity Framework. Kursplan - Innehåll Vidare behandlar kursen aspekter kring användarinteraktion genom att studera interaktions- och gränssnittsdesign. Denna del introducerar även användning av gränssnittskomponenter i C#. 4

Kursplan - Förkunskaper Avklarade kurser Databasteknik 7,5 högskolepoäng och Objektorienterad systemutveckling 1 7,5 högskolepoäng eller motsvarande. Dispens måste sökas av alla som inte uppfyller förkunskapskraven. För 21OB1B (OOSU1) går det att invänta resultat från tentamen, men åtkomst till PingPong dröjer då. Dispens ges utan förbehåll till dem som har klarat tentamen och laborationer i DBT och har VG i grundläggande programmering. Övriga fall bedöms individuellt utifrån resultat i LADOK mm. Att läsa en kurs som man fått dispens för medför ett extra ansvar för den enskilde studenten att inhämta och uppdatera nödvändiga förkunskaper Kursmaterialet finns temporärt även på http://www.gidenstam.org/hb/oosu2 Kursplan - Mål Efter avklarad kurs ska studenten kunna, med avseende på, Kunskap och förståelse 1. Förklara grundläggande koncept i en objektorienterad systemarkitektur, 2. Förklara grundläggande koncept i hantering av persistent data, 3. Förklara grundläggande koncept inom användarinteraktion, 4. Redogöra för tillämpliga metoder och tekniker inom hantering av persistent data, 5. Redogöra för tillämpliga metoder och tekniker inom interaktions- och gränssnittsdesign, 6. Visa kunskap i användningen av UML i arbetet med att designa och dokumentera en objektorienterad systemarkitektur, Färdighet och förmåga 7. Genomföra en objektorienterad arkitekturanalys och -design med stöd av UML, 8. Praktiskt kunna tillämpa metoder och tekniker inom hantering av persistent data med tillämpning i ett objektorienterat programmeringsspråk (C#), 9. Praktiskt kunna tillämpa metoder och tekniker inom interaktions- och gränssnittsdesign med tillämpning i ett objektorienterat programmeringsspråk (C#), Värderingsförmåga och förhållningssätt 10. Visa förmåga att göra en bedömning av lämpligheten av interaktions- och gränssnittsdesign utifrån ett givet problem, 11. Visa förmåga att göra en bedömning av lämpligheten av en systemarkitektur utifrån ett givet problem. 5

Kursplan Mål och examinationer Laboration 1 (LAB1): Systemarkitekturuppgift i grupp Högskolepoäng: 1.5 Betygskala: UG Lärandemål: 1. Förklara grundläggande koncept i en objektorienterad systemarkitektur, 6. Visa kunskap i användningen av UML i arbetet med att designa och dokumentera en objektorienterad systemarkitektur, 7. Genomföra en objektorienterad arkitekturanalys och -design med stöd av UML, 11. Visa förmåga att göra en bedömning av lämpligheten av en systemarkitektur utifrån ett givet problem. Kursplan Mål och examinationer Laboration 2 (LAB2): Programmeringsuppgift i grupp Högskolepoäng: 1.5 Betygskala: UG Lärandemål: 2. Förklara grundläggande koncept i hantering av persistent data, 4. Redogöra för tillämpliga metoder och tekniker inom hantering av persistent data, 8. Praktiskt kunna tillämpa metoder och tekniker inom hantering av persistent data med tillämpning i ett objektorienterat programmeringsspråk (C#), 6

Kursplan Mål och examinationer Laboration 3 (LAB3): Interaktions- och gränssnittsuppgift i grupp Högskolepoäng: 1.5 Betygskala: UG Lärandemål: 3. Förklara grundläggande koncept inom användarinteraktion, 5. Redogöra för tillämpliga metoder och tekniker inom interaktionsoch gränssnittsdesign, 9. Praktiskt kunna tillämpa metoder och tekniker inom interaktions- och gränssnittsdesign med tillämpning i ett objektorienterat programmeringsspråk (C#), 10. Visa förmåga att göra en bedömning av lämpligheten av interaktions- och gränssnittsdesign utifrån ett givet problem, Kursplan Mål och examinationer Tentamen: (TENT): Salstentamen Högskolepoäng: 3.0 Betygskala: UVG Lärandemål : 1. Förklara grundläggande koncept i en objektorienterad systemarkitektur, 2. Förklara grundläggande koncept i hantering av persistent data, 3. Förklara grundläggande koncept inom användarinteraktion, 4. Redogöra för tillämpliga metoder och tekniker inom hantering av persistent data, 5. Redogöra för tillämpliga metoder och tekniker inom interaktions- och gränssnittsdesign, 6. Visa kunskap i användningen av UML i arbetet med att designa och dokumentera en objektorienterad systemarkitektur, 10. Visa förmåga att göra en bedömning av lämpligheten av interaktions- och gränssnittsdesign utifrån ett givet problem, 11. Visa förmåga att göra en bedömning av lämpligheten av en systemarkitektur utifrån ett givet problem. Tentan kommer vara uppdelad i 3 delar Del 1 omfattar mål 1, 6 & 11 Del 2 omfattar mål 2 & 4 Del 3 omfattar mål 3, 5 & 10 För att bli godkänd på tentan måste varje del vara godkänd. För väl godkänd måste poängsumman nå upp till nivån för väl godkänd. Se till att kunna det som laborationerna prövar! 7

Innehåll och progression Grundläggande Programmering med C# Systemanalys och design Objektorienterad Systemutveckling 1 Databasteknik Objektorienterad Systemutveckling 2 Förändringsarbete och design av informationssystem Systemutvecklingsprojekt Innehåll och progression Del 3 Del 1 Grundläggande programmering med C# Objektorienterad systemutveckling 1 Del 2 8

Kursplan - Litteratur Microsoft Patterns & Practices Team. Microsoft Application Architecture Guide (Patterns & Practices). Finns gratis online. Deitel, H.M. och Deitel, P.J.. Visual C# 2012 How To Program, Pearson, (senaste upplagan). Benyon, D.. Designing Interactive Systems: A comprehensive guide to HCI, UX and interaction design, Pearson, (senaste upplaga). Litteraturhänvisning (ungefärlig) Kursbok A: Microsoft Application Architecture Guide (Patterns & Practices) B: Visual C# 2012 How To Program C: Designing Interactive Systems: A comprehensive guide to HCI, UX and interaction design Föreläsning Bok:kapitelnummer Systemarkitekturer A: 1-5+19 Lagerindelning och -design A: 6-9+17 (+16, 20-25) LINQ + LINQ to Entities B: 9+22 Entity Framework + lagerindelning Webresurser DB and Model First B: 22 + Webresurser Code first Webresurser Interaktionsdesign - Introduktion C: 1-5 Uppgiftsorienterad gränssnittsdesign C: 8-9 + 11-13 (+ 14-20) Windows Presentation Foundation B: 32-33 + Webresurser Windows Forms + Lagerseparation B: 14-15 + Webresurser 9

Övrigt Schema Kontrollera schemat noggrant Meddela snarast om det förekommer omöjliga konflikter Handledningar och övningar kan krocka med andra kurser Frågor? INTRODUKTION 10

GENERAL GUIDELINES Code against interfaces Not against implementations! 11

Grundläggande Principer för OO-design Hantera komplexitet (Divide-and-Conquer) Dela upp problemet och lösningen i delar. Inkapsling (Encapsulation) Använda gränssnitt (Interface) Dölja information (Information hiding) Accessnivåer: public, protected, private Abstraktion (Abstraction) Generalisering (Generality) Återanvändning (Extensibility) 24 Interface Is used to ensure a certain behavior. Enables the declaration of variables of interface type. Leads to loose coupling between objects. Makes it possible to implement several interfaces. 12

Abstract classes Enables inheritance of behavior and functionality. Enables the declaration of variables of the type of the abstract class. Leads to loose coupling between objects. Not possible to inherit from several abstract classes. Inheritance Inherit properties and functionality from other classes Not always the best solution! 13

Delegation Sometimes it is better to use an internal instance of a class to get access to its properties and functionality Again Code against interfaces Not against implementations! 14

SYSTEMARKITEKTUR Läsanvisningar Microsoft Application Architecture Guide (Patterns & Practices) Kapitel 1-5 + 19 Onlineresurser Länkar till onlineversioner av kursboken Application Architecture Knowledge Base (utgår från boken) 15

Vad är systemarkitektur? Systemarkitektur handlar både om fysisk och logisk uppdelning Logisk uppdelning handlar om lagerindelning och objektdesign Fysisk uppdelning handlar om vilka delar av systemet som körs på vilken enhet Vad innebär systemarkitektur? Systemarkitektur handlar om den övergripande organiseringen av systemet Det handlar om att dela upp ansvaret för olika delar av systemet på ett tydligt sätt som underlättar utveckling och underhåll 16

Vad innebär systemarkitektur? Software application architecture is the process of defining a structured solution that meets all of the technical and operational requirements, while optimizing common quality attributes such as performance, security, and manageability (kursboken) Vad innebär systemarkitektur? Software architecture encompasses the set of significant decisions about the organization of a software system including the selection of the structural elements and their interfaces by which the system is composed; (Krutchen, Booch, Bittner & Reitman via kursboken) The highest-level breakdown of a system into its parts; the decisions that are hard to change; (Martin Fowler, Patterns of Enterprise Application Architecture via kursboken) 17

Why is Architecture Important? Software must be built on a solid foundation. You may put your application at risk by failing to consider key scenarios, failing to design for common problems, or failing to appreciate the long term consequences of key decisions Architectural decisions are most often concerned with non-functional requirements Architectural analysis and design must be initiated early in the development Målet med arkitekturen The architecture should: Expose the structure of the system but hide the implementation details. Realize all of the use cases and scenarios. Try to address the requirements of various stakeholders. Handle both functional and quality requirements 18

Pekpinnar Ett grundantagande inom arkitektur är att systemets design kommer att evolvera över tid Du kan inte förutsäga allt från början En viktig nyckel till framgång inom systemutveckling handlar om att kunna hantera förändrade krav Skapa en arkitektur som tillåter evolvering och anpassning till nya och förändrade krav Pekpinnar Överarbeta inte arkitekturen Gör inga antaganden som inte kan verifieras Se till att lämna öppningar för framtida förändringar Identifiera sådant som leder till stora kostnader om det måste göras om och få dem rätt från början 19

Assess your Architecture When testing your architecture, consider the following questions: What assumptions have I made in this architecture? What explicit or implied requirements is this architecture meeting? What are the key risks with this architectural approach? What countermeasures are in place to mitigate key risks? In what ways is this architecture an improvement over the baseline or the last candidate architecture? ARKITEKTURMÖNSTER OCH STILAR 20

Vad innebär en arkitekturstil? En arkitekturstil är en samling principer som formar ett applikationssystem Ett generellt ramverk De tillhandahåller: Ett gemensamt språk Möjlighet att kommunicera utan hänsyn till specifikt programmeringsspråk eller plattform Designmönster på arkitekturnivå Arkitekturtyper Arkitekturstilar kan organiseras utifrån deras fokusområde Nästan alltid kombineras flera olika arkitekturstilar Category Communication Deployment Domain Structure Architecture styles Service-Oriented Architecture (SOA), Message Bus Client/Server, N-Tier, 3-Tier Domain Driven Design Component-Based, Object-Oriented, Layered Architecture 21

Arkitekturtyper Objektorienterad A design paradigm based on division of responsibilities for an application or system into individual reusable and self-sufficient objects, each containing the data and the behavior relevant to the object. An object oriented design views a system as a series of cooperating objects. Objects are discrete, independent, and loosely coupled; they communicate through interfaces, by calling methods or accessing properties in other objects, and by sending and receiving messages. 22

Domändriven design An object-oriented architectural style focused on modeling a business domain and defining business objects based on entities within the business domain. It aims to enable software systems that are a realization of the underlying business domain by defining a domain model expressed in the language of business domain experts. The whole team agrees to only use a single language that is focused on the business domain The Domain Driven Design process holds the goal not only of implementing the language being used, but also improving and refining the language of the domain. This in turn benefits the software being built, since the model is a direct projection of the domain language. Lagerindelning Layers help to differentiate between the different kinds of tasks performed by the components, making it easier to create a design that supports reusability of components Dividing an application into separate layers that have distinct roles and functionalities helps you to maximize maintainability of the code, optimize the way that the application works when deployed in different ways, and provides a clear delineation between locations where certain technology or design decisions must be made. By identifying the generic types of components that exist in most solutions, you can construct a meaningful map of an application or service, and then use this map as a blueprint for your design. 23

Lagerindelning Det finns normalt sett alltid minst tre typiska delar En del som möjliggör för användaren att interagera med systemet En del som hanterar affärslogiken Ser till att programmet gör rätt saker En del som möjliggör för systemet att minnas Presentationslagret This layer contains the user oriented functionality responsible for managing user interaction with the system generally consists of components that provide a common bridge into the core business logic encapsulated in the business layer 24

Affärs/Domänlagret This layer implements the core functionality of the system encapsulates the relevant business logic. It generally consists of components, some of which may expose service interfaces that other callers (e.g. the presentation layer) can use Datalagret This layer provides access to data hosted within the boundaries of the system, data exposed by other networked systems; perhaps accessed through services. 25

Define the Interfaces between Layers The primary goal of layers is to enforce loose coupling between layers a layer should not expose internal details on which another layer could depend the interface to a layer should be designed to minimize dependencies by providing a public interface that hides details of the components within the layer This hiding is called abstraction 26

Deplyment: N-Tier / 3-Tier Segregates functionality into separate segments in much the same way as the layered style, but with each segment being a tier located on a physically separate computer. Each tier is completely independent from all other tiers, except for those immediately above and below it. The nth tier only has to know how to handle a request from the n+1th tier, how to forward that request on to the n-1th tier (if there is one), and how to handle the results of the request Tiers vs Layers Tier usually means the physical deployment computer. An individual running server, or a server failover clustering, is one tier. Layer usually means logic software component grouped mainly by functionality Layer is used for software development purpose. Layer software implementation has many advantages and is a good way to achieve N-Tier architecture. Layer and tier may or may not exactly match each other. 27

Client/Server Segregates the system into two applications, the client makes requests to the server. The simplest form of client/server system involves a server application that is accessed directly by multiple clients, referred to as a 2-Tier architectural style Komponentbaserad arkitektur Focuses on the decomposition of the design into individual functional or logical components that expose well-defined communication interfaces containing methods, events, and properties. This provides a higher level of abstraction than object-oriented design principles, does not focus on issues such as communication protocols and shared state. 28

DESIGNMÖNSTER OCH -PRINCIPER Läsanvisningar Microsoft Application Architecture Guide (Patterns & Practices) Kapitel 1-5 + webbresurser Onlineresurser Länkar till onlineversioner av kursboken Application Architecture Knowledge Base (utgår från boken) GRASP-mönster Designmönster 29

The ultimate question Where does this go? User Presentation var apartments = from a in db.apartments where a.state == IL select a; Business Logic Data Access Logic Data Sources Responsibility Driven Design (RDD) Basic idea is to assign responsibilities to the software objects Two basic types of responsibility: Doing and Knowing Doing: doing something, creating an object, doing a calculation, initiate some action in another object, control activity between objects. Generate some activity Knowing: knowing about private encapsulated data, related objects, or things that can be derived or calculated May also have Collaboration, in which an object may collaborate with several other objects to fulfill a responsibility Note that responsibilities are not methods they are an abstraction but methods fulfill responsibilities RDD leads to thinking of the system as a community of collaborating objects, each with a set of responsibilities 61 30

GRASP GRASP = General Responsibility Assignment Software Patterns (or Principles) GRASP names and describes basic principles to assign responsibilities useful tool for RDD Provides patterns for assigning responsibilities What is a pattern? A principle or idiom used that provide guidance in the creation of software They have a name, describe a problem, and a solution to the problem Patterns can be applied in various circumstances, to numerous contexts Often these guide the assignment of responsibilities to objects A good pattern is a named and well known problem/solution pair that can be applied in new contexts Naming is important provides a way to identify the pattern Good patterns are usually the result of tried-and-true knowledge, i.e. solutions that have been applied many times before 62 More on GRASP GRASP defines 9 principles These are basic building blocks in OOD Creator Controller Information Expert Low Coupling (evaluative) High Cohesion (evaluative) Polymorphism Pure Fabrication Indirection Protected Variations Följande slides är baserade på C. Larman, Applying UML and Patterns, Pearson, 2005. 63 31

Creator Problem: Who should be responsible for creating a new instance of some class? Basic problem in design, so it s a good idea to have a general principle for deciding how to solve this (i.e., how to assign this responsibility) Solution: Assign class B the responsibility to create class A if one or more of the following is true: B contains or completely aggregates A B records A B closely uses A B has the initializing data for A that will be passed to A when it is created (B is an Expert with respect to creating A) 64 Example: Consider a Monopoly Game example. Who creates the Square object? 65 32

Creator First, note that this is a Domain Model, not a design class diagram (DCD) how do we get to the software classes? Look to the Domain Model for inspiration on what the software objects should be Notice that the Board conceptual class contains Squares this suggests a software class composition Board should create Squares, Squares are part of the Board, Board manages their creation and destruction (composition) 66 After reviewing the Domain Model diagram, we can conclude that a Board object would be a good creator for the Square object in our Design Model Note we also include an interaction diagram, so we can create the dynamic object model along with the static object model 67 33

Information Expert Problem: What is a basic principle for assigning responsibilities to objects? Solution: Assign a responsibility to the class that has the information needed to fulfill it. Example: Consider the Monopoly game. Suppose an object wants to reference an Square, given its name. Who is responsible for knowing the Square, given its name? Most likely candidate is the Board, because it is composed of Squares Since the Board is composed of Squares, it is the object that is best suited to produce a particular square given the square s name the Board is the Information Expert, it has all of the information needed to fulfill this responsibility See the next slide for how this translates into object design 68 69 34

Information Expert: How to Use Think of the objects in your design model as workers that you manage If you have a task to assign (a responsibility), who do you give it to? You give it to the person that has the best knowledge to do the task Occasionally the knowledge to do the task is spread over several objects Interact via several messages to do the work, but there is usually one object responsible for the completion of the task 70 Low Coupling Problem: How to support low dependency, low change impact, and increased reuse in your design? Solution: Assign responsibilities so that coupling remains low Coupling is a measure of how strongly one element is connected to, has knowledge of, or relies on other elements. Low coupling means less dependence on other objects This makes sense if a class with strong coupling is changed, it will affect many other classes, which makes for high change impact Consider the Monopoly Game: We assigned the getsquare responsibility to the Board, because it contains the Squares. What if we assigned it to another class, like Dog? Consider the following diagrams we have increased the coupling in our design, not a good idea 71 35

72 Low Coupling: Monopoly Example Note this adds another layer of complexity to the design model: First, Dog must get a list of all of the Squares from Board Only then can it access the Square it wants to satisfy the responsibility of finding the Square instance given its name Increased coupling now both Dog and Board are associated with Square Interaction diagram is a clue that this is not a good way to go Note that this is closely related to the Expert pattern Usually, the Expert is the best choice to fill the responsibility, because using another object will add coupling (the alternate object choice would probably need to be associated with the expert anyway) 73 36

Low Coupling: Observations Always good to reduce coupling in design decisions, but can t be the single factor In coding, coupling could mean: Having an attribute that refers to an instance of another object Calling services or methods of another object Referring to an instance of another object in a method Direct or indirect subclass Using an interface Low coupling is good independent objects lessen impact of change 74 GRASP Patterns: High Cohesion Problem: How to keep objects focused, understandable, and manageable, and as a result support Low Coupling? Solution: Assign a responsibility so that cohesion remains high. In other words, only assign strongly related responsibilities to an object. An element with highly related responsibilities that does not do a tremendous amount of work has high cohesion. Low cohesion classes: Complicated, hard to understand Hard to reuse Hard to maintain Brittle; easily affected by change 75 37

: Register : Sale makepayment() create() p : Payment addpayment( p ) : Register : Sale makepayment() makepayment() create() : Payment 76 High Cohesion: Observations High cohesion objects are useful when dealing with relational databases design separate classes to deal with different parts of the RDB In general, high cohesion classes usually have few methods with highly related functionality Collaborate with other objects to accomplish tasks Analogy: Avoid overloading one member of your team with too many responsibilities distribute the workload among experts, don t assign them unrelated activities This is similar to modular design High cohesion is related to low coupling bad cohesion leads to bad coupling, and viceversa 77 38

GRASP Patterns: Controller Problem: What first object beyond the User Interface layer receives and coordinates ( controls ) a system operation? Solution: Assign responsibility to a class representing one of the following choices: 1. Represents the overall system, a root object, a device that the software is running in, or a major subsystem (these are façade controllers) 2. Represents a use case scenario within which the system event occurs, often called a Handler, Coordinator, or Session. Use the same controller class for all system events in the same use case scenario. Note a session is a conversation between the system and an actor, and is often organized in terms of use cases System operations are operations that are performed as the result of a major system (input) event, like hitting Submit on a form or pressing the End Sale button in the POS A Controller is the first object (beyond any User Interface object) that is responsible for receiving or handling the event and generating the operation 78 GRASP Patterns: Controller Example During Analysis, could have a conceptual class called System that owns system operations but this may not directly translate to a similar class in design System endsale() enteritem() makenewsale() makepayment()... 79 39

GRASP Patterns: Controller Example presses button : Cashier actionperformed( actionevent ) UI Layer :SaleJFrame enteritem(itemid, qty) system operation message Domain Layer :??? Which class of object should be responsible for receiving this system event message? It is sometimes called the controller or coordinator. It does not normally do the work, but delegates it to other objects. The controller is a kind of "facade" onto the domain layer from the interface layer. 80 GRASP Patterns: Controller For the POS example, we could assign the operations of enteritem and endsale to the Register object, or we could create a POSSystem object, or create ProcessSaleHandler, ProcessSaleSession classes and assign the task of handling the system operations to them The Controller is a delegation principle; the Controller principle helps to summarize the choices the developer has to decide which Domain object will receive the work requests Choosing a handler for system events Make sure the controller you specify delegates the work, and does not do it itself. Think of the controller as being the team manager which delegates work to the experts Not a good idea to have the UI object directly delegate the work to the Domain Object this would lead to business logic being used in the UI Layer. 81 40

GRASP Patterns: Controller presses button Cashier actionperformed( actionevent ) UI Layer :SaleJFrame It is undesirable for an interface layer object such as a window to get involved in deciding how to handle domain processes. Business logic is embedded in the presentation layer, which is not useful. Domain Layer 1: makelineitem(itemid, qty) :Sale SaleJFrame should not send this message. 82 GRASP Patterns: Controller presses button : Cashier actionperformed( actionevent ) UI Layer :SaleJFrame system operation message 1: enteritem(itemid, qty) controller Domain Layer :Register 1.1: makelineitem(itemid, qty) :Sale 83 41

GRASP Patterns: Controller But do consider the cohesion of the controller Multiple access methods to domain object member data might be less useful than one to get the domain object. 84 Polymorphism Problem: How to handle alternatives based on type? How to create pluggable software components? Solution: When related alternatives or behaviors vary by type (or class), assign responsibilities for the behavior (using polymorphic operations) to the types for which the behavior varies. Polymorphism: Here it means giving the same name to services in different objects when services are similar or related. So for example, the different objects may implement a common interface or be members of the same super-class. 85 42

Polymorphism: Monopoly Example In Monopoly, there are different kinds of squares that require different behavior when landed on: Go square player receives $200 Income Tax square player must pay tax amount Go to Jail square player goes to the Jail Regular square nothing new happens right now, in more detailed use case player can buy or pay rent When designing the simulation application system, we must decide how to assign the responsibility of handling the system operation that occurs when a Player rolls the dice and lands on a square Note that although the Player always lands on a square, there are different behaviors depending upon Square type Avoid doing this as a Switch statement in the system too rigid. Use Polymorphism. 86 87 43

Polymorphism: Monopoly Example Here we have defined an abstract Square class with an abstract method called landedon(). We can then define subclasses for the types of Squares, and each can (using Polymorphism) define their own behaviors for the landedon() method. Note the Player only needs to be aware of the landedon() method name The Player knows the current location (Square) he/she is on, and the Player rolls the dice and gets the value The Player can then check with the Board to get the next square, and then use the landedon() method to initiate the behavior associated with that square. This is better than having the Player maintain a list of behaviors for each type of square and then having the Player implement the behavior See next slide for examples 88 89 44

Polymorphism: Observations Polymorphism is fundamental when designing a system for which a system operation may generate multiple variations of behavior (landedon()) Usually, this will result in the definition of interfaces or abstract classes Use interfaces to support polymorphism without creating a new class hierarchy In general, creating interfaces is more flexible, since you do not need to be a subclass of the super-class to implement the interface 90 Pure Fabrication Problem: If you do not want to violate High Cohesion and Low Coupling, what object should be assigned responsibility if the solutions offered by the Expert principle are not valid? Solution: Assign a highly cohesive set of responsibilities to an artificial or convenience class that does not represent a domain conceptual class i.e., create a new object that does not correspond to a domain object, but has high cohesion, low coupling, and is reusable. This allows us to make up new classes that are not implied by (or directly associated with) the Domain Model Often useful to collect responsibilities which simply cannot be assigned to existing objects in a good (high cohesion, low coupling) way 91 45

Pure Fabrication: Monopoly Example Currently, the Player rolls the dice (once for each die), gets the face value as a result of each roll, and computes the total Somewhat complicates the Player object, and the Dice object is not very reusable Can use Pure Fabrication to create a new class, Cup The Cup will be associated with the Dice object, and the Player will request that the Cup roll the dice and return the total The class Cup can be designed so that on instantiation the total number of die is set This class may then be used by other game systems, as is. 92 93 46

Indirection Problem: Where to assign a responsibility to avoid a direct coupling between two (or more) things? How to de-couple objects so that low coupling is supported and reuse potential remains high? Solution: Assign the responsibility to an intermediate object to mediate between other components or services so that they are not directly coupled. This is very related to Polymorphism and Pure Fabrication Essentially, create a go between or mediator class to insulate (protect) the inner design from external elements which may change 94 95 47

Protected Variations Problem: How to design objects, subsystems, and systems so that the variations or instability in these elements does not have an undesirable impact on other elements? Solution: Identify points of predicted variation or instability, assign responsibilities to create a stable interface around them One example: The Don t talk to strangers principle, which states that an object s methods should only send messages (i.e. use methods) of objects that it is directly familiar with Avoid a chain of method calls (foo.geta().getb().getc().getd()), because this traverses along the path of object connections to send a message to a distant object. Dangerous because of the possibility of change along the chain, which could easily break this design (further along you go, more likely something will change and so break) Related to Indirection, Polymorphism (the Tax Calculator example shows Indirection) 96 Gang of Four In 1994, four authors produced a book called Design Patterns (Gamma, Helm, Johnson, Vlissides) Described 23 patterns that are useful for OOD Considered the bible of design pattern books Often referred to as Gang of Four patterns, or GoF Patterns Många nya mönster har lagts till: Designmönster We will call the GRASP ideas principles and the GoF ideas patterns GRASP principles are more high level, general principles of object design GoF patterns are more concrete, solutions to specific problems in object design 97 48

Design Patterns as Problem Solution Pairs Conceptually, a design pattern provides a mapping from a specific design problem to a generic solution Design Patterns Defined [Cont.] Knowledge of design patterns simplifies software design by reducing the number of design problems that have to be solved from first principles. Design problems that match documented design patterns, have ready-made solutions. The remaining problems that don't match documented design patterns must be solved from first principles. 49

Code Design Design Pattern The following will be familiar to anyone who has written a GUI program in C#: Code Design Design Pattern Likewise, the following will be familiar to anyone who has written a GUI program in Java: 50

Code Design Design Pattern In each case, an event handler or callback routine is registered to handle button click events. Each implementation is unique, but in both cases the design is the same. Code Design Design Pattern In both cases the general design problem is how to allow one or more objects (those containing the event handling routines) to be notified when the state of another object (the button) changes. This is a routine design problem for which there exists a reusable solution in the form of the Observer design pattern. 51

Observer Intent The Observer design pattern defines a one-to-many relationship between a subject object and any number of observer objects such that when the subject object changes, observer objects are notified and given a chance to react to changes in the subject. Solution Static Structure 52

Solution Dynamic Behavior Solution with common base class for subjects 53

Vad har vi lärt oss? Systemarkitekturer Vad innebär systemarkitektur? Lagerindelning UI, domän, data Mönster och stilar Client/server, domändriven Designmönster GRASP Creator Controller Information Expert Low Coupling High Cohesion Polymorphism Pure Fabrication Indirection Protected Variations GoF Observer Varför bry sig? Software must be built on a solid foundation Poor architecture may result in software that is unstable, unable to support existing or future business requirements, difficult to deploy or manage in a production environment 54