Sunday, June 7, 2009

Design Pattern: Value

Consider a class Val which contains a value, and a method add() which add another value with the same type.

class Val {
private
$value;
public function
__construct($value=0) {$this->value = $value; }

public function
get() { return $this->value; }

public function
add($newVal) {
//(1) WRONG:
//$this->addV += $value; //WRONG !!

// (2) RIGHT !!
return new Val($this->value + $newVal->get());
}
}

Add directly the value to the internal properties (1) is wrong!!
Suppose to have a class ValContainer, with a properties that is a reference to object Val.

Two or more instances of ValContainer should be contains references to the same instance of Val (e.g. via another class which contains a Val instance and returns it).

If one instance calls the method add() of Val, the other instances will have the new value modified !! This is not in according to OOP principles !

The second method (2) is right, it instantiates another Val object in case of add() !!

No comments:

Post a Comment

 

PHP and tips|PHP