我所知道的动态类型语言从不让开发人员指定变量的类型,或者至少对这种类型的支持非常有限。
例如,JavaScript方便时不提供任何机制来强制变量类型。PHP使您可以指定一些类型的方法参数,但是无法使用本机类型(int
,string
,等)的参数,也没有办法强制类型的参数比任何其他。
同时,可以方便地选择以动态类型语言指定变量的类型,而不是手动进行类型检查。
为什么会有这样的限制?是出于技术/性能方面的原因(我认为是JavaScript)还是出于政治方面的原因(我认为是PHP)?我不熟悉的其他动态类型语言是否属于这种情况?
编辑:在回答和评论之后,这是一个澄清的示例:假设我们在纯PHP中具有以下方法:
public function CreateProduct($name, $description, $price, $quantity)
{
// Check the arguments.
if (!is_string($name)) throw new Exception('The name argument is expected to be a string.');
if (!is_string($description)) throw new Exception('The description argument is expected to be a string.');
if (!is_float($price) || is_double($price)) throw new Exception('The price argument is expected to be a float or a double.');
if (!is_int($quantity)) throw new Exception('The quantity argument is expected to be an integer.');
if (!$name) throw new Exception('The name argument cannot be an empty string.');
if ($price <= 0) throw new Exception('The price argument cannot be less or equal to zero.');
if ($price < 0) throw new Exception('The price argument cannot be less than zero.');
// We can finally begin to write the actual code.
// TODO: Implement the method here.
}
通过一些努力,可以将其重写为(另请参见PHP中的按合同编程):
public function CreateProduct($name, $description, $price, $quantity)
{
Component::CheckArguments(__FILE__, __LINE__, array(
'name' => array('value' => $name, 'type' => VTYPE_STRING),
'description' => array('value' => $description, 'type' => VTYPE_STRING),
'price' => array('value' => $price, 'type' => VTYPE_FLOAT_OR_DOUBLE),
'quantity' => array('value' => $quantity, 'type' => VTYPE_INT)
));
if (!$name) throw new Exception('The name argument cannot be an empty string.');
if ($price <= 0) throw new Exception('The price argument cannot be less or equal to zero.');
if ($price < 0) throw new Exception('The price argument cannot be less than zero.');
// We can finally begin to write the actual code.
// TODO: Implement the method here.
}
但是,如果PHP可以选择接受本机类型作为参数,则相同的方法将编写如下:
public function CreateProduct(string $name, string $description, double $price, int $quantity)
{
// Check the arguments.
if (!$name) throw new Exception('The name argument cannot be an empty string.');
if ($price <= 0) throw new Exception('The price argument cannot be less or equal to zero.');
if ($price < 0) throw new Exception('The price argument cannot be less than zero.');
// We can finally begin to write the actual code.
// TODO: Implement the method here.
}
哪一个更短?哪一个更容易阅读?