googlearchive / pedantic

How to get the most value from Dart static analysis
https://pub.dev/packages/pedantic
BSD 3-Clause "New" or "Revised" License
324 stars 56 forks source link

Don't allow `as` to be used in casting, it does more harm than good. #55

Closed dark-chocolate closed 4 years ago

dark-chocolate commented 4 years ago

I asked similar question on this comment, but the team didn't really respond quite well. I am thus creating a new issue.

You can either use as or type annotation to upcast or downcast things, let's take this example, where I have a SizedBox and I want to upcast to a Widget, so that I don't want to allow users to use width property on it, in this example I am using as to upcast, but this gives me a warning:

(Whenever I am writing bad in comment, that means it is undesired behavior, and good for desired one)

const widget = SizedBox() as Widget; // warning 
final width = widget.width; // error (good)

Now if I take warning into consideration and modify my code to silence pedantic, I can do:

const widget = SizedBox(); // no warning (good)
final width = widget.width; // no error (bad)

But this allows me to access width which I don't want.

Second solution is to use type annotation like:

const Widget widget = SizedBox(); // no warning (good)
final width = widget.width; // error (good)

So you can clearly see if I use as, I get myself in trouble and can only do limited things but if I use type annotation, I can do things the way I want. Let's take one more example into consideration (thanks to @eernstg )

final foo = 1 as String; // no error (bad)
final String bar = 1; // error (good)

As you can see if I am again comparing as with type annotation, the latter has advantages almost everywhere.

davidmorgan commented 4 years ago

Thanks! All makes sense to me at least ;)

pedantic isn't the right place to discuss, though; this package is just about publishing the analyzer configuration we use internally at google3.

I think the right place would be either the SDK or the linter

https://github.com/dart-lang/sdk/issues/new https://github.com/dart-lang/linter

--would you mind refiling at one of those, please? :)

dark-chocolate commented 4 years ago

@davidmorgan Sure sir, I am opening it in linter.