הנדסת תוכנה- הרצאה 7

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Design and Implementation

Faculty of Engineering, Bar-Ilan University

Software design and implementation is the stage in the software engineering process at which an executable software system is developed Software design and implementation activities are invariably inter-leaved
Software design is a creative activity in which you identify software components and their relationships, based on a customers requirements Implementation is the process of realizing the design as a program

Slides are based on slides by Ian Sommerville, by Mira Balaban and by Peter Bunus

In a wide range of domains, it is now possible to buy commercial-off-the-shelf (COTS) systems that can be adapted and tailored to the users requirements
For example, if you want to implement a medical records system, you can buy a package that is already used in hospitals. It can be cheaper and faster to use this approach rather than developing a system in a conventional programming language

When you develop an application in this way, the design process becomes concerned with how to use the configuration features of that system to deliver the system requirements

Structured object-oriented design processes involve developing a number of different system models They require a lot of effort for development and maintenance of these models and, for small systems, this may not be cost-effective However, for large systems developed by different groups design models are an important communication mechanism

There are a variety of different object-oriented design processes that depend on the organization using the process Common activities in these processes include:
Define the context and models of use of the system Design the system architecture Identify the principal system objects Develop design models Specify object interfaces

1 1

Control system

1 1..n

Weather Information system


1

1..n

Weather station
1..n

Process illustrated here using a design for a wilderness weather station

Satellite

Report weather Report status

System Use case Actors Description

Weather station Report weather Weather information system, Weather station The weather station sends a summary of the weather data that has been collected from the instruments in the collection period to the weather information system. The data sent are the maximum, minimum, and average ground and air temperatures; the maximum, minimum, and average air pressures; the maximum, minimum, and average wind speeds; the total rainfall; and the wind direction as sampled at five-minute intervals. The weather information system establishes a satellite communication link with the weather station and requests transmission of the data. The summarized data is sent to the weather information system. Weather stations are usually asked to report once per hour but this frequency may differ from one station to another and may be modified in the future.
8

Weather information system

Restart Shut down

Reconfigure

Stimulus

Control system

Power save Remote control


7

Response Comments

Once interactions between the system and its environment have been understood, you use this information for designing the system architecture You identify the major components that make up the system and their interactions, and then may organize the components using an architectural pattern such as a layered or client-server model The weather station is composed of independent subsystems that communicate by broadcasting messages on a common infrastructure

subsystem Fault manager

subsystem Configuration manager

subsystem Power manager

Communication link

subsystem Communications

subsystem Data collection

subsystem Instruments

10

Data collection

Transmitter

Receiver

Weather data

Identifying object classes is often a difficult part of object oriented design There is no 'magic formula' for object identification. It relies on the skill, experience and domain knowledge of system designers Object identification is an iterative process. You are unlikely to get it right first time

11

12

Use a grammatical approach based on a natural language description of the system (used in Hood OOD method) Base the identification on tangible things in the application domain Use a behavioural approach and identify objects based on what participates in what behaviour Use a scenario-based analysis. The objects, attributes and methods in each scenario are identified

A weather station is a package of software controlled instruments which collects data, performs some data processing and transmits this data for further processing. The instruments include air and ground thermometers, an anemometer, a wind vane, a barometer and a rain gauge. Data is collected periodically. When a command is issued to transmit the weather data, the weather station processes and summarises the collected data. The summarised data is transmitted to the mapping computer when a request is received.
13 14

Object class identification in the weather station system may be based on the tangible hardware and data in the system:
Ground thermometer, Anemometer, Barometer Application domain objects that are hardware objects related to the instruments in the system Weather station The basic interface of the weather station to its environment. It therefore reflects the interactions identified in the use-case model Weather data Encapsulates the summarized data from the instruments

WeatherStation Identifier reportWeather() ReportStatus() powerSave(instruments) remoteControl(commands) reconfigure(commands) restart(instruments) shutdown(instruments)

WeatherData airtTemperatures groundTemperatures windSpeeds windDirections Pressures rainfall collect() summarize()

