the class concept

73
1 P r o f . L The Class Concept Abstraction What is a class? Two parts of the class Two views of the class Class vs. type

Upload: lewis-swanson

Post on 16-Mar-2016

30 views

Category:

Documents


0 download

DESCRIPTION

The Class Concept. Abstraction What is a class? Two parts of the class Two views of the class Class vs. type. A Class -- Abstraction Over Objects. A class represents a set of objects that share a common structure and a common behavior. Class = Abstraction Over Objects. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: The Class Concept

1

Prof. Lorenz

The Class ConceptAbstractionWhat is a class?Two parts of the classTwo views of the classClass vs. type

Page 2: The Class Concept

NU

2

COM3230

A class represents a set of objects that share a common structure and a common behavior.

A Class -- Abstraction Over Objects

Page 3: The Class Concept

NU

3

COM3230

An Abstraction Process

Phenomenon A Phenomenon B

Phenomenon C

Yet Another UsefulAbstraction

Phenomenon 1 Phenomenon 2

Phenomenon 3

Some UsefulAbstraction

Class = Abstraction Over Objects Phenomena: Similar Objects Abstraction Mechanism: Class

Basic Metaphor: Data Type

Page 4: The Class Concept

NU

4

COM3230

Dimensions of the Class Concept Static vs. Dynamic Aspects Shared vs. Particular features Internal vs. External views

Multiple Interfaces The Data Type Metaphor Relationship with Instances

Class as an instance factory Existence as an Object

Meta classes

Page 5: The Class Concept

NU

5

COM3230

What is a Class? Abstraction Over Objects: a set of objects that share:

Dynamic Aspect Protocol: Declarations (signatures) of function members in C++ Behavior: Definitions (body) of function members in C++

Static Aspect Structure: Declarations of data members in C++.

• But not the definitions (value) of data members. State is not part of the class abstraction.

Mould for objects: used to instantiate objects (instances) with distinct identities that share protocol, behavior and structure but may assume different states.

In contrast to concrete object, a class does not necessarily exist in (run) time and (memory) space.

What’s not a Class? An object is not a class, but a class may be an object.

In “exemplar based’’ languages, there are no classes. New objects are “instantiated” from existing objects.

Not every set of objects is a class

Page 6: The Class Concept

NU

6

COM3230

Collaborating Classes: UML

BusRoute BusStopList

BusStopBusList

Bus PersonList

Person

passengers

buses

busStops

waiting

0..*

0..*

0..*

find all persons waiting at any bus stop on a bus route

OO solution:one methodfor each redclass

Static aspectDynamic aspect

Page 7: The Class Concept

NU

7

COM3230

ObjectGraph: in UML notation

Route1:BusRoute

:BusStopListbusStops

CentralSquare:BusStop

:PersonListwaiting

Paul:Person Seema:Person

:BusListbuses

Bus15:Bus

:PersonList

passengers

Joan:Person

Eric:Person

Page 8: The Class Concept

NU

8

COM3230

Shared vs. Particular Features

Type Operation

Constant Attribute

Shared Features

O pera tionSha red : BodyPa rticula r : H idden Argum ent

AttributeSha red : S tructurePa rticula r : Value

Particular Features

Features

Page 9: The Class Concept

NU

9

COM3230

class Stack {enum { N = 100 };int buff[N];int size;

public:void (*push)(int element);int (*pop)(void);

};

Abstraction, but not of the desired nature!

A Different Abstraction over Objects Common Parts:

Structure Protocol

Specified per Instance: State: values of data members. Behavior: “values” of function members.

Page 10: The Class Concept

NU

10

COM3230

The Two Views of a Class Implementation: the common structure and the details of how the

behavior works.Body in AdaDefinitions of function members in C++

Interface: the common protocol and the external specifications of the behavior.

Specification in AdaDeclarations in C++

Interface as a Contract: defines the contract of the relationship between instances of the class and their clients.

Strongly typed languages can detect some contract violations prior to run time.

Interface Components: Declaration of all class operations Declarations of externally accessible attributes Other pertinent declarations: constants, exceptions and other classes and/or

types, etc. Multiple Interfaces: frequently, the class has different interfaces to

different kinds of clients. Example: electronic mail agent has different interfaces to users and to

administrators.

