Perfect Developer basic tutorial 4 | This page last modified 2011-10-30 (JAC) |
Let's provide some sort of access to the authors attribute of our Book objects.
Rather than make authors publicly readable, instead we will add a method to check whether a particular person is included in authors. We can do this by adding a method hasAuthor as follows:
Now we can use the expression
b.hasAuthor("Douglas Adams")
to check whether "Douglas Adams" is one of the authors of the Book object
b.
Looking at the function declaration in more detail, we can see that it comprises the keyword function followed by the name we have chosen, then comes the parameter list (if there are any parameters), then the return type is declared (after a colon, just as for variables and parameters).
Note that a function is not allowed to change either the abstract data of the object it is called on, nor its parameters - all it can do is return a value. (Actually, functions can return several values at once, but we'll skip this facility for now).
Let's add a second way of accessing the authors variable, by declaring a function to return any one of the authors. Of course, when there are several such authors, the result is not precisely defined. The function is therefore nondeterministic, which we indicate by declaring it opaque. Here is one way of declaring an anyAuthor function:
We have defined anyAuthor using an any expression to choose any element from the collection authors.
However, there is another way we can specify what a function returns, which is particularly useful for opaque functions:
Instead of using the is-defined-as symbol ^=
to define the
return value, we use the keyword satisfy to introduce a condition (or
several comma-separated conditions) that the result must obey.
Before we move on, take a good look at the Book class we have arrived at. Can you see any problems with it in general, and with the anyAuthor function (expressed in either way) in particular?
Next: Try it out!
Save My Place | Glossary | Language Reference Manual |
Copyright © 1997-2012 Escher Technologies Limited. All rights reserved. Information is subject to change without notice. |