Ground thermometer gt_Ident temperature get() Test()

Anemometer an_Ident windSpeed windDirection get() Test()

Barometer bar_Ident pressure height get() Test()

15

16

Design models show the objects and object classes and relationships between these entities Static models describe the static structure of the system in terms of object classes and relationships Dynamic models describe the dynamic interactions between objects

17

18

State diagrams are used to show how objects respond to different service requests and the state transitions triggered by these requests State diagrams are useful high-level models of a system or an objects run-time behavior You dont usually need a state diagram for all of the objects in the system. Many of the objects in a system are relatively simple and a state model adds unnecessary detail to the design

Controlled

shutdown()

Operation

remoteControl()

Shutdown

restart()

reportStatus()

Running
transmission done

Testing
test complete

configuration done reconfigure() powerSave()

Transmitting
clock collection done reportWeather() weather summary complete

Configuring summarizing Collecting

19

20

Object interfaces have to be specified so that the objects and other components can be designed in parallel Designers should avoid designing the interface representation but should hide this in the object itself Objects may have several interfaces which are viewpoints on the methods provided The UML uses class diagrams for interface specification but Java may also be used

interface Reporting weatherReport(WS-Ident):Wreport statusReport(WS-Ident):Sreport

interface Remote Control startInstrument(instrument):iStatus stopInstrument(instrument):iStatus collectData(instrument):iStatus provideData(instrument):iStatus

21

22

A design pattern is a way of reusing abstract knowledge about a problem and its solution A pattern is a description of the problem and the essence of its solution It should be sufficiently abstract to be reused in different settings Pattern descriptions usually make use of object-oriented characteristics such as inheritance and polymorphism

Name
A meaningful pattern identifier

Problem description Solution description


Not a concrete design but a template for a design solution that can be instantiated in different ways

Consequences
The results and trade-offs of applying the pattern

23

24

Name
Observer

Pattern name Description

Observer Separates the display of the state of an object from the object itself and allows alternative displays to be provided. When the object state changes, all displays are automatically notified and updated to reflect the change. In many situations, you have to provide multiple displays of state information, such as a graphical display and a tabular display. Not all of these may be known when the information is specified. All alternative presentations should support interaction and, when the state is changed, all displays must be updated. This pattern may be used in all situations where more than one display format for state information is required and where it is not necessary for the object that maintains the state information to know about the specific display formats used.

Description
Separates the display of object state from the object itself

Problem description
Used when multiple displays of state are needed

Solution description
See slide with UML description

Problem description

Consequences
Optimisations to enhance display performance are impractical

25

26

Pattern name
Solution description

Observer
This involves two abstract objects, Subject and Observer, and two concrete objects, ConcreteSubject and ConcreteObject, which inherit the attributes of the related abstract objects. The abstract objects include general operations that are applicable in all situations. The state to be displayed is maintained in ConcreteSubject, which inherits operations from Subject allowing it to add and remove Observers (each observer corresponds to a display) and to issue a notification when the state has changed. The ConcreteObserver maintains a copy of the state of ConcreteSubject and implements the Update() interface of Observer that allows these copies to be kept in step. The ConcreteObserver automatically displays the state and reflects changes whenever the state is updated.

Subject

Consequences

The subject only knows the abstract Observer and does not know details of the concrete class. Therefore there is minimal coupling between these objects. Because of this lack of knowledge, optimizations that enhance display performance are impractical. Changes to the subject may cause a set of linked updates to observers to be generated, some of which may not be necessary.
27 28

Subject Attach(Observer) Detach(observer) Notify()

Observer Update() for all o in observers o->Update()

To use patterns in your design, you need to recognize that any design problem you are facing may have an associated pattern that can be applied
Tell several objects that the state of some other object has changed (Observer pattern) Tidy up the interfaces to a number of related objects that have often been developed incrementally (Faade pattern) Provide a standard way of accessing the elements in a collection, irrespective of how that collection is implemented (Iterator pattern) Allow for the possibility of extending the functionality of an existing class at run-time (Decorator pattern)

