69

I've been investigating JSON parsing for my Flutter app and have a question about factory constructors that I can't resolve. I'm trying to understand the advantage of using a factory constructor versus a plain constructor. For example, I see quite a few JSON parsing examples that create a model class with a JSON constructor like this:

class Student{
  String studentId;
  String studentName;
  int studentScores;

  Student({
    this.studentId,
    this.studentName,
    this.studentScores
  });

  factory Student.fromJson(Map<String, dynamic> parsedJson){
    return Student(
      studentId: parsedJson['id'],
      studentName : parsedJson['name'],
      studentScores : parsedJson ['score']
    );
  }
}

I've also seen an equal number of examples that DON'T declare the constructor as a factory. Both types of classname.fromJSON constructors create an object from the JSON data so is there an advantage to declaring the constructor as a factory or is using a factory here superfluous?

2
  • 5
    Factory constructors are not actual constructors. They are functions hidden behind a fake constructor. They are used to replace static methods that you'd use in other languages Sep 12, 2018 at 16:03
  • This helped me understand it: stackoverflow.com/a/56107639
    – MoralCode
    Dec 20, 2021 at 4:49

4 Answers 4

61

A normal constructor always returns a new instance of the current class (except when the constructor throws an exception).

A factory constructor is quite similar to a static method with the differences that it

  • can only return an instance of the current class or one of its subclasses
  • can be invoked with new but that is now less relevant since new became optional.
  • has no initializer list (no : super())

