简体   繁体   English

Dart工厂(构造函数)与静态方法; 例如,为什么int.parse()不是工厂构造函数?

[英]Dart factory (constructor) vs. static method; e.g., why is int.parse() not a factory constructor?

The Dart Style Guide recommends using constructors instead of static methods to create instances , given that " named constructors and factory constructors in Dart give you all of the flexibility of static methods in other languages, while still allowing the callsite to appear like a regular constructor invocation ". Dart样式指南建议使用构造函数而不是静态方法来创建实例 ,因为Dart中的命名构造函数和工厂构造函数为您提供了其他语言中静态方法的所有灵活性,同时仍允许调用点看起来像常规构造函数调用 ”。

Is there a technical reason then, for having declared int.parse() and double.parse() as static methods rather than factory constructors? 有没有技术上的原因,因为已经将int.parse()double.parse()为静态方法而不是工厂构造函数?

More generally, what would be the guidelines for choosing to write a factory constructor over a static (factory) method in Dart? 更一般地说,选择在Dart中通过静态(工厂)方法编写工厂构造函数的指导原则是什么?

After digging around in Google Groups for a while, I did in fact find an official explanation for it: Link to Groups discussion 在谷歌群组中挖掘了一段时间后,我确实找到了一个正式的解释: 链接到群组讨论

For archive purposes, here the text as quoted from the link: 出于存档目的,此处引用链接中引用的文本:

I thought about making it a constructor, but it didn't feel right for int or double values. 我想过把它变成一个构造函数,但是对于int或double值感觉不对。

I see "parse" as a utility function more than a constructor, probably because int and double don't really have constructors otherwise. 我认为“解析”作为一个实用函数而不是构造函数,可能因为int和double实际上没有构造函数。 You don't create an integer, you discover it. 你没有创建一个整数,你发现它。

Also, currently the only way to check if a string is a number literal is to call parse and see if it throws (but I'm not entirely satisfied with that!), and I don't like constructors that throw on anything but programming errors. 此外,目前检查字符串是否为数字文字的唯一方法是调用解析并查看它是否抛出(但我对此并不完全满意!),并且我不喜欢构建器除了编程之外什么都没有错误。

And you don't have to write "new" in front of it this way, for no particular gain. 而且你不必以这种方式在它面前写“新”,因为没有特别的收获。

There is no single hard reason that makes it obviously not a constructor, but a bunch of smaller issues that together make me prefer it as a static function. 没有一个硬性原因使它显然不是构造函数,而是一堆较小的问题,这些问题共同使我更喜欢它作为静态函数。

So much for my "performance purposes" theory. 对我的“表现目的”理论来说太过分了。 Oh well. 那好吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM