I am reading an article about constructors doing too much work. One paragraph reads
In the object oriented style, where dependencies tend to be inverted, the constructor has a different and more Spartan role. Its only job is to make sure that object initializes into a state where it satisfies its basic invariants (in other words, it makes sure that the object instance starts off in a valid state and nothing more).
Here is a basic example of a class. On creation of the class I pass in the HTML which needs parsed to then set the class properties.
OrderHtmlParser
{
protected $html;
protected $orderNumber;
public function __construct($html)
{
$this->html = $html;
}
public function parse()
{
$complexLogicResult = $this->doComplexLogic($this->html);
$this->orderNumber = $complexLogicResult;
}
public function getOrderNumber()
{
return $this->orderNumber;
}
protected function doComplexLogic($html)
{
// ...
return $complexLogicResult;
}
}
I'm calling it using
$orderparser = new OrderHtmlParser($html);
$orderparser->parse()
$orderparser->getOrderNumber();
I use a parse
function because I dont want the constructor to be doing any logic as both the article above and this article state this is terrible practice.
public function __construct($html)
{
$this->html = $html;
$this->parse(); // bad
}
However if I don't use the parse
method, then all my properties (in this example just the one) would return null
.
Is this known as an object in an 'invalid state'?
Also, it somewhat feels like my parse method is an initialise
function in disguise, which is also deemed bad by the other article (although im not sure if that is only when a constructor calls that method, when it is manually called or both). Regardless, the initialise method is still doing some complex logic prior to setting a property - which needs to happen before the getters can be reliably called.
So either I am misunderstanding these articles or these articles are pushing me to think that maybe my overall implementation of this simple class is incorrect.
Aucun commentaire:
Enregistrer un commentaire