ConcreteSubject GetState() subjectState return subjectState

ConcreteObserver Update() observerState observerState= subject->GetState()

29

30

Focus here is not on programming, although this is obviously important, but on other implementation issues that are often not covered in programming texts:
Reuse Most modern software is constructed by reusing existing components or systems. When you are developing software, you should use as much existing code as possible Configuration management During the development process, you have to keep track of the many different versions of each software component in a configuration management system Host-target development Production software does not usually execute on the same computer as the software development environment. Rather, you develop it on one computer (the host system) and execute it on a separate computer (the target system)

From the 1960s to the 1990s, most new software was developed from scratch, by writing all code in a high-level programming language
The only significant reuse or software was the reuse of functions and objects in programming language libraries

Costs and schedule pressure mean that this approach became increasingly unviable, especially for commercial and Internet-based systems An approach to development based around the reuse of existing software emerged and is now generally used for business and scientific software

31

32

The abstraction level


At this level, you dont reuse software directly but use knowledge of successful abstractions in the design of your software

The object level


At this level, you directly reuse objects from a library rather than writing the code yourself

The component level


Components are collections of objects and object classes that you reuse in application systems

The system level


At this level, you reuse entire application systems

The costs of the time spent in looking for software to reuse and assessing whether or not it meets your needs Where applicable, the costs of buying the reusable software. For large off-the-shelf systems, these costs can be very high The costs of adapting and configuring the reusable software components or systems to reflect the requirements of the system that you are developing The costs of integrating reusable software elements with each other (if you are using software from different sources) and with the new code that you have developed
33 34

Configuration management is the name given to the general process of managing a changing software system The aim of configuration management is to support the system integration process so that all developers can access the project code and documents in a controlled way, find out what changes have been made, and compile and link components to create a system

Version management, where support is provided to keep track of the different versions of software components. Version management systems include facilities to coordinate development by several programmers System integration, where support is provided to help developers define what versions of components are used to create each version of a system. This description is then used to build a system automatically by compiling and linking the required components Problem tracking, where support is provided to allow users to report bugs and other problems, and to allow all developers to see who is working on these problems and when they are fixed

35

36

Most software is developed on one computer (the host), but runs on a separate machine (the target) More generally, we can talk about a development platform and an execution platform
A platform is more than just hardware. It includes the installed operating system plus other supporting software such as a database management system or, for development platforms, an interactive development environment

Development platform usually has different installed software than execution platform; these platforms may have different architectures
37

An integrated compiler and syntax-directed editing system that allows you to create, edit and compile code A language debugging system Graphical editing tools, such as tools to edit UML models Testing tools, such as Junit that can automatically run a set of tests on a new version of a program Project support tools that help you organize the code for different development projects
38

Software development tools are often grouped to create an integrated development environment An IDE is a set of software tools that supports different aspects of software development, within some common framework and user interface IDEs are created to support development in a specific programming language such as Java. The language IDE may be developed specially, or may be an instantiation of a general-purpose IDE, with specific language-support tools

If a component is designed for a specific hardware architecture, or relies on some other software system, it must obviously be deployed on a platform that provides the required hardware and software support High availability systems may require components to be deployed on more than one platform. This means that, in the event of platform failure, an alternative implementation of the component is available If there is a high level of communications traffic between components, it usually makes sense to deploy them on the same platform or on platforms that are physically close to one other. This reduces the delay between the time a message is sent by one component and received by another
39 40

Open source development is an approach to software development in which the source code of a software system is published and volunteers are invited to participate in the development process Its roots are in the Free Software Foundation (www.fsf.org), which advocates that source code should not be proprietary but rather should always be available for users to examine and modify as they wish Open source software extended this idea by using the Internet to recruit a much larger population of volunteer developers. Many of them are also users of the code
41

The best-known open source product is, of course, the Linux operating system which is widely used as a server system and, increasingly, as a desktop environment Other important open source products are Java, the Apache web server and the mySQL database management system

42

Should the product that is being developed make use of open source components? Should an open source approach be used for the softwares development?