Page 11: The Class Concept

NU

11

COM3230

Java Interface ClassGraphI Collection getIncomingEdges(Object v)

A List of edges (EdgeI objects) coming into node v.

Object getNode(String l) The node labeled l in the class graph.

Collection getNodes() A collection of nodes in the class graph.

Collection getOutgoingEdges(Object v) A collection of edges (EdgeI objects) going out of node v.

Page 12: The Class Concept

NU

12

COM3230

UML class graph

F

CBA

D

G

E

H

gf

e

Page 13: The Class Concept

NU

13

COM3230

Java: how to use the Interface public class ClassGraph extends Object implements

ClassGraphI

Page 14: The Class Concept

NU

14

COM3230

Java Interface EdgeI String getLabel()

The label of the edge, or null if it is not a construction edge.

Object getSource() The source node of the edge.

Object getTarget() The target node of the edge.

boolean isConstructionEdge() Is the edge a construction (part) edge?

boolean isInheritanceEdge() Is the edge an inheritance (superclass) edge?

Page 15: The Class Concept

NU

15

COM3230

Implementation in the Interface? In C++, the structure of an instance is defined in the

private part of class interface. Give away state information Changes to representation -> a functional affect on clients.

Why isn’t the structure of an instance part of the Implementation?

Needed by the compiler. Cannot allocate memory for objects without knowing their

size. Size is determined by structure.

Alternatives: OO Hardware: technology is not sufficiently advanced. Sophisticated Compilers: slowly, but coming. Other OOPLs: not as sexy as C++ and Java.

Page 16: The Class Concept

NU

16

COM3230

Dynamic PartStatic Part

Implementation

Interface

---Instance Variables

Messages &Methods---

The Two Parts of a Class Dynamic Part: specifications of the dynamic aspects

of the class instances. Static Part: specifications of the static aspects of the

class instances. Example: views and parts in Smalltalk.

Page 17: The Class Concept

NU

17

COM3230

Implementation

Interface

Dynamic Part

private function memberspublic function members

Static Part

private data memberspublic data members

Views and Parts in C++ Kinds of Interfaces in C++

Users of a Class:InstancesSubclassesClients

Levels of Visibility:privateprotectedpublic

Page 18: The Class Concept

NU

18

COM3230

Public Data Members?class Person { public age int;}class Person { private a int; public int age() {return a;}}class Person{ public int age() {return current_year-birth_year;}}AVOID INTERFACE CHANGES

Page 19: The Class Concept

NU

19

COM3230

Views and Parts in Eiffel

Implementation

Interface

Dynamic Part

Unexported routines

Exported routines

Static Part

Unexported attributesExported without args?

Attributesim plem ented as data

FunctionsIm plem ented as code

W ithout Argum ents

Functions Returning value

ProceduresNot returning value

RoutinesIm plem ented as code

W ith Argum ents

FeaturesEverything a c lassm ay have to o ffe r

Level and direction of export are orthogonal to kind of feature.

User cannot know the kind ofimplementation of a feature.

Page 20: The Class Concept

NU

20

COM3230

Abstract Data Types and Classes Type: A set of values with common operations

Main Application: protect mixing unrelated values/operations Example 1: Decree forbidding pointers multiplication Example 2: Decree against assigning a struct to an int variable

Abstract Data Type: defined by the set of basic values, means of generating other values, set of allowed operations and their meaning.

Example: Boolean type in Pascal.Values: True, False.Operations: Not, And, Or, =, <>, <=, >=, <, >. Implicit Operations: Assignment, argument passing, function return

value. Conversion to integer (ord). Class: A lingual mechanism that gives the means for realization of a:

Type Abstract Data Type Abstraction

Page 21: The Class Concept

NU

21

COM3230

Initialization Memory management:

Allocation Deallocation

Type conversions Literals (basic values) A set of operators

Operator overloading

User Defined Types If a user-defined type is to be a first class citizen (have

the look and feel of a built-in type), then the programming language must provide the ability to define for it:

Page 22: The Class Concept

NU

22

COM3230

Inheritance

Sets, Objects and Inheritance Specialization and Factorization Basic Terminology and Notation Inheritance Hierarchies

Page 23: The Class Concept

NU

23

COM3230

Inheritance -- What does it look like?

