Formally speaking: How to apply OCL



Similar documents
Design by Contract beyond class modelling

Software Specification and Testing

Execution of A Requirement Model in Software Development

Tips for writing good use cases.

Appendix... B. The Object Constraint

Rigorous Software Development CSCI-GA

RUP iteration planning

[Refer Slide Time: 05:10]

The «include» and «extend» Relationships in Use Case Models

How to Study Mathematics Written by Paul Dawkins

Chapter 13: Program Development and Programming Languages

UML-based Test Generation and Execution

Agile Techniques for Object Databases

In this Lecture you will Learn: Systems Development Methodologies. Why Methodology? Why Methodology?

Quotes from Object-Oriented Software Construction

Software Requirements Specification of A University Class Scheduler

Construct by Contract: Construct by Contract: An Approach for Developing Reliable Software

Introducing Formal Methods. Software Engineering and Formal Methods

On the Relation between Design Contracts and Errors: A Software Development Strategy

The value of modeling

A Framework for the Semantics of Behavioral Contracts

Constructing Contracts: Making Discrete Mathematics Relevant to Beginning Programmers

Book 3 Cost Estimating in an Agile Development Environment. (early release)

Five High Order Thinking Skills

The Service Revolution software engineering without programming languages

Cutting to the chase What do you need to get accepted to an economics PhD program?

Model Simulation in Rational Software Architect: Business Process Simulation

Digital Industries Trailblazer Apprenticeship. Software Developer - Occupational Brief

A Standards-Based Approach to Extracting Business Rules

Writing in the Computer Science Major

Software Development in the Large!

Rigorous Software Development CSCI-GA

DISCLAIMER OVERVIEW WHY DO WE MODEL WHAT IS QUALITY? Jeff Jacobs,

Using Karel with Eclipse

Generating Aspect Code from UML Models

Advanced Software Engineering ( -Formal specification, verification, transformation, and application-

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

2667A - Introduction to Programming

Why Your Job Search Isn t Working

Automated Theorem Proving - summary of lecture 1

CRISP-DM, which stands for Cross-Industry Standard Process for Data Mining, is an industry-proven way to guide your data mining efforts.

Sofware Requirements Engineeing

Software Design. Software Design. Software design is the process that adds implementation details to the requirements.

How To Write A Test Engine For A Microsoft Microsoft Web Browser (Php) For A Web Browser For A Non-Procedural Reason)

UML Profiling Comes of Age Realizing the Potential of Domain-Specific Modeling

Requirements engineering

Use Case Modeling. Software Development Life Cycle Training. Use Case Modeling. Set A: Requirements Analysis Part 3: Use Case Modeling

To introduce software process models To describe three generic process models and when they may be used

TOGAF usage in outsourcing of software development

ABET General Outcomes. Student Learning Outcomes for BS in Computing

Cloud: It s not a nebulous concept

Why do you want to launch a business analyst career? Some possibilities include:

6 A/B Tests You Should Be Running In Your App

7 Insider Secrets For Selecting the Perfect Web Designer For Your Next Project. By Bruce Spiher & Tarun Gehani

Undergraduate Basics for Systems Engineering (SE), using The Principles, Measures, Concepts and Processes of

G C.3 Construct the inscribed and circumscribed circles of a triangle, and prove properties of angles for a quadrilateral inscribed in a circle.

A Meeting Room Scheduling Problem

Learning to Delegate

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

BCS HIGHER EDUCATION QUALIFICATIONS Level 6 Professional Graduate Diploma in IT. March 2013 EXAMINERS REPORT. Software Engineering 2

Rigorous Software Engineering Hoare Logic and Design by Contracts

Lecture 9: Requirements Modelling

Challenges and Opportunities for formal specifications in Service Oriented Architectures

Generating Enterprise Applications from Models

WESTMORELAND COUNTY PUBLIC SCHOOLS Integrated Instructional Pacing Guide and Checklist Computer Math

Minimizing code defects to improve software quality and lower development costs.

VHDL Test Bench Tutorial

IBM Rational Asset Manager

The role of integrated requirements management in software delivery.

Software Engineering Reference Framework

Case studies: Outline. Requirement Engineering. Case Study: Automated Banking System. UML and Case Studies ITNP090 - Object Oriented Software Design

UML basics: An introduction to the Unified Modeling Language

Aspect Oriented Strategy to model the Examination Management Systems

Sequential Program Execution

Chapter 1: Key Concepts of Programming and Software Engineering

Software Component Specification Using Design by Contract

HOW TO USE DATA VISUALIZATION TO WIN OVER YOUR AUDIENCE

Chapter 4 Software Lifecycle and Performance Analysis

