Static function instead of constructor

Notice: This thread is very old.
washo
Member | 88
+
0
-

Hello,
this is more philosophical question, but do you know some reason, why not to use public static function as a second constructor?

Ilustrative example:

class Color
{
  private $red;
  private $green;
  private $blue;

  public static function rgb($r,$g,$b)
  {
    $result = new self;
    $result->setRgb($r,$g,$b);
    return result;
  }

  public static function hexa($hexa)
  {
    $result = new self;
    $result = setHexa($hexa)
    return $result;
  }
}

I know static is considered as evil, but I haven't found any difference between:

$color = new Color(1,2,3);
or
$color = Color::rgb(1,2,3);

Do you have some potential issue with this?

Ondřej Brejla
Member | 746
+
0
-

This is just “Static Factory Method” pattern (I don't mean Abstract Factory or Factory Method from GoF). It's a widely used pattern (especially in Java). It has advantages and disadvanteges too. For more info try to google it, or read e.g. Effective Java (J. Bloch).

HosipLan
Moderator | 4668
+
0
-

Static is considered evil, only if working with some state. Your example is not working with any state – it's just creating instances – it's perfectly valid.

Last edited by HosipLan (2012-09-28 12:55)

redhead
Member | 1313
+
0
-

Just to add my bit, a static factory method has an advantage that I really like – it is (should be) named properly. When you use constructor, you don't always know what parameters are needed and why without reading the docs. With properly named factory method it's easy. Like in this example:

class Angle {
	public static fromRadians($angle) { ... };
	public static fromDegrees($angle) { ... };
}

In strictly typed languages it also overcomes problem with two constuctors with the same parameters of the same type (above both params would be of type double, and you can't have two constructors with a single parameter of type double).

It's also far more readable when used:

Angle::fromRadians(0.5);

Last edited by redhead (2012-09-28 16:48)