Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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) {
    ...
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading