Sdk: "Re-abstracting" a method

Created on 3 Jan 2017  路  3Comments  路  Source: dart-lang/sdk

I wish there was a way to override an inherited method in such a way that the analyzer would complain if it wasn't reimplemented by further subclasses.

That is:

  • abstract class A implements method test() with a default behaviour (e.g. return null).
  • abstract class B extends A, but wants to indicate that the default behaviour of test() isn't ok for B subclasses, and B subclass implementations must implement a "real" test().
  • class C extends B. I want a warning from the analyzer if C doesn't implement test().

Right now you can declare an abstract method that overrides a concrete one but both the analyzer and the compiler just ignore it, which is weird:

abstract class A {
  void test1() { print('should never be shown'); }
}

class B extends A {
  @override
  void test1(); // no warning, even though B isn't abstract and declares an abstract method
}

class C extends B { } // no warning, but this is where I would really want one

void main() {
  new C().test1(); // calls A.test1() instead of failing because B.test1 has no implementation
}
P3 area-analyzer type-enhancement

Most helpful comment

A @mustOverride annotation would be great for this.

All 3 comments

There is no language-based way to do what you ask for. If the new method didn't have the same signature, then it would effectively become "abstract" again - subclasses that don't override the method won't correctly implement their own interface, which gives a warning. If it has the same signature, that is not a problem, the class has a correctly typed implementation for all its interface's members.

(The rule is that a non-abstract class must implement its own interface, which an abstract method doesn't help you with - an abstract method is just a way to add something to the interface without adding it to the class itself).

There is no plan to add such a feature to the language. The object model of Dart is fairly simple, and I don't think an addition like this would carry its own weight. I don't think there is an @mustOverride annotation in package:meta, so it would have to be added, if the analyzer wants to support it.

I agree with Lasse: the language has easy semantics, and this use case is probably not strong enough to warrant changes to the language.

However, I'm generally in favor of improving the communication between the developer and the analyzer/editor. On the one hand this just passes the bucket, but on the other hand this should allow us more flexibility.
The most important criteria for these "communication means" is that they must not change the actual semantics. That is, your program would still run when users don't override test1.

Also, I'm obviously worried that programs will have annotations all over the place, but we can tackle that problem when we see it.

A @mustOverride annotation would be great for this.

Was this page helpful?
0 / 5 - 0 ratings