想象一下你有这门课
class Ai1ec_Less_Parser_Controller {
/**
* @var Ai1ec_Read_Variables_Startegy
*/
private $read_variable_strategy;
/**
* @var Ai1ec_Save_Variables_Strategy
*/
private $write_variable_strategy;
/**
* @var Ai1ec_Less_Variables_Collection
*/
private $less_variables_collection;
/**
* @var Ai1ec_Less_Parser
*/
private $ai1ec_less_parser;
/**
* We set the private variables in the constructor. I feel that there are too many parameters.
* Should i use setter instead and throw an exception if something is not set?
*
* @param Ai1ec_Read_Variables_Startegy $read_variable_strategy
* @param Ai1ec_Save_Variables_Strategy $write_variable_strategy
* @param Ai1ec_Less_Variables_Collection $less_variables_collection
* @param Ai1ec_Less_Parser $ai1ec_less_parser
*/
public function __construct( Ai1ec_Read_Variables_Startegy $read_variable_strategy,
Ai1ec_Save_Variables_Strategy $write_variable_strategy,
Ai1ec_Less_Variables_Collection $less_variables_collection,
Ai1ec_Less_Parser $ai1ec_less_parser ) {
}
}
我需要设置这些变量,所以我在构造函数中设置它们(但看起来参数太多)。另一种选择是使用 setter 来设置它们,然后在一个方法中如果没有像这样设置所需的变量之一,则抛出异常
public function do_something_with_parser_and_read_strategy() {
if( $this->are_paser_and_read_strategy_set === false ) {
throw new Exception( "You must set them!" );
}
}
private function are_paser_and_read_strategy_set () {
return isset( $this->read_variable_strategy ) && isset( $this->ai1ec_less_parser );
}
你认为这两种方法中的一种更好吗?为什么?