Page 1 of 9 Q1. [8 Marks] Intra-Method Control Flow: Draw A

Total Page:16

File Type:pdf, Size:1020Kb

Page 1 of 9 Q1. [8 Marks] Intra-Method Control Flow: Draw A Page 1 of 9 Q1. [8 marks] Intra-Method Control Flow: Draw a flowchart for the following method: public void countLengths(List<String> data) { for (String next : data) { if (next != null) { if (next.length() > CUT_OFF) { large = large + next.length(); } else { small = small + next.length(); } } } } start hasNext String? F T next != null F T next.length() F > CUT_OFF? T s = s + next.length() l = l + next.length() stop Page 2 of 9 Note: Question 2 refers to the JetUML project checked out of the repository. Be careful not to make any changes to this code! Q2. [12 marks] Sequence Diagram: Draw a sequence diagram to represent a call to the getCallees() method of the CallNode class in the graph package of the JetUML system. Include only the first level of calls to the Java library. Do not include arguments to methods. Assume that any for-each loop that you encounter iterates over a collection of size 2. CN: CallNode AL: ArrayList G: Graph E: Edge cn:CN callees:AL pGraph:G e1:E e2:E getCallees new ArrayList getEdges getStart getEnd add getStart getEnd add Page 3 of 9 Q3. [6 marks] The Liskov Substitution Principle Consider the following specification for a method that belongs to a class named ColourChooser: // REQUIRES: c is one of: "red", "green", "blue", "black", "white" // MODIFIES: this // EFFECTS: colour is set to c public void setColour(String c) { // implementation not important } Now suppose we override this method in a subclass BWColourChooser and give it the following specification: // REQUIRES: c is one of: "black", "white" // MODIFIES: this // EFFECTS: colour is set to c @Override public void setColour(String c) { // implementation not important } Will an instance of BWColourChooser be substitutable for an instance of ColourChooser? In other words, can you replace an instance of ColourChooser with an instance of BWColourChooser? You must provide an answer in the context of the Liskov Substitution Principle. Answers of the form "yes, because the postcondition has been strengthened" are not sufficient – you must state why the postcondition has been strengthened. No. You cannot replace an instance of ColourChooser with an instance of BWColourChooser. The Liskov Substitution Principle (LSP) requires that when overriding a method in a subclass, the precondition is weakened (or remains the same) and the postcondition is strengthened (or remains the same). In the case of setColour, the precondition is strengthened in the subclass. It is strengthened because it specifies a more restrictive set of values then the precondition in the superclass. The precondition in the superclass allows the colour to be any one of "red", "green", "blue", "black", "white" whereas as the corresponding precondition in the subclass restricts the colour to be only one of "black" or "white". Page 4 of 9 Note: Question 4 refers to the JetUML project checked out of the repository. You must not modify the code in this system in any way while answering this question. In particular, you must not add any code whatsoever. Q4. [8 marks] Type Hierarchies Below you will find a type hierarchy that includes some of the types in the graph package of the JetUML system. Use it to help you answer the questions on the following page. «interface» Edge «abstract» AbstractEdge «abstract» ShapeEdge «abstract» NoteEdge StateTransitionEdge SegmentedLineEdge ReturnEdge CallEdge ClassRelationshipEdge Page 5 of 9 For each group of statements marked (i) through (iv) below, put a check-mark ✔ alongside if every statement in the group will compile, otherwise put a cross ✗. In the case where a group of statements does not compile, you must explain why – it is sufficient to provide only one valid reason for each group of statements. No marks will be awarded for the cross ✗ alone. Note that these statements involve the types shown in the type hierarchy on the previous page. Remember: you must not add any code to the system. In particular, you must not type any of the code below into IntelliJ. (i) SegmentedLineEdge edge = new SegmentedLineEdge(); edge.setStartLabel("*"); ✗ SegmentedLineEdge is an abstract class and therefore cannot be instantiated. (ii) SegmentedLineEdge slEdge = new CallEdge(); slEdge.setSignal(true); ✗ We cannot call setSignal on an object whose apparent type is SegmentedLineEdge as this method is not specified for that type. (iii) Edge e = new ReturnEdge(); Node start = e.getStart(); ✔ (iv) CallEdge cEdge = new ReturnEdge(); ArrayList<Point> pts = cEdge.getPoints(); ✗ ReturnEdge is not a subclass of CallEdge, so we cannot assign an instance of ReturnEdge to a variable declared to be of type CallEdge. Page 6 of 9 Note: Question 5 refers to the ShoppingList project checked out of the repository. Q5. [18 marks] Data Abstraction: Implementation Complete the implementation of the ShoppingList class by providing an implementation for the constructor and the four methods specified in this class. Note that a field has been provided for you – use it! You should not have to add any other fields. You do not need to make any changes to the ShoppingItem class but you should take time to familiarize yourself with its specification. Note that tests have been provided for you – do not modify them! If you implement the class according to its specification, the given tests will pass. Feel free to develop your code using IntelliJ but you must copy your answer onto this exam paper before the end of the exam. Note: • headers for the constructor and methods have been provided for you – you just need to fill in the body • it is not necessary to copy the comment statements • note that we have provided more space than you are likely to need. public ShoppingList() { items = new LinkedList<ShoppingItem>(); } public void addItem(ShoppingItem item) { items.add(item); } public boolean hasItem(ShoppingItem item) { return items.contains(item); } Page 7 of 9 public int getTotalCostOfItems() { int cost = 0; for(ShoppingItem next : items) { cost += next.getCost(); } return cost; } public int countNumberOfItemsWithCostInRange(int low, int high) { int count = 0; for (ShoppingItem next : items) { if (next.getCost() > low && next.getCost() < high) { count++; } } return count; } Page 8 of 9 Note: Question 6 refers to the Roadstar project checked out of the repository. Q6. [12 marks] Testing Robust Classes Carefully read the specification of the methods in the Car class. In this question you will be asked to design tests for the drive method. Note that a CarTest class has been provided for you. Use this class to design your tests and be sure to copy your answer onto this exam paper before the end of the exam. You must assume that the runBefore method runs before each of your tests. Do not add fields to the CarTest class and do not modify the runBefore method. If you need to declare additional variables, you must declare them locally in your test method. a) Design a jUnit test method that tests the implementation of the drive method when the car is driven a distance that is less than Car.SERVICE_DISTANCE @Test public void testDriveRegular() throws ServiceException { testCar.drive(Car.SERVICE_DISTANCE / 2); assertEquals(Car.SERVICE_DISTANCE / 2, testCar.getDistanceSinceLastService()); assertFalse(testCar.needsService()); } b) Design a jUnit test method that tests the implementation of the drive method when the method is called twice on the same car object and the total distance travelled is less than Car.SERVICE_DISTANCE @Test public void testAccumulateDistance() throws ServiceException { testCar.drive(Car.SERVICE_DISTANCE / 4); testCar.drive(Car.SERVICE_DISTANCE / 4); assertEquals(Car.SERVICE_DISTANCE / 2, testCar.getDistanceSinceLastService()); assertFalse(testCar.needsService()); } Page 9 of 9 c) Design a jUnit test method that tests the implementation of the drive method when the car is driven a distance that is at least Car.SERVICE_DISTANCE with a single call to the drive method. @Test public void testServiceDistance() throws ServiceException { testCar.drive(Car.SERVICE_DISTANCE); assertEquals(Car.SERVICE_DISTANCE, testCar.getDistanceSinceLastService()); assertTrue(testCar.needsService()); } d) Design a jUnit test method that tests the implementation of the drive method when a call to the method is expected to produce a ServiceException. @Test (expected = ServiceException.class) public void testDriveNeedsService() throws ServiceException { testCar.drive(Car.SERVICE_DISTANCE); testCar.drive(1); } .
Recommended publications
  • 07 Requirements What About RFP/RFB/Rfis?
    CMPSCI520/620 07 Requirements & UML Intro 07 Requirements SW Requirements Specification • Readings • How do we communicate the Requirements to others? • [cK99] Cris Kobryn, Co-Chair, “Introduction to UML: Structural and Use Case Modeling,” UML Revision Task Force Object Modeling with OMG UML Tutorial • It is common practice to capture them in an SRS Series © 1999-2001 OMG and Contributors: Crossmeta, EDS, IBM, Enea Data, • But an SRS doesn’t need to be a single paper document Hewlett-Packard, IntelliCorp, Kabira Technologies, Klasse Objecten, Rational Software, Telelogic, Unisys http://www.omg.org/technology/uml/uml_tutorial.htm • Purpose • [OSBB99] Gunnar Övergaard, Bran Selic, Conrad Bock and Morgan Björkande, “Behavioral Modeling,” UML Revision Task Force, Object Modeling with OMG UML • Contractual requirements Tutorial Series © 1999-2001 OMG and Contributors: Crossmeta, EDS, IBM, Enea elicitation Data, Hewlett-Packard, IntelliCorp, Kabira Technologies, Klasse Objecten, Rational • Baseline Software, Telelogic, Unisys http://www.omg.org/technology/uml/uml_tutorial.htm • for evaluating subsequent products • [laM01] Maciaszek, L.A. (2001): Requirements Analysis and System Design. • for change control requirements Developing Information Systems with UML, Addison Wesley Copyright © 2000 by analysis Addison Wesley • Audience • [cB04] Bock, Conrad, Advanced Analysis and Design with UML • Users, Purchasers requirements http://www.kabira.com/bock/ specification • [rM02] Miller, Randy, “Practical UML: A hands-on introduction for developers,”
    [Show full text]
  • OMG Systems Modeling Language (OMG Sysml™) Tutorial 25 June 2007
    OMG Systems Modeling Language (OMG SysML™) Tutorial 25 June 2007 Sanford Friedenthal Alan Moore Rick Steiner (emails included in references at end) Copyright © 2006, 2007 by Object Management Group. Published and used by INCOSE and affiliated societies with permission. Status • Specification status – Adopted by OMG in May ’06 – Finalization Task Force Report in March ’07 – Available Specification v1.0 expected June ‘07 – Revision task force chartered for SysML v1.1 in March ‘07 • This tutorial is based on the OMG SysML adopted specification (ad-06-03-01) and changes proposed by the Finalization Task Force (ptc/07-03-03) • This tutorial, the specifications, papers, and vendor info can be found on the OMG SysML Website at http://www.omgsysml.org/ 7/26/2007 Copyright © 2006,2007 by Object Management Group. 2 Objectives & Intended Audience At the end of this tutorial, you should have an awareness of: • Benefits of model driven approaches for systems engineering • SysML diagrams and language concepts • How to apply SysML as part of a model based SE process • Basic considerations for transitioning to SysML This course is not intended to make you a systems modeler! You must use the language. Intended Audience: • Practicing Systems Engineers interested in system modeling • Software Engineers who want to better understand how to integrate software and system models • Familiarity with UML is not required, but it helps 7/26/2007 Copyright © 2006,2007 by Object Management Group. 3 Topics • Motivation & Background • Diagram Overview and Language Concepts • SysML Modeling as Part of SE Process – Structured Analysis – Distiller Example – OOSEM – Enhanced Security System Example • SysML in a Standards Framework • Transitioning to SysML • Summary 7/26/2007 Copyright © 2006,2007 by Object Management Group.
    [Show full text]
  • PART 3: UML Dynamic Modelling Notations • State Machines/Statecharts • Collaboration Diagrams • Sequence Diagrams • Activity Diagrams
    PART 3: UML Dynamic Modelling Notations • State machines/statecharts • Collaboration diagrams • Sequence diagrams • Activity diagrams. Chapter 19 of the textbook is relevant to this part. 1 State machines • State machines describe dynamic behaviour of objects, show life history of objects over time + object communications. • Used for real-time system design (eg., robotics); GUI design (states represent UI screens/modes). Example shows simple state machine with two states, On and Off and transitions between them. 2 Switch Off swon swoff On Simple state machine 3 State machines Elements of a state machine are: States: Rounded-corner boxes, containing state name. Transitions: Arrows from one state, source of transition, to another, target, labelled with event that causes transition. Default initial state: State of object at start of its life history. Shown as target of transition from initial pseudostate (black filled circle). Termination of state machine can be shown by `bullseye' symbol. 4 State machines UML divides state machines into two kinds: 1. Protocol state machines { describe allowed life histories of objects of a class. Events on transitions are operations of that class, transitions may have pre and post conditions. Transitions cannot have generated actions (although we will allow this). 2. Behaviour state machines { describe operation execution/implementation of object behaviour. Transitions do not have postconditions, but can have actions. State machines describe behaviour of objects of a particular class, or execution processing of an operation. 5 State machines • Class diagrams describe system data, independently of time. • State machines show how system/objects can change over time. • Switch state machine is protocol state machine for objects of Switch class.
    [Show full text]
  • UML Tutorial: Sequence Diagrams
    UML Tutorial: Sequence Diagrams. Robert C. Martin Engineering Notebook Column April, 98 In my last column, I described UML Collaboration diagrams. Collaboration diagrams allow the designer to specify the sequence of messages sent between objects in a collaboration. The style of the diagram emphasizes the relationships between the objects as opposed to the sequence of the messages. In this column we will be discussing UML Sequence diagrams. Sequence diagrams contain the same information as Collaboration diagrams, but emphasize the sequence of the messages instead of the relationships between the objects. The Cellular Phone Revisited Here again is the final collaboration diagram from last column’s Cellular Phone example. (See Figure 1.) 1*:ButtonPressed() :DigitButton Digit:Button 1.1:Digit(code) Adapter 2:ButtonPressed() :SendButton Send:Button :Dialler Adapter 2.1:Send() 1.1.2:EmitTone(code) 2.1.1:Connect(pno) 1.1.1:DisplayDigit(code) 2.1.1.1:InUse() :Cellular display display:Dialler :Speaker Radio :CRDisplay Display Figure 1: Collaboration diagram of Cellular Phone. The Sequence diagram that corresponds to this model is shown in Figure 2. It is pretty easy to see what the diagrams in Figure 2 are telling us, especially when we compare them to Figure 1. Let’s walk through the features. First of all, there are two sequence diagrams present. The first one captures the course of events that takes place when a digit button is pressed. The second captures what happens when the user pushes the ‘send’ button in order to make a call. At the top of each diagram we see the rectangles that represent objects.
    [Show full text]
  • Interface Types for Haskell
    Interface Types for Haskell Peter Thiemann and Stefan Wehr Institut f¨urInformatik, Universit¨atFreiburg, Germany {thiemann,wehr}@informatik.uni-freiburg.de Abstract. Interface types are a useful concept in object-oriented pro- gramming languages like Java or C#. A clean programming style advo- cates relying on interfaces without revealing their implementation. Haskell’s type classes provide a closely related facility for stating an in- terface separately from its implementation. However, there are situations in which no simple mechanism exists to hide the identity of the imple- mentation type of a type class. This work provides such a mechanism through the integration of lightweight interface types into Haskell. The extension is non-intrusive as no additional syntax is needed and no existing programs are affected. The implementation extends the treat- ment of higher-rank polymorphism in production Haskell compilers. 1 Introduction Interfaces in object-oriented programming languages and type classes in Haskell are closely related: both define the types of certain operations without revealing their implementations. In Java, the name of an interface also acts as an interface type, whereas the name of a type class can only be used to constrain types. Interface types are a proven tool for ensuring data abstraction and information hiding. In many cases, Haskell type classes can serve the same purpose, but there are situations for which the solutions available in Haskell have severe drawbacks. Interface types provide a simple and elegant solution in these situations. A modest extension to Haskell provides the simplicity and elegance of interface types: simply allow programmers to use the name of a type class as a first- class type.
    [Show full text]
  • Plantuml Language Reference Guide (Version 1.2021.2)
    Drawing UML with PlantUML PlantUML Language Reference Guide (Version 1.2021.2) PlantUML is a component that allows to quickly write : • Sequence diagram • Usecase diagram • Class diagram • Object diagram • Activity diagram • Component diagram • Deployment diagram • State diagram • Timing diagram The following non-UML diagrams are also supported: • JSON Data • YAML Data • Network diagram (nwdiag) • Wireframe graphical interface • Archimate diagram • Specification and Description Language (SDL) • Ditaa diagram • Gantt diagram • MindMap diagram • Work Breakdown Structure diagram • Mathematic with AsciiMath or JLaTeXMath notation • Entity Relationship diagram Diagrams are defined using a simple and intuitive language. 1 SEQUENCE DIAGRAM 1 Sequence Diagram 1.1 Basic examples The sequence -> is used to draw a message between two participants. Participants do not have to be explicitly declared. To have a dotted arrow, you use --> It is also possible to use <- and <--. That does not change the drawing, but may improve readability. Note that this is only true for sequence diagrams, rules are different for the other diagrams. @startuml Alice -> Bob: Authentication Request Bob --> Alice: Authentication Response Alice -> Bob: Another authentication Request Alice <-- Bob: Another authentication Response @enduml 1.2 Declaring participant If the keyword participant is used to declare a participant, more control on that participant is possible. The order of declaration will be the (default) order of display. Using these other keywords to declare participants
    [Show full text]
  • Chapter 8. Deploying an Osgi Service
    Chapter 8. Deploying an OSGi Service The OSGi core framework defines the OSGi Service Layer, which provides a simple mechanism for bundles to interact by registering Java objects as services in the OSGi service registry. One of the strengths of the OSGi service model is that any Java object can be offered as a service: there are no particular constraints, inheritance rules, or annotations that must be applied to the service class. This chapter describes how to deploy an OSGi service using the OSGi blueprint container. The Blueprint Container ........................................................................................................... 92 Blueprint Configuration ................................................................................................... 93 Defining a Service Bean .................................................................................................. 95 Exporting a Service ........................................................................................................ 98 Importing a Service ...................................................................................................... 104 Publishing an OSGi Service .................................................................................................... 113 Accessing an OSGi Service ..................................................................................................... 118 FUSE ESB Deploying into the OSGi Container Version 4.2 91 Chapter 8. Deploying an OSGi Service The Blueprint Container Blueprint Configuration
    [Show full text]
  • Mixin-Based Programming in C++1
    Mixin-Based Programming in C++1 Yannis Smaragdakis Don Batory College of Computing Department of Computer Sciences Georgia Institute of Technology The University of Texas at Austin Atlanta, GA 30332 Austin, Texas 78712 [email protected] [email protected] Abstract. Combinations of C++ features, like inheritance, templates, and class nesting, allow for the expression of powerful component patterns. In particular, research has demonstrated that, using C++ mixin classes, one can express lay- ered component-based designs concisely with efficient implementations. In this paper, we discuss pragmatic issues related to component-based programming using C++ mixins. We explain surprising interactions of C++ features and poli- cies that sometimes complicate mixin implementations, while other times enable additional functionality without extra effort. 1 Introduction Large software artifacts are arguably among the most complex products of human intellect. The complexity of software has led to implementation methodologies that divide a problem into manageable parts and compose the parts to form the final prod- uct. Several research efforts have argued that C++ templates (a powerful parameteriza- tion mechanism) can be used to perform this division elegantly. In particular, the work of VanHilst and Notkin [29][30][31] showed how one can implement collaboration-based (or role-based) designs using a certain templatized class pattern, known as a mixin class (or just mixin). Compared to other techniques (e.g., a straightforward use of application frameworks [17]) the VanHilst and Notkin method yields less redundancy and reusable components that reflect the structure of the design. At the same time, unnecessary dynamic binding can be eliminated, result- ing into more efficient implementations.
    [Show full text]
  • Interface Evolution Via Virtual Extension Methods Brian Goetz Fourth Draft, June 2011
    Interface evolution via virtual extension methods Brian Goetz Fourth draft, June 2011 1. Problem statement Once published, it is impossible to add methods to an interface without breaking existing implementations. (Specifically, adding a method to an interface is not a source- compatible change.) The longer the time since a library has been published, the more likely it is that this restriction will cause grief for its maintainers. The addition of closures to the Java language in JDK 7 place additional stress on the aging Collection interfaces; one of the most significant benefits of closures is that it enables the development of more powerful libraries. It would be disappointing to add a language feature that enables better libraries while at the same time not extending the core libraries to take advantage of that feature1. V1 of the Lambda Strawman proposed C#-style static extension methods as a means of creating the illusion of adding methods to existing classes and interfaces, but they have significant limitations – for example, they cannot be overridden by classes that implement the interface being extended, so implementations are stuck with the “one size fits all” implementation provided as an extension2, and they are not reflectively discoverable. 2. Virtual extension methods3 In this document, we outline a mechanism for adding new methods to existing interfaces, which we call virtual extension methods. Existing interfaces can be augmented without compromising backward compatibility4 by adding extension methods to the interface, whose declaration would contain instructions for finding the default implementation in the event that implementers do not provide a method body.
    [Show full text]
  • Dynamic Interfaces
    Dynamic Interfaces Vasco T. Vasconcelos Simon J. Gay Antonio´ Ravara Departamento de Informatica´ Department of Computing Science SQIG at Instituto de Telecomunicac¸oes˜ Faculdade de Cienciasˆ da University of Glasgow, UK Department of Mathematics, IST, Universidade de Lisboa, Portugal [email protected] Technical University of Lisbon, Portugal [email protected] [email protected] Nils Gesbert Alexandre Z. Caldeira Department of Computing Science Departamento de Informatica´ University of Glasgow, UK Faculdade de Cienciasˆ da [email protected] Universidade de Lisboa, Portugal [email protected] Abstract 1. Introduction We define a small class-based object-oriented language in which Standard class-based object-oriented languages present the pro- the availability of methods depends on an object’s abstract state: grammer with the following view: an object is declared to belong to objects’ interfaces are dynamic. Each class has a session type which a certain type, and the type defines various methods; it is therefore provides a global specification of the availability of methods in possible at any time to call any of the methods described in the type. each state. A key feature is that the abstract state of an object However, there are often semantic reasons why it is not appropriate may depend on the result of a method whose return type is an to call a particular method when the object is in a particular inter- enumeration. Static typing guarantees that methods are only called nal state. For example: with a stack, one should not attempt to pop when they are available.
    [Show full text]
  • Create Mixins with Interfaces and Extension Methods by Bill Wagner
    Create Mixins with Interfaces and Extension Methods by Bill Wagner Mixins are small utility classes that define some useful functionality that will usually become part of something larger. For example, a class that implements a serial number to uniquely identify an object, or a timestamp that reports when an object was created. In C++, these mixin classes would be created using regular class definitions, and larger classes that wanted to use the mixin behavior would simply inherit from the mixin, in addition to any base classes it needed. Because the .NET Framework does not support multiple inheritance, we’ve typically used interface to define mixins. That works, but it’s not as powerful. One of the limitations of using interfaces to define mixin behavior is that every class that implements an interface must reimplement every method defined in that interface. That leads many developers to creating minimal interface definitions. (IEqualityComparer<T> has one method, IComparable<T> has only method). In those instances, the interface’s full functionality is completely defined in those small methods. But, what about cases where your interface can, or should, contain many more methods in order to support the developers that want to use the interface? That’s a perfect use case for extension methods. By creating extension methods using the interface, you can inject many more methods into the public definition of the interface, without forcing every developer to re-create those methods whenever he or she implements that interface. I’ve created a simple example based on strings that represent file paths. I often write classes that contain files or directories, usually for offline caches, or similar needs.
    [Show full text]
  • Variable-Arity Generic Interfaces
    Variable-Arity Generic Interfaces T. Stephen Strickland, Richard Cobbe, and Matthias Felleisen College of Computer and Information Science Northeastern University Boston, MA 02115 [email protected] Abstract. Many programming languages provide variable-arity func- tions. Such functions consume a fixed number of required arguments plus an unspecified number of \rest arguments." The C++ standardiza- tion committee has recently lifted this flexibility from terms to types with the adoption of a proposal for variable-arity templates. In this paper we propose an extension of Java with variable-arity interfaces. We present some programming examples that can benefit from variable-arity generic interfaces in Java; a type-safe model of such a language; and a reduction to the core language. 1 Introduction In April of 2007 the C++ standardization committee adopted Gregor and J¨arvi's proposal [1] for variable-length type arguments in class templates, which pre- sented the idea and its implementation but did not include a formal model or soundness proof. As a result, the relevant constructs will appear in the upcom- ing C++09 draft. Demand for this feature is not limited to C++, however. David Hall submitted a request for variable-arity type parameters for classes to Sun in 2005 [2]. For an illustration of the idea, consider the remarks on first-class functions in Scala [3] from the language's homepage. There it says that \every function is a value. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying." To achieve this integration of objects and closures, Scala's standard library pre-defines ten interfaces (traits) for function types, which we show here in Java-like syntax: interface Function0<Result> { Result apply(); } interface Function1<Arg1,Result> { Result apply(Arg1 a1); } interface Function2<Arg1,Arg2,Result> { Result apply(Arg1 a1, Arg2 a2); } ..
    [Show full text]