The class concept
This presentation is the property of its rightful owner.
Sponsored Links
1 / 73

The Class Concept PowerPoint PPT Presentation

  • Uploaded on
  • Presentation posted in: General

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.

Download Presentation

The Class Concept

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

The class concept

The Class Concept


What is a class?

Two parts of the class

Two views of the class

Class vs. type

Prof. Lorenz

A class abstraction over objects

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

Class = Abstraction Over Objects

  • Phenomena: Similar Objects

  • Abstraction Mechanism: Class

    • Basic Metaphor: Data Type

An Abstraction Process


Dimensions of the class concept

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


What is a class

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

  • NU

    Collaborating classes uml

    Collaborating Classes: UML

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




    OO solution:

    one method

    for each red











    Static aspect

    Dynamic aspect




    Objectgraph in uml notation

    ObjectGraph: in UML notation

















    Shared vs particular features

    Shared vs. Particular Features


    A different abstraction over objects

    A Different Abstraction over Objects

    • Common Parts:

      • Structure

      • Protocol

    • Specified per Instance:

      • State: values of data members.

      • Behavior: “values” of function members.

    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!


    The two views of a class

    The Two Views of a Class

    • Implementation: the common structure and the details of how the behavior works.

      • Body in Ada

      • Definitions of function members in C++

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

    • Specification in Ada

    • Declarations 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.

  • NU

    Java interface classgraphi

    Java Interface ClassGraphI

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

    • ObjectgetNode(String l) The node labeled l in the class graph.

    • CollectiongetNodes() A collection of nodes in the class graph.

    • CollectiongetOutgoingEdges(Object v) A collection of edges (EdgeI objects) going out of node v.


    Uml class graph

    UML class graph













    Java how to use the interface

    Java: how to use the Interface

    • public class ClassGraph extends Object implements ClassGraphI


    Java interface edgei

    Java Interface EdgeI

    • StringgetLabel() The label of the edge, or null if it is not a construction edge.

    • ObjectgetSource() The source node of the edge.

    • ObjectgetTarget() The target node of the edge.

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

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


    Implementation in the interface

    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.


    The two parts of a class

    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.

    Static Part

    Dynamic Part

    Instance Variables





    Messages &Methods


    Views and parts in c

    Views and Parts in C++



    • Kinds of Interfaces in C++

      • Users of a Class:




      • Levels of Visibility:




    Dynamic Part

    Static Part

    private data members

    private function members

    public function members

    public data members


    Public data members

    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;}




    Views and parts in eiffel

    Views and Parts in Eiffel



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

    • User cannot know the kind ofimplementation of a feature.

    Dynamic Part

    Static Part

    Unexported attributes

    Unexported routines

    Exported routines

    Exported without args?


    Abstract data types and classes

    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: Booleantype 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


    User defined types

    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:

    • Initialization

    • Memory management:

      • Allocation

      • Deallocation

    • Type conversions

    • Literals (basic values)

    • A set of operators

      • Operator overloading




    • Sets, Objects and Inheritance

    • Specialization and Factorization

    • Basic Terminology and Notation

    • Inheritance Hierarchies


    Inheritance what does it look like

    Inheritance -- What does it look like?


    The personnel example

    The Personnel Example

    • 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);

    • // ...

    • };


    Factorization and specialization

    Factorization and Specialization

    struct Employee {

    char *name;

    short year_born;

    short department;

    int salary;

    Employee *next;

    void raise_salary(int how_much);

    // ...


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

    /* ... */


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

    struct Engineer: Employee {

    char *degrees;

    // ...


    struct SalesPerson: Employee {

    float *commission_rate;

    // ...



    Program domain example

    Program Domain Example








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





    Inheritance hierarchy

    Inheritance Hierarchy


    Observe the direction of the arrows!

    Air Vehicle

    Land Vehicle

    Water Vehicle







    • 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


    Terminology smalltalk vs c

    Terminology: Smalltalk vs. C++






    Instance Variable



    Class Variable

    Class Method


    Base class

    Derived class

    Data Member

    Member function

    Member function call

    Static data member

    Static function member


    The eiffel terminology

    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).


    Typing and strict inheritance

    Typing and Strict Inheritance

    • Value, Type, Variable

    • Static and Dynamic Typing

    • Strict Inheritance


    Value type variable

    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.


    Objectgraph in uml notation a value

    ObjectGraph: in UML notationA value

















    Significance of type

    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.


    Loopholes in the type system

    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.


    Typing in languages

    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, ...


    Dynamic typing

    Dynamic Typing






    • Type is associated with values.

      Each value carries a tag, identifying its type.

    • A variable may contain any value of any type.


    Strong typing what does it look like

    Strong Typing -- What does it look like?

    Strong typing prevents mixing abstractions.


    Static typing is strong typing

    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.


    Why static typing

    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 collection

        • Const correctness

        • Pre and post conditions


    Design by contract

    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.


    Rights and obligations

    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


    Rights and obligations1

    Rights and obligations

    • Precondition binds clients

    • Postcondition binds class





    If precondition is not satisfied

    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.


    Source of complexity

    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


    Class invariants and class correctness

    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);


    Class invariants and class correctness1

    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)


    Class invariants and class correctness2

    Class invariants and class correctness

    • A class invariant only applies to public methods; private methods are not required to maintain the invariant.


    Invariant rule

    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.


    Invariant rule1

    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


    Invariant rule2

    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


    The class concept

    Resource Allocation









    when: TimeInterval






    inv Job::allocated<>0 ==> allocated.provides->includesAll(type.reqs)

    --Any allocated resource must have the required facilities

    inv Resource::jo1, jo2: Job::

    (schedule->includesAll({jo1,jo2}) ==>


    -- no double-booking of resources


    Benefits of strong typing

    Benefits of Strong Typing

    • 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 typing1

    Benefits of Strong Typing


    class A {

    Object b;

    Object c;


    class B {

    Object d;


    class C extends B {









    If all instance variables are

    of class Object

    we get strange class graphs


    Benefits of strong typing2

    Benefits of Strong Typing


    class A {

    B b;

    C c;


    class B {

    D d;


    class C extends B {










    Strict inheritance

    Strict Inheritance

    • 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.

    struct Manager: public Employee {

    char *degrees;

    // ...



    Is a relationship

    Is-A Relationship

    • Inheritance represents an is a relationship.

      • A subclass is a (more specialized) version of the base class:

        • Manager is an Employee.

        • Rectangleis a Shape.

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

    class Monom { ... };

    Monom operator +(Monom m1, Monom m2){ ... }

    class DMonom: public Monom { ...

    } d1, d2;

    Monom m = d1 + d2;


    Types and oop

    Types and OOP

    • Types and Classes

      • Types: Administrative aid

        • Check for typos.

        • Type predicates and type calculus.

      • Classes: A mould for creating objects

        Usually, 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.


    Properties of strict inheritance

    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


    Collections in little smalltalk

    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.


    What are collections

    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.


    Classification of collections

    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.


    Collections attributes

    Collections’ Attributes

    NameCreationFixed Order? InsertionAccessRemoval MethodSize? MethodMethodMethod

    Setnew no no add: includes: remove:

    Dictionarynewnono at:put: at: removeKey:

    Interval n to: m yes yes none none none

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

    Arraynew: yes yes at:put:at: none

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

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

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


    Inserting an element

    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' )


    Removing an element

    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 ( )


    Accessing an element

    Accessing an Element

    • In indexed collections the elements are accessed by key.

      > 'SmallTalk' at: 6


    • The method keys returns the keys of an indexed collection.

      > D keys

      Set ('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'


    • The method includes: is defined for all collections.

      > #( 10 20 30 40 50 ) keys includes: 5



    Selecting elements

    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 )


    Performing computations

    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 ] ]


      > #(1 2 3 4 5) do: B

      1 is odd!

      2 is even!

      3 is odd!

      4 is even!

      5 is odd!

      Array ( 1 2 3 4 5 )


    Collecting results

    Collecting Results

    The 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.1


    > grades <- #(70 55 60 42) collect: [ :g | g * factor ]

    Array ( 77 60.5 66 46.2 )


    Accumulative processing

    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 size

      3 “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”


    Implementation examples

    Implementation Examples

    • Collection inject:into:

      inject: aValue into: aBlock | last |

      last <- aValue.

      self do: [:x | last <- aBlock value:last value:x ].


    • Collection 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 ] ]


    Roman numbers

    Roman Numbers

    Class Roman Object dict

    Methods Roman 'all'


    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 ].




    The class stack

    The Class Stack

    Class Stack Object list

    Methods Stack


    list <- List new


    push: anObject

    list addFirst: anObject


    pop| top |

    top <- list first. list removeFirst. ^top



    ^list size


    do: aBlock

    list do: aBlock


    A Stack is composed by a List.


  • Login