1

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();
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
user1338952
  • 3,233
  • 2
  • 27
  • 41
  • What's wrong with restricting the scope to the library? `void _sniff()` – MarioP Aug 07 '13 at 07:39
  • sniff is bad example, I should have used something only big dogs do. But, using private _sniff does not address the general problem. It's like saying, "here is a nice interface, go make all the derivatives you want, just make sure all methods you add are private". I don't want to stop the world from sniffing, just base Dog instances. The reason this came up is I had some thorough tests that were all passing, but I use emacs. I loaded project into Dart Editor and found the issues. I don't want to change the language, just automate a requirement for 0 or near 0 analysis warnings. – user1338952 Aug 07 '13 at 12:13

2 Answers2

1

This isn't possible. The problem is that your instance really is a BigDog; and therefore it really has a sniff method. An important goal in Dart is that type annotations do not affect runtime behaviour; therefore your Dog annotation is unable to change the behaviour.

The tooling is able to highlight this because it does use the type annotations.

This sort of question comes up a lot in the Dart bug tracker; but it would be a pretty fundamental change to allow type annotations to change behaviour, so it's not something I expect would ever be considered; confusing as it might be. See here for some more info on this.

Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275
1

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567