(BA122) Software Engineer s Workshop (SEW)

CHAPTER 11 REQUIREMENTS

Lecture 3 Topics on Requirements Engineering

Web Services - Consultant s View. From IT Stategy to IT Architecture. Agenda. Introduction

Introduction to Formal Methods. Các Phương Pháp Hình Thức Cho Phát Triển Phần Mềm

Use-Case Analysis. ! What is it? ! From where did it come? ! Now part of UML

Data Modeling Basics

Introduction. Book Structure

Secrets to Automation Success. A White Paper by Paul Merrill, Consultant and Trainer at Beaufort Fairmont, LLC

Transcription:

Page 1 of 6 Copyright IBM Corporation 2004 http://www-106.ibm.com/developerworks/rational/library/5390.html Search for: within All of dw Use + - ( ) " " Search help IBM home Products & services Support & downloads My account developerworks > Rational Formally speaking: How to apply OCL Gary Pollice Worcester Polytechnic Institute 14 Jul 2004 from The Rational Edge: This article discusses various uses of OCL (Object Constraint Language) for both developers and testers. IT also enumerates the many advantages of the language, which is part of the UML specification. If you were a computer science or software engineering major in college, you probably had to take a course in the foundations of computer science or formal methods. And if you did, you probably thought, What will I ever use this for? Since I have devoted a significant part of my career to working with language tools, formal methods are important to me. But they also have a lot of value for software practitioners, especially when they are embedded in a specification language, such as OCL (Object Constraint Language). In this article, I will share with you why I value OCL and how I apply it. Contents: What are formal methods? UML and OCL OCL as a specification language Testers like it, too Conclusion References Notes About the author Rate this article Subscriptions: dw newsletters dw Subscription (CDs and downloads) What are formal methods? Formal methods are the mathematical foundations for many technologies and practices that software engineers use. Joseph Goguen says that formal methods are syntactic in essence but semantic in purpose. 1 What he means is that formal methods are concerned with form with the syntax of statements, predicates, and so on. They are also concerned with content. Formal specification languages represent one area of formal methods. Among the best known are Larch, VDM, and Z. Most of these languages are based on first-order logic with set theory. Many have supporting tools basically theorem provers that accept a specification written in the formal language and evaluate it for consistency, completeness, and accuracy. These languages describe what a program should do rather than how it should do it. Often they are syntactically simple and semantically rich they use the symbols of mathematical logic (e.g., ). Unfortunately, understanding simple expressions in these languages such as can be difficult, even for people with a solid math education. 2 But just because these languages are difficult to understand doesn't mean they are useless. Some kinds of software must be developed and quality tested more rigorously than other kinds. For example, compilers must work correctly all the time, so they are excellent candidates for formal specifications. Of course, we should always strive for bug-free software, but if a compiler generates incorrect code, the consequences will be more dire than if a grocery list program fails. UML and OCL In addition to compilers, another component in many software developers toolkits today has a strong formal background: Unified Modeling Language (UML). This language fits Goguen s description of a formal method. It is syntactic in essence, offering a well-defined way to construct a model. It is also semantic in purpose that is, it is designed to convey meaning. Much information can be encoded in a UML model. But it is not always easy to construct syntactically correct and semantically rich models of software using just UML diagrams. The rules for which type of arrowhead and which type of connector to use for which purpose can be just as confusing as the syntax for a programming language such as Java. And then, even if you can construct a correct UML diagram, there is much information that it will not convey. The Rational Edge--July 2004