So a factory constructor can be used

  • to create instances of subclasses (for example depending on the passed parameter
  • to return a cached instance instead of a new one
  • to prepare calculated values to forward them as parameters to a normal constructor so that final fields can be initialized with them. This is often used to work around limitations of what can be done in an initializer list of a normal constructor (like error handling).

In your example this code

  studentId: parsedJson['id'],
  studentName : parsedJson['name'],
  studentScores : parsedJson ['score']

could be moved to the body of a normal constructor because no final fields need to be initialized.

12
  • 2
    I think the main point of factory constructor is to hide the fact that it's a static function as an implementation detail; to provide a consistent way of instantiating objects Sep 12, 2018 at 16:11
  • 5
    You can't use it as a variable like you'd do with callbacks though. But yeah, with dart 2 the gain is limited Sep 12, 2018 at 16:14
  • 3
    Maybe mention that subclasses can't super.factory? Sep 12, 2018 at 16:18
  • 2
    Thanks for the reply, Gunter. It seems like using a factory constructor verses a named constructor has valid special case uses but shouldn't be used capriciously. The majority of examples I saw could be adequately addressed just using a named constructor but were using a factory constructor. In the example I used in my question it seems like the correct implementation would be this: Student.fromJson(Map<String, dynamic> parsedJson) : studentId = parsedJson['id'], studentName = parsedJson['name'], studentScores = parsedJson['score'];
    – mjordan
    Sep 12, 2018 at 23:21
  • 1
    Right, if you made the 3 fields in the class final it would look differently though. Sep 13, 2018 at 2:41
52

In the particular example in the question, there's no advantage to using a factory constructor. It makes no difference to callers (there is no expectation to receive an already-existing object), and this particular factory constructor could have been a normal constructor that delegated to the main constructor instead.

In general, the factory keyword is not very useful and provides an advantage only in special circumstances.


A factory constructor vs. a normal constructor

  • A factory constructor invokes another constructor.
  • Since a factory constructor does not directly create a new instance, it cannot use a constructor initializer list.
  • A normal constructor always returns a new instance of the class. A factory constructor is permitted to return an existing instance, an instance of a derived class, or null. (However, some people dislike returning null from a factory constructor. Note that returning null from a factory constructor is disallowed with null-safety.)
  • Due to the above, an extending class cannot invoke a factory constructor as the superclass constructor. A class that provides only factory constructors therefore cannot be extended with derived classes.

A factory constructor vs. a static method

  • A factory constructor can be the unnamed, default constructor of a class.
  • A factory constructor can be used with new. (But using new is now discouraged.)
  • Until Dart 2.15, constructors could not be used as tear-offs (i.e., they could not be used as callbacks), whereas static methods could.
  • Static methods can be async. (A factory constructor must return a type of its class, so it cannot return a Future.)
  • Factory constructors can be declared const.
  • In null-safe Dart, a factory constructor cannot return a nullable type.
  • In generated dartdoc documentation, a factory constructor obviously will be listed in the "Constructors" section (which is prominently at the top) whereas a static method will be in the "Static Methods" section (which currently is buried at the bottom).
4
  • 3
    that doesn't really answer the question. You explain the difference between a factory constructor and a normal one, and a static method respectively. The question instead is about why to use factory constructor when parsing json, given in the official examples a new instance is always created within the factory constructor.
    – Alessio
    Mar 4, 2020 at 8:17
  • 1
    @Alessio This is a very well written answer, and he works in Dart for Google, +1 from me.
    – iDecode
    May 1, 2020 at 12:35
  • 3
    @iKeepChangingName that's ok, but I still keep my opinion that the answer is not actually answering the question, while been a well written summary of what a factory constructor is and isn't. The fact that he works in Dart for Google doesn't change my opinion either. No worries we can disagree about it :)
    – Alessio
    May 4, 2020 at 10:28
  • Didn't like the answers here. They are too complicated and do not answer the main question clearly. Found a good explanation to the specific question here stackoverflow.com/a/63628949/12695188 Mar 5, 2022 at 18:49
4

After I've been noticing and wondering the same, and given I don't think the other answers actually answer the question ("I've been investigating JSON parsing [...] I'm trying to understand the advantage of using a factory constructor verses a plain constructor"), here my try:

there's no advantage or difference that I could see or understand, when parsing json, in using a factory constructor instead of a plain constructor. I tried both, and both works fine, with all the types of parameters. I decided eventually to adopt the factory constructor, because of the convenience of how the code is written, and readability, but it's a matter of choice and both will work fine in all the cases.

-2

One of the uses of factory constructor is, we can decide which instance to create, at run-time and move all the logic to the parent's factory constructor

let's say you have 1 parent class and 2 subclasses

class GolderRetriever extends Dog{
   GolderRetriever(String name):super(name);
}
class Labrador extends Dog{
  Labrador(String name):super(name);
}

Then we have the parent class

class Dog{
  final String name;
  Dog(this.name);
  
  
  factory Dog.createInstance({required String name,DogType type=DogType.UNKNOWN}){
    
    if(type==DogType.GOLDEN_RETRIEVER){
      return GolderRetriever(name);
    }
    else if(type==DogType.DALMATION){
      return Labrador(name);
    }else{
    return Dog(name);
    }
  }
}

and also I have enum DogType

enum DogType{
  GOLDEN_RETRIEVER,DALMATION,UNKNOWN
}

Then in the main Method, you just delegate which subclass instance you want to create to the parent Dog class

main() {
     
  Dog myDog = Dog.createInstance(name:"Rocky",type:DogType.DALMATION);
  Dog myNeighboursDog =  Dog.createInstance(name:"Tommy",type:DogType.GOLDEN_RETRIEVER);
  Dog strayDog = Dog.createInstance(name:"jimmy");
}

you can't do this with a named constructor as you can create only the instance of that class(Dog class), not its subtypes.

Now the responsibility of which instance to create is delegated to the parent class. This can remove a lot of if-else boilerplate code. When you want to change the logic, you just change that in Animal class alone.

2
  • 2
    First, I don't think that answers the question. Secondly, I don't think it is a good practise, that a parent class knows about its children. Your example would fit better, if Dog would be called DogFactory and there would be an additional DogInterface. DogFactory could then use the factory constructor build in into Dart. Jul 11, 2021 at 13:56
  • The parent class shouldn't know about its children, Thank you, that makes a lot of sense!!!
    – Saravanan
    Jul 12, 2021 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.