More and more product companies are using an open source approach to development Their business model is not reliant on selling a software product but on selling support for that product They believe that involving the open source community will allow software to be developed more cheaply, more quickly and will create a community of users for the software

43

44

A fundamental principle of open-source development is that source code should be freely available, this does not mean that anyone can do as they wish with that code
Legally, the developer of the code (either a company or an individual) still owns the code. They can place restrictions on how it is used by including legally binding conditions in an open source software license Some open source developers believe that if an open source component is used to develop a new system, then that system should also be open source Others are willing to allow their code to be used without this restriction. The developed systems may be proprietary and sold as closed source systems

The GNU General Public License (GPL). This is a socalled reciprocal license that means that if you use open source software that is licensed under the GPL license, then you must make that software open source The GNU Lesser General Public License (LGPL) is a variant of the GPL license where you can write components that link to open source code without having to publish the source of these components The Berkley Standard Distribution (BSD) License. This is a non-reciprocal license, which means you are not obliged to re-publish any changes or modifications made to open source code. You can include the code in proprietary systems that are sold

45

46

Establish a system for maintaining information about open-source components that are downloaded and used Be aware of the different types of licenses and understand how a component is licensed before it is used Be aware of evolution pathways for components Educate people about open source Have auditing systems in place Participate in the open source community
47

Iterator State Singelton Strategy Template Method Visitor Chain of Responsibility Command Interpreter Mediator Memento

48

Accessing the elements of an aggregate object without exposing its internal structure Traverse the aggregate in different ways, depending on needs Do not want to bloat the aggregate interface with operations for different traversals, even if they can be anticipated Need to have more than one traversal pending on the same aggregate

Key idea: Take the responsibility for access and traversal out of the aggregate object and put it into an Iterator object.

The list objects are responsible for creating their corresponding iterator
49 50

use Iterator to allow clients to iterate through the Files in a Directory


without exposing Directorys internal structure to the client
interface Iterator { public void first(); public void next(); public boolean isDone(); public Object current(); } // // // // set to first advance is done get current

class Directory extends Node { ... public Iterator iterator(){ return new DirectoryIterator(this); } // use a private inner class because: // - it is not visible outside the class // - its methods have access to Directorys // private field _children private class DirectoryIterator implements Iterator { private Vector _files; private int _fileCnt; DirectoryIterator(Directory d){ _files = d._children; _fileCnt = 0; } ...
51 52

public void first(){ _fileCnt = 0; } public void next(){ _fileCnt++; } public boolean isDone(){ return _fileCnt == _files.size(); } public Object current(){ return _files.elementAt(_fileCnt); } } }

