22

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".

Is there a technical reason then, for having declared int.parse() and double.parse() as static methods rather than factory constructors?

More generally, what would be the guidelines for choosing to write a factory constructor over a static (factory) method in Dart?

Patrice Chalin
  • 15,440
  • 7
  • 33
  • 44
  • Yes, that does seem a bit inconsistent. `new int.fromString()` would make more sense from that perspective. Although `int.parse()` feels more natural. – ronag Jan 27 '14 at 19:09
  • This may very well be another special treatment for performance purposes, but that's really just wild guessing. – MarioP Jan 27 '14 at 21:01
  • @MarioP: Yea, I guess that makes sense. However, I would have hoped that the compiler was good enough at optimizing that such special treatment wasn't necessary. – ronag Jan 27 '14 at 21:09
  • @ronag Turns out I was wrong anyway. "Feels more natural" is actually much closer ;-) – MarioP Jan 27 '14 at 21:28

1 Answers1

20

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.

I see "parse" as a utility function more than a constructor, probably because int and double don't really have constructors otherwise. 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.

Community
  • 1
  • 1
MarioP
  • 3,752
  • 1
  • 23
  • 32
  • 6
    Ok so since Dart 2.0 where the use of new is discouraged there is really no difference then. – Thomas Aug 18 '19 at 16:25