Page 24: The Class Concept

NU

24

COM3230

Suppose we want to computerize our personnel records...

We start by identifying the two main types of employees we have:

struct Engineer {Engineer *next;char *name;short year_born;short department;int salary;char *degrees;void raise_salary(

int how_much);// ...

};

struct SalesPerson {SalesPerson *next;char *name;short year_born;short department;int salary;float *commission_rate;void raise_salary(

int how_much);// ...

};

The Personnel Example

Page 25: The Class Concept

NU

25

COM3230

Factorization and Specializationstruct Employee {

char *name;short year_born;short department;int salary;Employee *next;void raise_salary(

int how_much);// ...

};

struct Engineer: Employee {

char *degrees;// ...

};

struct SalesPerson: Employee {

float *commission_rate;// ...

};

C version:struct Engineer { struct Employee E; char *degree; /* ... */};

Indeed, inclusion is a poor man’s (poor) imitation of inheritance!

Page 26: The Class Concept

NU

26

COM3230

Rectangle

Draw

Program Domain ExampleShape

MoveLocateRotate

LocationRotation

Ellipse

Draw

Observe the OMT (Object Modeling Technique) style of using a triangle for denoting Inheritance

Page 27: The Class Concept

NU

27

COM3230

Inheritance HierarchyVehicle

Car Truck

Land Vehicle Water Vehicle Air Vehicle

Airplane RocketBoat Submarine

Fundamental Rule: Suppose that a Vehicle has a

speed attribute, and an accelerate method,

then all other classes in the above diagram will have (at least) speed attribute, and the same accelerate method.

Classification of hierarchies: Connected / Disconnected Tree / DAG

Observe the direction of the arrows!

Page 28: The Class Concept

NU

28

COM3230

Terminology: Smalltalk vs. C++

Smalltalk

Inherit

Superclass

Subclass

Instance Variable

Method

Message

Class Variable

Class Method

C++

Inherit/Derive

Base class

Derived class

Data Member

Member function

Member function call

Static data member

Static function member

Page 29: The Class Concept

NU

29

COM3230

The Eiffel Terminology Inheritance:

Heir: immediate subclass. Descendant: transitive closure of the heir relation. Proper Descendant: Descendant minus heir. Parent: immediate super-class. Ancestor: transitive closure of the parent relation. Proper Ancestor: Ancestor minus parent.

Taxonomy of features: Feature: member in C++.

Attribute: data member of C++.Routine (Service): function member in C++.

• Procedure (Command): void function member in C++ (Mutator).

• Function (Query): ordinary function memberin C++ (Inspector).

Page 30: The Class Concept

NU

30

COM3230

Typing and Strict Inheritance

Value, Type, Variable Static and Dynamic Typing Strict Inheritance

Page 31: The Class Concept

NU

31

COM3230

Value, Type, Variable Value - the entities manipulated by programs.

Contents of a memory cell at a specific moment. State of an object.

Type - means of classification of values. Type is a set of values that have similar protocol.

Protocol - collection of permissible operations. Variable

A name of a memory cell that may contain values.

Page 32: The Class Concept

NU

32

COM3230

ObjectGraph: in UML notationA value

Route1:BusRoute

:BusStopListbusStops

CentralSquare:BusStop

:PersonListwaiting

Paul:Person Seema:Person

:BusListbuses

Bus15:Bus

:PersonList

passengers

Joan:Person

Eric:Person

Page 33: The Class Concept

NU

33

COM3230

Significance of Type Type Determines Meaning: What will be executed as a

result of the following expression? a + b

Integer addition, if a and b are integer, or Floating point addition, if a and b are of floating point type, or Conversion to a common type and then addition, if a and b are

of different types. Type determines what’s allowed: Is the following

expression legal? X[i]

Yes, if X of an array type and i is of an integral type. No, e.g., if X is a real number and i is a function.

Page 34: The Class Concept

NU

34

COM3230

Loopholes in the Type System

Types usually hide the fact that a variable is just a box of bits, however:Type Casting, as in long i, j, *p = &i, *q = &j;long ij = ((long) p) ^ ((long) q));

and union (variable records), as in

union {float f;long l;} d;d.f = 3.7;printf("%ld\n", d.l);

allow one to peep into the implementation of types.