Page 2 of 6 However, OCL, a formal specification language that is part of the UML specification, enables you to annotate models with expressions that clarify meaning. In UML 1.1, the main purpose of OCL was to identify the constraints on model elements. For example, it could help you indicate that, to be assigned a room, a specific course must have at least six students enrolled. With OCL you could annotate the association between the Course and Classroom classes to represent the constraint, as shown in Figure 1. As an alternative to the note shown in this figure, you could use a constraint connector between the Course and Classroom classes. Figure 1: Using OCL to indicate a constraint on assigning a classroom to a course UML 2.0 has expanded the role of OCL to include queries, business rule specification, and other types of expressions. If Model Driven Architecture (MDA) succeeds in taking hold, it will be in part because of OCL. It allows us to annotate models and convey specifications that generate accurate code. I also use OCL to help clarify my focus on critical testing areas. As many developers do not know how to apply OCL in these ways, I will devote the rest of this article to showing readers how I do it. OCL as a specification language Since my undergraduate days as a mathematics major, I ve enjoyed using some form of logical notation to express program design. One of my professors at Rutgers University designed a programming language based on the predicate calculus 3 that allowed me to write a specification using the language of logic, encode it to a file, and compile it to a program that satisfied the specification. The effective semantic richness was incredible. Once, I experimented to see how using this predicate-calculus language (PCL) compared to using an Algol-like language. I wrote a program to copy and transform a disk file to another form, applying certain filtering and transformation rules. First, I wrote it in PCL, using six lines (expressions) of code; it was accepted and ran the first time. Writing the very same program in the Algol-like language required more than 600 lines of code. So the savings PCL afforded, in terms of what I had to write, was two orders of magnitude. 4 Plus, I discovered an unexpected value in writing the PCL program first: I could use it to specify my second implementation in the Algol-like language, which also compiled and executed correctly the first time! After that, I began to write specifications in PCL whenever possible, and an amazing number of my programs compiled and ran correctly the first time. So I found that logic was indeed useful outside of the classroom. The biggest problem with PCL, though, was its bizarre syntax. If you have ever written an APL program, you can understand what I m talking about. Although APL programmers love(d) their language, it is mostly unintelligible to mere mortals who have to program in COBOL, C, or some other more common language. PCL suffered from the same problems. However, now we have OCL, whose authors realized that ease-of-use and understandability were pretty important if they wanted to see the language adopted by a wide audience. If you spend a little time studying the OCL specification and look at some examples, you can

http://qacma.cupertino.ibm.com/cma/previewxmlarticle?content_id=5390 Page 3 of 6 7/16/2004 jump right into using it to specify programs. Just as with UML, you can spend a lot of time and effort getting an OCL specification to obey all the syntax rules and requirements. But you can expend much less effort and still write something that is useful and understandable. Let s refer to this as using semiformal methods. You can do this when you get stuck; instead of attempting to follow every rule in OCL, use only the parts of it that are familiar to you, or that your audience will find easy to understand. A simple example In last month s column we looked at a triangle tester program that accepted three numbers and determined what type of triangle, if any, has sides with corresponding lengths. Let s specify this in OCL. Our method, kindoftriangle, returned the object TriangleType, which enabled us to determine the type of triangle. The specification for this method is shown in Code sample 1. Code sample 1: Triangle tester kindoftriangle specification At first glance the code sample looks rather long. It also looks like some sort of pseudo code; which it is in a way. But let s look a little closer. First of all, the specification is long because I ve formatted it that way. I could probably shorten it by ten lines if I wanted to. But it still takes up less space than would the same specification written out in English prose. After presenting the next couple of features of this specification I ll explain some of the OCL syntax and semantics. The second thing to notice is that the specification is just that a specification that says what the effect of executing the method kindoftriangle will be. It says nothing about how to implement the method. This is a key attribute of specifications: They must be free of implementation details, which may be difficult if we are using natural language. Often we have preconceived notions about

Page 4 of 6 implementation details, such as what the data storage mechanism should be. If we remove implementation details, we get to the heart of the problem and create a clearer specification. The third feature of an OCL specification is that it is declarative, specifying only the what and not the how. There is no description of any change in state or assignment to variables. OCL expressions are said to be side-effect free. In short, what you see is what you get. Now let s go back and analyze Code sample 1. The first line tells us what the specification applies to its context. It is for the kindoftriangle operation in the TriangleTester class, and the operation returns a value of type TriangleType. Other kinds of context declarations are defined in OCL for UML classifiers, attributes, and operations. The second line describes the preconditions for this operation things that must be true for the operation to work properly. If you are practicing design by contract, 5 and the client must guarantee that contract conditions are met before invoking an operation, the client s part of the contract is specified by the preconditions. The rest of the specification consists of the post-conditions. This is the service side of the contract. If the preconditions are met, the implementer agrees to produce the results specified by the post-conditions. If you have programmed in almost any modern programming language, you should be able to read and understand the post-condition specification. There is more to OCL than just context, preconditions, and post-conditions. It has syntax for describing invariants in a context, initial values, queries, and so on. Also, OCL does not employ a lot of mathematical notation. Most of its notation is readily accessible to software developers. Jotting down specifications in OCL, whether you are planning to include them in a formal document, make them into comments in your code, or throw them away, is a useful exercise. It helps you, as a software developer, to clarify what your real task is. But it s not the only use for OCL. Testers like it, too Test cases should be derived from specifications, but this may be difficult to do, especially if the specifications are written in prose in a long document. Use cases are useful for giving testers enough information to perform system-level and black-box tests to ensure that the system delivers value to the client. Analysis and design activities decompose a system into classes and subsystems that need to be tested. OCL can be helpful here. Let s start looking at the use-case level of a system specification. If you are familiar with use cases, you know that they already have precondition and post-condition attributes. With a little training, you could probably instruct everyone on how to read enough OCL to understand pre-conditions and post-conditions written in it. 6 This can help requirements specifiers focus on clarity and ensure that the use case is consistent, coherent, and of real value to the actor. If you describe the pre- and post-conditions of your use case with OCL, you can then make them the specification of your specification and review the use-case flows of events to determine if they accurately reflect the OCL. You can also ensure that the flows of events address all the constraints and visible results. Testers can use the pre- and post-conditions to write their system-level test cases. For example, in the specification in Code sample 1, we can quickly identify some test cases and construct a table to ensure that we have at least tested all possible result combinations. Our test case table might look like Table 1. Table 1: Triangle tester test cases

