We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.
While I do mostly agree with you (as I have also wanted async constructors) I feel like having an object that isn't yet itself would make it's 'this' into 'thisButNotJustYet'.
Regarding readability, static methods can take advantage of tear off, while factory constructors can't (yet).
bar(Foo.fromJson); // fromJson as static method
bar((payload) => Foo.fromJson(payload)); // fromJson as factory constructor
Guess who's here ...tear offs made it to the party! https://uploads.disquscdn.c...
This is the main reason I use only `static` over `factory`. The cases pointed in this article are all irrelevant to be, but I often use the pattern, so `fromJson` is always `static` in my codes.
That is because a constructor is not a method.
The most important difference is not mentioned here.
Factories can return a subtype (factory in Animal class can return a Cat instance), but static methods can't.
Wow.. the article and replies are very helpful. Thank you very much!
Been asking myself this lately - and came across this article & discussion - very interesting all the concise-ness stuff - thx Remi.
I use factory constructors to process API-response data and do all the extraction/transformation work to produce a new (or cached or const) instance of my model-classes. However, with null-safety, factory constructors now always have to return a valid instance - even if the data is invalid - and so they seem a bit less useful...
A static pseudo-constructor, OTOH, can be defined to return an optional (i.e. null is ok). This seems like an advantage for using static instead - so invalid data received from an API can be discarded by the static method, and allowed to return null, rather than constructing a "token"/skeleton instance just to meet the return-value requiement of a factory - and then higher layers (e.g. the UI) can do a simple null-check on the return value of the static method rather than having to null-check each property (or, if the instances are going into a List, the nulls can just be omitted). Also means my model classes don't have to be defined as having optional members, to allow for constructing an instance from missing/corrupted data from the API...
Does this make sense?
Thanks for this article. I knew I had seen some of these features using factory, but couldn't find them in the Dart feature tour.
Thank you for the article. However, this seems no longer valid...
....
Static(); // OK, likely a mistake
Factory constructors can't be async; static methods can be.