Page 35: The Class Concept

NU

35

COM3230

Typing in Languages Formal Lang.: classified by significance of type

Strongly typed languages: a type is associated with each value. It is impossible to break this association within the framework of the language.

ML, Eiffel, Modula, ... Weakly typed languages: values have associated types, but it is possible

for the programmer to break or ignore this association.C, Turbo-Pascal

Untyped languages: values have no associated type.Assembly, BCPL, Lisp, Mathematica, Mathematical formulae.

Programming Lang.: classified by time of enforcement Dynamic typing: type rules are enforced at run-time. Variables have no

associated type.Smalltalk, Prolog, ...

Static typing: type rules are enforced at compile time. All variables have an associated type.

C, Pascal, Eiffel, ML, ...

Page 36: The Class Concept

NU

36

COM3230

Dynamic Typing Type is associated with values.

Each value carries a tag, identifying its type. A variable may contain any value of any type.

MyBook

“Nineteen-eighty-four”string

1984Integer

Page 37: The Class Concept

NU

37

COM3230Strong typing prevents mixing abstractions.

Strong Typing -- What does it look like?

Page 38: The Class Concept

NU

38

COM3230

Static Typing (is Strong Typing) In static typing, each variable, and even more generally, each identifier

is associated with a type.

This usually means that all identifiers should be declared before used. However this is not always the case:

Type inference in ML. Implicit type inference in Fortran.Grammatical type inference in some dialects of Basic.

A variable may contain only values of its associated type. All expressions are guaranteed to be type-consistent:

No value will be subject to operations it does not recognize. This allows the compiler to engage in massive optimization.

Static typing goes together with strong typing: The two terms are used almost synonymously in the literature and in this

course. In OOP, the preferred term is strong typing, since, as we will see later, there

is also a notion of dynamic type even in statically/strongly typed systems.

IdentifierType

Page 39: The Class Concept

NU

39

COM3230

Why Static Typing? Recursive functions theory teaches us that an

automatic tool is very limited as a programming aid Cannot determine if the program stops. Cannot determine if the program is correct. Cannot decide almost any other interesting run time

property of a program. One thing that can be done automatically is make sure

that no run time type error occurs. We can use every tiny bit of help in our struggle

against the complexity of software! Few other automatic aids are:

Garbage collectionConst correctnessPre and post conditions

Page 40: The Class Concept

NU

40

COM3230

Design by contract Object-Oriented Software Construction by Bertrand

Meyer, Prentice Hall The presence of a precondition or postcondition in a

routine is viewed as a contract.

Page 41: The Class Concept

NU

41

COM3230

Rights and obligations Parties in the contract: class and clients require pre, ensure post with method r: If you promise

to call r with pre satisfied then I, in return, promise to deliver a final state in which post is satisfied.

Contract: entails benefits and obligations for both parties

Page 42: The Class Concept

NU

42

COM3230

Rights and obligations Precondition binds clients Postcondition binds class

Page 43: The Class Concept

NU

43

COM3230

Example

Contract forpush of classStack

Obligations Benefits

ClientProgrammer

Only call push(x) on anon-full stack

Get x added as newstack top on return (topyields x, nb_elementsincreased by 1)

ClassImplementor

Make sure that x is puton top of stack

No need to treat casesin which the stack isalready full

Page 44: The Class Concept

NU

44

COM3230

If precondition is not satisfied If client’s part of the contract is not fulfilled, class can

do what it pleases: return any value, loop indefinitely, terminate in some wild way.

Advantage of convention: simplifies significantly the programming style.

Page 45: The Class Concept

NU

45

COM3230

Source of complexity Does data passed to a method satisfy requirement for

correct processing? Problem: no checking at all or: multiple checking. Multiple checking: conceptual pollution: redundancy;

complicates maintenance Recommended approach: use preconditions

Page 46: The Class Concept

NU

46

COM3230

Class invariants and class correctness Preconditions and postconditions describe properties

of individual methods Need for global properties of instances which must be

preserved by all routines 0<=nb_elements; nb_elements<=max_size empty=(nb_elements=0);

Page 47: The Class Concept

NU

47

COM3230

Class invariants and class correctness A class invariant is an assertion appearing in the

invariant clause of the class. Must be satisfied by all instances of the class at all