Page 5 of 6 The tests described in Table 1 clearly are not complete. However they provide at least a basic test of the post-conditions defined in the Code sample 1 specification. Depending upon the priority and criticality of the feature and the risks of not completely testing all possible combinations, we can either stop here or add as many test cases as necessary. I have found that creating test cases from OCL specifications is a straightforward task. Programmers and testers who use OCL can become very good at ensuring that the specifications are correct and the tests really address them. In fact, you could use OCL in combination with the TFP technique I described in last month s column to design tests from a well-formed, independent specification. When I teach software testing classes at WPI, I have students write OCL specifications for methods that lack other specifications. This helps them do a better job of testing because they are able to isolate the method s real requirements or those the implementer perceives and write appropriate tests for them. Sometimes, implementers find that perceived requirements do not match actual ones. OCL can help by creating a concise, readable, and analyzable specification. Conclusion OCL is not the only formal language that can be used for specification, nor is it the most rigorous or complete one. But it does have some important things going for it: It does not have overly complicated mathematical symbols and rules. It is easy to learn and begin applying. It is part of a standard adopted by many organizations. It will be supported by many new tools under development. You do not even need to use OCL with the rest of UML to realize its benefits. Like any new technique, you have to learn it, begin to use it, refine your skills, and keep in mind the end goal: producing reliable software. In general, it is useful to study and embrace formal methods as a way of thinking. The software professionals I know who have done so are, in my opinion, some of the best analysts, designers, and programmers that I have ever had the privilege of working with. There is something about thinking formally that is well-suited to developing computer software. If you have a chance to take a course in formal methods, I urge you to do so and then note how it makes you better at what you do. References Information about OCL and the OCL specification can be found at http://www.omg.org. Jos Warmer and Anne Kleppe, The Object Constraint Language, 2e. Addison-Wesley, 2003 (ISBN: 0321179366)

Page 6 of 6 Joseph A. Goguen s Web page contains his publications on software engineering, architecture, formal methods, and methodology: http://www.cs.ucsd.edu/users/goguen/projs/swarch.html Peter Ryan and Chris Sennett, eds., Formal Methods in Systems Engineering. Springer-Verlag, 1993. (ISBN: 3540197516) Notes 1 Joseph A. Goguen in the Introduction to Formal Methods in Systems Engineering, Ryan and Sennett, ed., Springer-Verlag, 1993. 2 This particular expression declares succinctly that an ordered collection, x, of n+1 integers, or some other comparable type, is sorted in ascending order. 3 The predicate calculus is a logic consisting of predicate expressions that evaluate whether something is true or false. It has the typical logical operations, such as AND and OR, and relational operators such as =, <, and so on. 4 An order of magnitude is a factor of ten. Two orders of magnitude sounds much more impressive than 100 times, don t you think? 5 Design by contract is associated mainly with Dr. Bertrand Meyer and his Eiffel programming language. See http://archive.eiffel.com/doc/manuals/technology/contract/ for more information. 6 In their book, The Object Constraint Language, Second Edition, Warmer and Kleppe provide an alternate OCL syntax that is easier for business modelers to use and understand. OCL can be quite flexible in the syntax area. About the author Gary Pollice is a Professor of Practice at Worcester Polytechnic Institute, in Worcester, MA. He teaches software engineering, design, testing, and other computer science courses, and also directs student projects. Before entering the academic world, he spent more than thirty-five years developing various kinds of software, from business applications to compilers and tools. His last industry job was with IBM Rational Software, where he was known as "the RUP Curmudgeon" and was also a member of the original Rational Suite team. He is the primary author of Software Development for Small Teams: A RUP-Centric Approach, published by Addison-Wesley in 2004. He holds a B.A. in mathematics and M.S. in computer science. What do you think of this document? Killer! (5) Good stuff (4) So-so; not bad (3) Needs work (2) Lame! (1) Comments? Submit feedback developerworks > Rational About IBM Privacy Terms of use Contact