2

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?

Brian Ogden
  • 18,439
  • 10
  • 97
  • 176

1 Answers1

5

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, declaring the constructor as a factory constructor would leave open the possibility that someday it could return an existing instance instead of guaranteeing a new instance.

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

jamesdlin
  • 81,374
  • 13
  • 159
  • 204