-
Notifications
You must be signed in to change notification settings - Fork 1
Classmembers
In XP Language, there are three different types of reference types: Classes, interfaces and enums. Most members may be declared in any three, but we'll focus on classes here.
```groovy
public class Album {
protected string $name;
public __construct(string $name= null) { $this.setName($name); } public void setName(string $name) { $this.name= $name; } public string getName() { return $this.name; } }
|
We've omitted the public modifier for both the class and for the methods (meaning: this is not part of the API, test cases and their methods are used by the unittest runner only). In reality, since public is the default, nothing has changed. Annotations decorate the test methods, for which we've used the underscore naming pattern contrary to the camelCase version as in the public API since it reads better for unittests. Since test methods don't return anything, we use the "void" type. |
Now that we have a tested version, we'll apply our first refactoring. Actually, we'll only be changing the code to be more concise, and because the compiler is inbetween, it's a merely visual change! We'll rewrite the Album
using the so-called "compact" syntax. It will allow us to shorten the name accessor methods slightly.
```groovy
public class Album {
protected string $name;
public __construct(string $name= null) { $this.setName($name); } public void setName($this.name) { } public self withName($this.name) -> $this; public string getName() -> $this.name; }
|
So this time around, we use a property and thus are able to use all the operations the Vector class provides for us instead of having to reimplement them: add() and elements(), but also clear() and size(), and possibly more. We use a private member for backing the public property and make it read-only by raising exceptions from its setter. Now are API reads along the lines of: $album.images.add(new Image()) . Because the Vector class overloads array access and iteration, we can even use $album.images[0] and iteration with foreach.
|