public class Main { public static void main(String[] args){ Directory root = new Directory(""); File core = new File("core", root, "hello"); Directory usr = new Directory("usr", root); File adm = new File("adm", usr, "there"); Directory foo = new Directory("foo", usr); File bar1 = new File("bar1", foo, "abcdef"); File bar2 = new File("xbar2", foo, "abcdef"); File bar3 = new File("yybarzz3", foo, "abcdef"); // use iterator to print contents of /usr Iterator it = usr.iterator(); for (it.first(); !it.isDone(); it.next()){ Node n = (Node)it.current(); System.out.println(n.getAbsoluteName()); } } }
53 54

/usr/adm /usr/foo/

TCPConnection that represents a network


connection. A TCPConnection object can be in one of several different states: Established,

Listening, Closed Problem: A TCPConnection object responds


differently to requests, depending on its current state

55

56

Key idea: Introduce an abstract class TCPState to represent the states of the network connection
1

Context
defines interface of interest to clients maintains reference to a ConcreteState subclass that defines the current state

State
defines an interface for encapsulating the behavior associated with a particular state of the

Context

ConcreteState subclasses
each subclass implements a behavior associate with a state of the Context (by overriding methods in State)

57

58

Allow an object to change its behavior when its internal state changes use State when:
an objects behavior depends on its state operations have large conditional statements that depend on the objects state (the state is usually represented by one or more enumerated constants)

59

60

example of a vending machine:


product price is $0.25 machine accepts any combination of nickels, dimes, and quarters customer enters coins; when credit reaches $0.25 product is dispensed, and refund is given for the remaining credit machine has a display that shows the current balance

61

62

use integers to represent the states


more complex states may require objects and enumerated types

methods addNickel(), addDime(), and addQuarter() to model user actions methods refund(), displayBalance(), and dispenseProduct() to model systems actions conditional logic (with if/switch statements) depending on current state
63

class TraditionalVendingMachine { private int _balance; public TraditionalVendingMachine() { _balance = 0; welcome(); } void welcome() { System.out.println("Welcome. Please enter $0.25 to buy product."); } void dispenseProduct() { System.out.println("dispensing product..."); } void displayBalance() { System.out.println("balance is now: " + _balance); } void refund(int i) { int System.out.println("refunding: " + i); } ...

64

public void addNickel() { switch (_balance) { case 0 : _balance = 5; displayBalance(); break; break case 5 : _balance = 10; displayBalance(); break; break case 10 :_balance = 15; displayBalance(); break; break case 15 :_balance = 20; displayBalance(); break; break case 20 :dispenseProduct(); _balance = 0; welcome(); } }

65

public void addDime() { switch (_balance) { case 0 :_balance = 10; displayBalance(); break; break case 5 :_balance = 15; displayBalance(); break; break case 10 :_balance = 20; displayBalance(); break; break case 15 :dispenseProduct(); _balance = 0; welcome(); break; break case 20 :dispenseProduct(); refund(5); _balance = 0; welcome(); } }

66

public class Client { public static void main(String[] args) { VendingMachine v = new VendingMachine(); v.addNickel(); v.addDime(); v.addNickel(); v.addQuarter(); } }

state-specific behavior scattered over different conditionals


changing one states behavior requires visiting each of these

inflexible: adding a state requires invasive change (editing each conditional) approach tends to lead to large monolithic classes
not clear how to partition functionality

67

68

interface VendingMachineState { public void addNickel(VendingMachine v); public void addDime(VendingMachine v); public void addQuarter(VendingMachine v); public int getBalance(); }

class Credit0 implements VendingMachineState { private Credit0(){ } private static Credit0 _theInstance; static Credit0 instance(VendingMachine v) { null) if (_theInstance == null { _theInstance = new Credit0(); } v.welcome(); return _theInstance; } public void addNickel(VendingMachine v) { v.changeState(Credit5.instance()); } public void addDime(VendingMachine v) { v.changeState(Credit10.instance()); } public void addQuarter(VendingMachine v) { v.dispenseProduct(); v.changeState(Credit0.instance(v)); } public int getBalance() { return 0; } }
69 70

class Credit10 implements VendingMachineState { private Credit10(){ } private static Credit10 _theInstance; static Credit10 instance(){ null){ if (_theInstance == null _theInstance = new Credit10(); } return _theInstance; } public void addNickel(VendingMachine v) { v.changeState(Credit15.instance()); } public void addDime(VendingMachine v) { v.changeState(Credit20.instance()); } public void addQuarter(VendingMachine v) { v.dispenseProduct(); v.refund(10); v.changeState(Credit0.instance(v)); } public int getBalance(){ return 10; } }
71

public class VendingMachine { public VendingMachine() { _state = Credit0.instance(this this); this } // methods welcome(), dispenseProduct() etc. // same as before void changeState(VendingMachineState s) { _state = s; displayBalance(); } this); public void addNickel() { _state.addNickel(this } this this); public void addDime() { _state.addDime(this } this this); public void addQuarter() { _state.addQuarter(this } this private VendingMachineState _state; }

72

localizes state-specific behavior, and partitions behavior for different states


leads to several small classes instead of one large class natural way of partitioning the code

avoids (long) if/switch statements with statespecific control flow


also more extensible---you dont have to edit your switch statements after adding a new state

makes state transitions explicit


simply create a new ConcreteState object, and assign it to the state field in Context

state-objects can be shared


and common functionality can be placed in abstract class

State

73

You might also like