Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you make helper functions in classes without instantiating an object of that class?

Tags:

dart

I have a class which has its functions for an instantiated object, but i am aware of other languages which will have helper functions inside the class which are public without defining an object explicitly.

The DART language website seemed like it didnt really address it. In a simple case, it could be something like having a Point class, then having a jsondecoder inside of it which may have some use instead of needing to have other libraries included.

class Point {
  int x, y;
  Point(this.x, this.y);

  Point fromMap(HashMap<String, int> pt){
    return new Point(pt["x"]||null, pt["y"]||null);
  }
}

that way when i need to use the Point class, i could just say:

Point pt = Point.fromMap({});

I didnt really see any examples as to when I was flipping through classes to make these properly public.

like image 422
Fallenreaper Avatar asked Jan 19 '16 16:01

Fallenreaper


2 Answers

Dart allows to define static member on a class. In your case:

class Point {
  int x, y;
  Point(this.x, this.y);

  static Point fromMap(Map<String, int> pt) {
    return new Point(pt["x"], pt["y"]);
  }
}

It's worth to note that you can also use named constructor and/or factory constructor :

class Point {
  int x, y;
  Point(this.x, this.y);

  // use it with new Point.fromMap(pt)
  Point.fromMap(Map<String, int> pt) : this(pt["x"], pt["y"]);

  // use it with new Point.fromMap2(pt)
  factory Point.fromMap2(Map<String, int> pt) => new Point(pt["x"], pt["y"]);
}
like image 86
Alexandre Ardhuin Avatar answered Sep 22 '22 14:09

Alexandre Ardhuin


The given example is perhaps not the best as the desired result is a new Point. Named constructors - as Alexandre says in his answer - are the preferred solution in the case.

Perhaps a better example (but still kinda artificial) would be:

library Points;

class Point {

  ...

  /// Return true if data in pt is valid [Point] data, false otherwise. 
  bool isValidData(HashMap<String, int> pt) { ... }
}

In languages without first-class function (e.g., Java), a static method would be proper. Dart supports this also.

class Point {

  ...

  /// Return true if data in pt is valid [Point] data, false otherwise. 
  static bool isValidData(HashMap<String, int> pt) { ... }
}

As Dart has first class functions, a function defined in the library may be a better choice.

library Points;

bool isValidPointData(HashMap<String, int> pt) { ... }

class Point {
  ...
}
like image 33
Argenti Apparatus Avatar answered Sep 25 '22 14:09

Argenti Apparatus