how do I make analysis warnings trigger runtime failure

Issue

In the following example, main is allowed to call a sniff function on Dog that I would prefer would somehow break. If I say exactly what a Dog can do, but somehow the client knows more and can get the object to do more with that special knowledge – I think that is an encapsulation leak. I don’t necessarily want it to die in the general case, but is there a flag or way to run that would enforce that only methods be called if they exist. I know the language supports the knowledge that something is wrong since the Dart Editor displays a warning: The method ‘sniff’ is not defined for the class ‘Dog’. Even when run with –checked flag, this runs fine.

So suppose similar code were invoked by a test. Is there a flag in Dart or some code to cause it to fail when the test is run?

abstract class Dog {
  void run();
  void bark();
}

class BigDog implements Dog {
  void run() => print("Big dog running");
  void bark() => print("Woof");
  void sniff() => print("Sniff");
}

main() {
  Dog bd = new BigDog();
  bd.run();
  bd.bark();
  bd.sniff();
}

Solution

You should ensure to run the tests in checked mode dart -c testfile.dart then type annotations are taken into account. You shouldn’t use checked mode in production though because it slows down your application.

Answered By – Günter Zöchbauer

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *