Quantcast
Viewing all articles
Browse latest Browse all 4

Smalltalk Best Practice Patterns: Constructor Method

Sadly reading is going slower than expected due to being so busy with various things in life. Oh well, just a single pattern today.

Constructor Method

How do you represent instantiation?

In addition to a vanilla constructor, add methods for common cases to instantiate typical objects. For strange cases allow the use of accessors.

Using Perl (with Moose) an example might be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package Point;

use Moose;

has x => (is => 'ro');
has y => (is => 'ro');

sub r_theta {
  my ($class, $r, $theta) = @_;

  $class->new(
    x => $r * cos($theta),
    y => $r * sin($theta),
  );
}

1;

So now both of the following work:

1
2
my $p = Point->new(5, 6);
my $v = Point->r_theta(10, 1.4);

Viewing all articles
Browse latest Browse all 4

Trending Articles