Kirpich643
Kirpich643

Reputation: 121

How to run custom function in initializer list dart lang?

I research dart language and I want to write a value object model for Uuid with value validation.

import 'package:uuid/uuid.dart' as uuidLibrary;

class Uuid {
  String value;
  Uuid (String value) : uuidLibrary.Uuid.isValidOrThrow(fromString: uuid), this.value = value;
}

But my static code analizer is telling me that initializer list is wrong: uuidLibrary.Uuid.isValidOrThrow(fromString: uuid).

Static method isValidOrThrow already implements all checks that I need, I want to do this checks before assign value;

How I can do this, continuing using the isValidOrThrow and null safety?

Upvotes: 2

Views: 374

Answers (1)

jamesdlin
jamesdlin

Reputation: 89995

Initializer lists aren't really meant to execute arbitrary code. Usually the proper thing to do is to just call your validation function in your constructor body. Doing so would execute it after you've initialized your members (and executed all base class constructors), but:

  • Initializing members usually shouldn't have side-effects, so order shouldn't matter.
  • An exception from invalid arguments usually is a logical error and should crash the program anyway.

However, if for some reason you really must call your validation function before initializing members, you can cheat. Since initializer lists can contain asserts, you can add an assert that executes whatever function you want:

bool myValidationFunction(int x) {
  return x >= 0;
}

class Foo {
  int x;

  Foo(int x)
    : assert(myValidationFunction(x)),
      x = x;
}

Or if you want your validation function to throw instead of returning a bool:

void throwIfInvalid(int x) {
  if (x < 0) {
    throw ArgumentError('Invalid value: $x');
  }
}

class Foo {
  int x;

  Foo(int x)
    : assert(() { throwIfInvalid(x); return true; }),
      x = x;
}

Of course, asserts might not be enabled. If you want your validation function to be called unconditionally, you could just call a function in the process of initializing an existing member:

int checkIfValid(int x) {
  if (x < 0) {
    throw ArgumentError('Invalid value: $x');
  }
  return x;
}

class Foo {
  int x;
  
  Foo(int x)
    : x = checkIfValid(x);
}

Upvotes: 3

Related Questions