Why use the factory constructor in this case

I came across a helpful Parsing Complex JSON tool in this article. The tool will take a JSON example and parse it in the programming language of your choice.

I am currently working with Dart and for my simple raw JSON "content" example:

{
  "title": "Welcome to quicktype!"
}

Being parsed by this JSON tool in Dart creates this Dart class:

import 'dart:convert';

Content contentFromJson(String str) => Content.fromJson(json.decode(str));

String contentToJson(Content data) => json.encode(data.toJson());

class Content {
    String title;

    Content({
        this.title,
    });

    factory Content.fromJson(Map<String, dynamic> json) => new Content(
        title: json["title"],
    );

    Map<String, dynamic> toJson() => {
        "title": title,
    };
}

What is the purpose of a factory constructor in this case? There is no "private" variable storing the Content class instantiation. There isn't a cache or a key that is checked so that the already instantiated Content class is returned on subsequent Content.fromJson calls that use the same raw JSON data argument.

Because the factory keyword is used, does that mean that Dart handles reusing the same instantiation behind the scenes simply because the method is denoted as a factory constructor?

1 answer

  • answered 2019-05-15 06:13 jamesdlin

    I don't see a need to use factory in that example. It could have been a normal named constructor:

    Content.fromJson(Map<String, dynamic> json) : this(title: json["title"]);
    

    That said, even if unnecessary, there a few reasons why factory could be useful:

    • It leaves the possibility open that someday it could return an existing instance instead of guaranteeing a new instance.

    • If any error-checking code is added to Content.fromJson, it's likely that it would need a constructor body and might no longer be able to delegate to the main constructor. A factory constructor doesn't use initialization lists and thus wouldn't have that limitation.

    Of course, in this case, a factory constructor is also unnecessary since it could also be a static method (which could provide other benefits).