Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Factory constructor code example - Dart

I have some niggling questions about factory constructors example mentioned here (https://www.dartlang.org/guides/language/language-tour#factory-constructors). I am aware of only three types of constructors on a basic level - default, named and parameterised.

  1. Why should I use factory at all for this example?
  2. Is that a named constructor which is being used? and why? Example factory constructor
like image 499
Ananta K Roy Avatar asked Dec 21 '18 14:12

Ananta K Roy


People also ask

What is factory constructor in Dart How will you create a factory?

A factory constructor is a constructor that can be used when you don't necessarily want a constructor to create a new instance of your class. This might be useful if you hold instances of your class in memory and don't want to create a new one each time (or if the operation of creating an instance is costly).

What is a factory constructor in flutter?

A factory constructor can be the unnamed, default constructor of a class. It can be used with new. (But using new is now discouraged.) Static methods can be used to create tear-offs (i.e., they can be used as callbacks) but constructors currently can't.

How do you define a constructor in darts?

Dart defines a constructor with the same name as that of the class. A constructor is a function and hence can be parameterized. However, unlike a function, constructors cannot have a return type. If you don't declare a constructor, a default no-argument constructor is provided for you.


2 Answers

tl;dr Use a factory in situations where you don't necessarily want to return a new instance of the class itself. Use cases:

  • the constructor is expensive, so you want to return an existing instance - if possible - instead of creating a new one;
  • you only ever want to create one instance of a class (the singleton pattern);
  • you want to return a subclass instance instead of the class itself.

Explanation

A Dart class may have generative constructors or factory constructors. A generative constructor is a function that always returns a new instance of the class. Because of this, it does not utilize the return keyword. A common generative constructor is of the form:

class Person {   String name;   String country;    // unnamed generative constructor   Person(this.name, this.country); } var p = Person("...") // returns a new instance of the Person class 

A factory constructor has looser constraints than a generative constructor. The factory need only return an instance that is the same type as the class or that implements its methods (ie satisfies its interface). This could be a new instance of the class, but could also be an existing instance of the class or a new/existing instance of a subclass (which will necessarily have the same methods as the parent). A factory can use control flow to determine what object to return, and must utilize the return keyword. In order for a factory to return a new class instance, it must first call a generative constructor.

Dart Factory Explained

In your example, the unnamed factory constructor first reads from a Map property called _cache (which, because it is Static, is stored at the class level and therefore independent of any instance variable). If an instance variable already exists, it is returned. Otherwise, a new instance is generated by calling the named generative constructor Logger._internal. This value is cached and then returned. Because the generative constructor takes only a name parameter, the mute property will always be initialized to false, but can be changed with the default setter:

var log = Logger("..."); log.mute = true; log.log(...); // will not print 

The term factory alludes to the Factory Pattern, which is all about allowing a constructor to return a subclass instance (instead of a class instance) based on the arguments supplied. A good example of this use case in Dart is the abstract HTML Element class, which defines dozens of named factory constructor functions returning different subclasses. For example, Element.div() and Element.li() return <div> and <li> elements, respectively.

In this caching application, I find "factory" a bit of a misnomer since its purpose is to avoid calls to the generative constructor, and I think of real-world factories as inherently generative. Perhaps a more suitable term here would be "warehouse": if an item is already available, pull it off the shelf and deliver it. If not, call for a new one.

How does all this relate to named constructors? Generative and factory constructors can both be either unnamed or named:

...   // named generative   // delegates to the default generative constructor   Person.greek(String name) : this(name, "Greece");     // named factory    factory Person.greek(String name) {     return Greek(name);   } }  class Greek extends Person {   Greek(String name) : super(name, "Greece"); }   
like image 68
Dave Fort Avatar answered Oct 10 '22 09:10

Dave Fort


1) There is not much difference between a static method and a factory constructor.

For a factory constructor the return type is fixed to the type of the class while for a static method you can provide your own return type.

A factory constructor can be invoked with new, but that became mostly irrelevant with optional new in Dart 2.

There are other features like redirects rather rarely used that are supported for (factory) constructors but not for static methods.

It is probably still good practice to use a factory constructor to create instances of classes instead of static methods to make the purpose of object creation more obvious.

This is the reason a factory constructor is used in the example you posted and perhaps because the code was originally written in Dart 1 where it allowed to create a logger instance with new like with any other class.

2) Yes this is a named constructor and the prefix _ makes it a private named constructor. Only named constructors can be made private because otherwise there would be no place to add the _ prefix.

It is used to prevent instance creation from anywhere else than from the public factory constructor. This way it is ensured there can't be more than one Logger instance in your application. The factory constructor only creates an instance the first time, and for subsequent calls always returns the previously created instance.

like image 35
Günter Zöchbauer Avatar answered Oct 10 '22 09:10

Günter Zöchbauer