“stable” times (instance in stable state): on instance creation before and after every remote call to a routine (may be

violated during call)

Page 48: The Class Concept

NU

48

COM3230

Class invariants and class correctness A class invariant only applies to public methods;

private methods are not required to maintain the invariant.

Page 49: The Class Concept

NU

49

COM3230

Invariant Rule An assertion I is a correct class invariant for a class C iff the following two

conditions hold: The constructor of C, when applied to arguments satisfying the

constructor’s precondition in a state where the attributes have their default values, yields a state satisfying I.

Every public method of the class, when applied to arguments and a state satisfying both I and the method’s precondition, yields a state satisfying I.

Page 50: The Class Concept

NU

50

COM3230

Invariant Rule Precondition of a method may involve the initial state and the

arguments Postcondition of a method may only involve the final state, the

initial state (through old) and in the case of a function, the returned value.

The class invariant may only involve the state

Page 51: The Class Concept

NU

51

COM3230

Invariant Rule The class invariant is implicitly added (anded) to both the

precondition and postcondition of every exported routine Could do, in principle, without class invariants. But they give

valuable information. Class invariant acts as control on evolution of class A class invariant applies to all contracts between a method of the

class and a client

Page 52: The Class Concept

NU

52

COM3230

Resource Allocation

<JobCategory> <Facility>reqs

<Job>when: TimeInterval <Resource>

0..*

type

allocated

provides 0..*

0..1

