User-defined data types
Building your own data types
- The built-in types cover simple cases; richer problems need user-defined types.
- They make code clearer and let the compiler catch more mistakes.
- They split into non-composite (a single value) and composite (a group).
Non-composite types
- An enumerated type has values that are a fixed list of named constants:
TYPE Vehicle = (M100, M230, T101, T102)
DECLARE MyTaxi : Vehicle
MyTaxi ← T102 // cannot assign anything outside the list
- A pointer holds the memory address of another variable (or
NULL). To dereference (p^) is to reach what it points to — used to build linked lists and trees.
Practice
An enumerated type holds:
An enumerated type restricts a variable to one of a fixed set of named values (e.g. days of the week).
Practice
A pointer variable holds:
A pointer stores an address; dereferencing (p^) reaches the variable it points to — used for dynamic structures.
Composite types
- A record groups fields of different types (Topic 10).
- A set is an unordered collection of unique values, with add/remove/membership/union/intersection.
- A class/object combines data fields (attributes) with operations on them (methods); an object is an instance of a class.
CLASS Taxi
PRIVATE Capacity : INTEGER
PUBLIC FUNCTION GetCapacity() RETURNS INTEGER
RETURN Capacity
ENDFUNCTION
ENDCLASS
Practice
A class combines:
A class bundles attributes and methods; an object is an instance of a class.
Practice
A set is:
A set holds unique values with no order, supporting membership tests, union and intersection.
You've got it
Key idea
- enumerated = a value from a fixed named list; pointer = an address (dereference with
^) - record = fields of different types; set = unordered unique values
- a class/object combines attributes (data) and methods (behaviour)
- choose a class when you need state and behaviour together
Practice
For a variable that must be one of {Red, Green, Blue}, the best type is:
A fixed list of allowed values is exactly what an enumerated type is for.