Home > Blockchain >  Constructor: Storing pre-processed params in helper variables passed to final fields
Constructor: Storing pre-processed params in helper variables passed to final fields

Time:08-20

I'd like to provide an alternative constructor for my Circe class where the center and radius are calculated from 3 points. But I cannot find a way to store the calculated center to the temporal variable and pass it to both final fields. Calling _getCenter twice works, but this approach is suboptimal. Is there a more efficient way?

import 'dart:math';

class Circle {
  final Point center;
  final double radius;

  Circle(this.center, this.radius);

  Circle.fromPoints(Point p1, Point p2, Point p3)
      : center = _getCenter(p1, p2, p3),
        radius = _getCenter(p1, p2, p3).distanceTo(p1);

  static Point _getCenter(Point p1, Point p2, Point p3) {
    ...
  }

CodePudding user response:

You could make use of a factory constructor:

import 'dart:math';

class Circle {
  final Point center;
  final double radius;

  Circle(this.center, this.radius);

  factory Circle.fromPoints(Point p1, Point p2, Point p3) {
    final center = _getCenter(p1, p2, p3);
    final radius = center.distanceTo(p1);

    return Circle(center, radius);
  }

  static Point _getCenter(Point p1, Point p2, Point p3) {
    ...
  }
}

The point of such constructor is to behave like a constructor but does not create any object instance automatically. You must then return an object that is compatible with the class the factory constructor is part of.

CodePudding user response:

I'd probably use a factory constructor as suggested by julemand101's answer. Another approach is to use late members so that they can be initialized in a constructor body.

import 'dart:math';

class Circle {
  late final Point center;
  late final double radius;

  Circle(this.center, this.radius);

  Circle.fromPoints(Point p1, Point p2, Point p3) {
    center = _getCenter(p1, p2, p3);
    radius = center.distanceTo(p1);
  }

  static Point _getCenter(Point p1, Point p2, Point p3) {
    ...
  }

This would matter if you want to use the fromPoints constructor from a redirecting constructor or if you have some derived class that wants to invoke fromPoints as a base class constructor. However, late variables are potentially more expensive since they might add runtime checks.

  • Related