inv Job::allocated<>0 ==> allocated.provides->includesAll(type.reqs)--Any allocated resource must have the required facilitiesinv Resource::jo1, jo2: Job:: (schedule->includesAll({jo1,jo2}) ==> jo1.when.noOverlap(jo2.when)-- no double-booking of resources

schedule

0..*

Page 53: The Class Concept

NU

53

COM3230

Enforce the design decisions. Prevent runtime crashes:

Mismatch in # of parameters Mismatch in parameters Sending an object an inappropriate message

Early error detection reduces: Development time Cost Effort

Type declarations help to document programs X: speed; (* Good *) Y: real; (* Bad *) Z = 3; (* Worse *)

More efficient and more compact object code type SMALL_COUNTER is range 0 .. 128;

Benefits of Strong Typing

Page 54: The Class Concept

NU

54

COM3230

class A { Object b; Object c;}class B { Object d;}class C extends B {}

Benefits of Strong TypingObject

A

CB

D

b

c d

If all instance variables areof class Object

we get strange class graphs

Page 55: The Class Concept

NU

55

COM3230

class A { B b; C c;}class B { D d;}class C extends B {}

Benefits of Strong TypingObject

A

CB

Db

c

d

Page 56: The Class Concept

NU

56

COM3230

Extension of base class: Structure Protocol Behavior

Engineer and SalesPerson extend, each in its own way, the structure and protocol of Employee.

Identifying the Employee abstraction, helps us define more types:

General Idea: similar to procedure call, but applied to data.

If procedure P calls procedure Q, then it can be said that “P extends Q”

P does everything that Q does + more.

Strict Inheritance

struct Manager: public Employee {char *degrees;

// ...};

Page 57: The Class Concept

NU

57

COM3230

Is-A Relationship

class Monom { ... };Monom operator +(Monom m1, Monom m2){ ... }class DMonom: public Monom {

... } d1, d2;

Monom m = d1 + d2;

Inheritance represents an is a relationship. A subclass is a (more specialized) version of the base

class:Manager is an Employee.Rectangle is a Shape.

A function taking the class B as an argument, will also accept a class D derived from B.

Page 58: The Class Concept

NU

58

COM3230

Types and OOP Types and Classes

Types: Administrative aid Check for typos.Type predicates and type calculus.

Classes: A mould for creating objectsUsually, type = class.

Subtypes and Subclasses Subtype: a type which is a subset of another type. Subclass: a class that inherits from another class.

Extend the mould.Usually, the subtype and subclass relationship are isomorphic.

Strict inheritance and Subtypes: With strict inheritance, we have full conformance and

substitutability, and therefore, a subclass is always a subtype.

Page 59: The Class Concept

NU

59

COM3230

Properties of Strict Inheritance The structure and the behavior of a subclass are a superset

of those of the superclass. The only kind of inheritance in Oberon (the grand-daughter of

Pascal). Conformance (AKA substitutability)

If a class B inherits from another class A, then the objects of B can be used wherever the objects of A are used.

Benefits of strict inheritance: New abstraction mechanism: extend a given class without

touching its code.

No performance penalty. Compile-time creature. Can be thought of as a syntactic sugar which helps define

classes. No conceptual penalty.

Structured path for understanding the classes. Drawbacks of strict inheritance:

Not overly powerful!

Except in the total size of objects,which, due to alignment, depends on

the depth of inheritance hierarchy

Page 60: The Class Concept

NU

60

COM3230

Collections in Little Smalltalk What are they? Kinds of collections. Basic Operations. Usage of Inheritance in the Collections Library. Roman numbers example. The Stack Example:

Defining a new kind of collection.

Page 61: The Class Concept

NU

61

COM3230

What are Collections? Collections provide the means for managing and

manipulating groups of objects. Kinds of collections: Set: represents an unordered group of objects. Elements

are added and removed by value. Dictionary: is also an unordered collection of elements, but

insertions and removals require an explicit key. Interval: represents a sequence of numbers in arithmetic

progression, either ascending or descending. List: is a group of objects having a specific linear ordering.

Insertions and removals are done in the extremes. Array: a fixed-size collections. Elements can not be inserted

or removed, but they may be overwritten. String: can be considered to be a special form of Array,

where the elements must be characters. Collections can be converted into a different kind by the

use of messages like asSet, asArray, etc.

Page 62: The Class Concept

NU

62

COM3230

Classification of Collections The different kinds of Collections may be classified according

to several attributes. Size

Fixed Unbounded

Ordering Ordered Unordered

Access Method By value Indexed Sequential

Choose the right Collection by examining its attributes.

Page 63: The Class Concept

NU

63

COM3230

Collections’ Attributes

Name Creation Fixed Order? Insertion Access Removal Method Size? Method Method Method

Set new no no add: includes: remove:

Dictionary new no no at:put: at: removeKey:

Interval n to: m yes yes none none none

List new no yes addFirst: first removeFirst addLast: remove:

Array new: yes yes at:put: at: none

String new: yes yes at:put: at: none

Note however that the implementation of new: in the class String is buggy. It creates a string of size 0!

This is rarely a problem, since one usually creates strings as literals.

Page 64: The Class Concept

NU

64

COM3230

Inserting an Element Indexed collections (Dictionary, Array) require an

explicit key and a value, by using the method at:put:> D <- Dictionary new at:'com1204' put:'OOP'; \ at:'com3230' put:'OOD'; at:'com3351' put:'PPL'Dictionary ( 'com1204' 'com3230' 'com3351' ) Non-indexed collections require only a value, by using the

method add:> S <- Set new add:'red'; add:'green'; add:'blue'Set ( 'blue' 'green' 'red' ) In the case of Lists the values can be added in the

beginning or end of the collection, by using the methods addFirst: and addLast:

> L <- List new addLast: 'End'; addFirst: 'Begin'List ( 'Begin' 'End' )

Page 65: The Class Concept

NU

65

COM3230

Removing an Element In indexed collections the removal method requires the

key.> D removeKey: 'com1204'Dictionary ( 'com3230' 'com3351' ) In collections with fixed size (Array and String)

elements can not be removed. In non-indexed collections the argument is the object to

be removed.> S remove: 'green'Set ( 'blue' 'red' ) In a List, an element can be removed from the beginning

(removeFirst) or by value (remove:).> L removeFirst remove: 'END'List ( )

Page 66: The Class Concept

NU

66

COM3230

Accessing an Element In indexed collections the elements are accessed by key.> 'SmallTalk' at: 6$T The method keys returns the keys of an indexed

collection.> D keysSet ('com3230' 'com3351') In non-indexed collections we already have the value,

hence the only question is whether it is in the collection.> S includes: 'black'false The method includes: is defined for all collections.> #( 10 20 30 40 50 ) keys includes: 5true

Page 67: The Class Concept

NU

67

COM3230

Selecting Elements The method select: returns a collection containing all the

elements that satisfy some condition. It receives a one-argument block that is evaluated for each

element in the collection, returning true or false. The returned collection is of the same class as the receiver in

case it is Set, List, and Array, and Array otherwise. > #( 1 2 3 4 5 ) select: [ :i | ( i rem: 2 ) = 0 ]Array ( 2 4 ) The method reject: returns the complementary collection.> #( 1 2 3 4 5 ) asSet reject: [ :i | ( i rem: 2 ) = 0 ]Set ( 1 3 5 ) Strings are special:> '1234567890' select: [ :c | c > $5 ]Array ( $6 $7 $8 $9 )

Page 68: The Class Concept

NU

68

COM3230

Performing Computations The method do: allows a computation to be performed on

every element in a collection. It also receives a one-argument block.> B <- [ :x | ( x rem: 2 ) = 0 ifTrue: [ ( x printString , ' is even!' ) print ] \ ifFalse: [ ( x printString , ' is odd!' ) print ] ]Block> #(1 2 3 4 5) do: B1 is odd!2 is even!3 is odd!4 is even!5 is odd!Array ( 1 2 3 4 5 )

Page 69: The Class Concept

NU

69

COM3230

Collecting ResultsThe method collect: is similar to do:, but it produces a new collection containing the results of the block evaluation for each element of the receiver collection.

> #( 1 2 3 4 5 ) collect: [ :i | i factorial ]Array ( 1 2 6 24 120 )> #( 1 2 3 4 5 ) collect: [ :j | j rem: 2 ]Array ( 1 0 1 0 1 )> D <- Dictionary new at:0 put:'even'; at:1 put:'odd'Dictionary ( 'even' 'odd' )> #( 1 2 3 4 5 ) collect: [ :x | D at: ( x rem: 2 ) ]Array ( 'odd' 'even' 'odd' 'even' 'odd' )> factor <- 1.11.1> grades <- #(70 55 60 42) collect: [ :g | g * factor ]Array ( 77 60.5 66 46.2 )

Page 70: The Class Concept

NU

70

COM3230

Accumulative Processing The method inject:into: is useful for processing all the

values of a collection and returning a single result. The first argument is the initial value, and the second is a two-

parameter block that performs some computation. At each iteration the block receives the result of the previous

computation and the next value in the collection.> A <- #(1 2 3 4 5)Array ( 1 2 3 4 5 )> ( A inject:0 into: [:a :b| a + b ] ) / A size3 “average of the values in the array”> A inject:0 into: [:x :y| x > y ifTrue:[x] ifFalse:[y]]5 “maximum value in the array” > A inject:0 into: [:i :j| ( j rem: 2 ) = 0 \ ifTrue: [ i + 1 ] ifFalse: [ i ] ]2 “number of even values in the array”

Page 71: The Class Concept

NU

71

COM3230

Implementation Examples Collection inject:into: inject: aValue into: aBlock | last | last <- aValue. self do: [:x | last <- aBlock value:last value:x ]. ^last Collection size size ^self inject: 0 into: [ :x :y | x + 1 ] Collection occurrencesOf: occurrencesOf: anObject ^self inject: 0 into: [ :x :y | ( y = anObject ) ifTrue: [ x + 1 ] ifFalse: [ x ] ]

Page 72: The Class Concept

NU

72

COM3230

Roman NumbersClass Roman Object dictMethods Roman 'all' new dict <- Dictionary new at:1 put: 'I'; at: 4 put: 'IV'; at: 5 put: 'V'; at: 9 put: 'IX'; at: 10 put:'X'; at: 40 put: 'XL'; at: 50 put: 'L'; at: 90 put: 'XC'; at: 100 put: 'C'; at: 400 put: 'CD'; at: 500 put: 'D'; at: 900 put: 'CM'; at: 1000 put: 'M'| generate: anInteger | count roman | count <- anInteger. roman <- ''. ( dict keys select: [ :k | k <= count ] ) sort

reverseDo: [ :key | ( count quo: key ) timesRepeat: [ roman <- roman , ( dict at:

key ) ]. count <- count rem: key ]. ^roman]

Page 73: The Class Concept

NU

73

COM3230

The Class StackClass Stack Object listMethods Stack

newlist <- List new

|push: anObjectlist addFirst: anObject

|pop | top |top <- list first. list removeFirst. ^top

|size^list size

|do: aBlocklist do: aBlock

]

A Stack is composed by a List.