Skip to content

Make new optional #20750

Closed
Closed

Description

@Zectbumo

I see how new makes it familiar to new programmers but the new keyword is really not necessary in the end. Dart has named constructors and static methods and it is up to the library maker to decide which is appropriate to use. Currently named constructors need `new' while static methods do not. My focus here is to relieve the programmer of having to remember what side of the bed the library developer woke up on and remembering do I need the new keyword or not.

Story time:
One day a library developer woke up and said parsing ints from strings is "discovering" the int so therefore it is not a constructor and a static method instead: Integer.parse(); was born. The library user MUST NOT use new to construct this Integer. Then another morning a library developer makes Element.html() and this time he think this is a constructor. The library user MUST use new to create his Element. This requires the library user to stop and think, do I need new or not?, when really in the end the library user just wants an object created; it doesn't matter how it's made.

Before:

var now = new DateTime.now();
var num = Integer.parse('54');
var elm = new Element.html(<u>54&lt;/u&gt;');

After (optional):

var now = DateTime.now();
var num = Integer.parse('54');
var elm = Element.html('<u>54</u>');

A discussion in issue #18241 talks about making const and new together being optional. This issue was created to focus on just making the new keyword optional.

Activity

  1. DartBot commented on Aug 29, 2014

    @DartBot

    This comment was originally written by @zoechi


    What about cases without a named constructor or do you propose to use only named constructors?
    var car = Car.new(); // rather ugly in my opinion.

  2. DartBot commented on Aug 29, 2014

    @DartBot

    This comment was originally written by norman...@gmail.com


    'new' makes it clear that we instantiate new object, not referencing to existing variable.

  3. Zectbumo commented on Aug 29, 2014

    @Zectbumo
    Author

    …do you propose to use only named constructors?
    var car = Car.new(); // rather ugly in my opinion.

    No. Nameless constructors are fine the way they are.

    What about cases without a named constructor…

    For consistency sake I would say make new optional there as well.

    var buf = new StringBuffer();
    or
    var buf = StringBuffer();

    I think it's pretty clear what is going on here. Even if new is made to be required in the nameless constructor case and optional in the named case then I would understand. I leave it in your hands to make the call.

  4. DartBot commented on Aug 30, 2014

    @DartBot

    This comment was originally written by @Emasoft


    Please don't. That would make the code much less readable. You would not be able to distinguish methods calls from class instantiations anymore.
    Also using static constructors give no advantage at all.
    You have to type the same number of characters for:

    var car = Car.new();
    or
    var car = new Car();

    It is completely useless, and it would drastically reduce readability of code.

  5. DartBot commented on Aug 30, 2014

    @DartBot

    This comment was originally written by @richardeakin


    Please don't. That would make the code much less readable. You would not be able to distinguish methods >> calls from class instantiations anymore.

    In other languages that don't require the new keyword to make an object, like C++, python, and newer language's like Apple's swift, method calls and class instantiation is completely distinguishable. The reason is simply that the way you write the code makes it clear (method names start with lower case, classes start with upper case). In all practicality, this is all the information you need to determine when a new object is constructed, as 98% (or more) of all code out there follows by this simple style rule.

    I'll even go as far as to say that it really doesn't matter anyway, I've never had a problem with 'knowing where something was originally constructed' using the C++ standard library (constructors look_like_this()), methods can always return a newly constructed object and you would not know at the call site. If one is worrying about something like where objects are constructed, there are probably much larger things wrong with the structure of their codebase.

  6. anders-sandholm commented on Sep 1, 2014

    @anders-sandholm

    Added Area-Language, Triaged labels.

  7. DartBot commented on Sep 1, 2014

    @DartBot

    This comment was originally written by nino.porcino...@gmail.com


    if 'new' is made optional, then also 'const' (from constant constructors) should be optional too. The semantic should be:

    var p = Point(); // alias for var p = new Point(); if Point is normal constructor
    var p = Point(); // alias for var p = const Point(); if Point is const constructor

  8. Zectbumo commented on Sep 1, 2014

    @Zectbumo
    Author

    if 'new' is made optional, then also 'const'

    No, optional const has it's own issues. See issue #18241

  9. Zectbumo commented on Sep 1, 2014

    @Zectbumo
    Author

    If the use of new is important to you then it should be an entry in your style guide to prefer new.

  10. lrhn commented on Sep 1, 2014

    @lrhn
    Member

    Since we have factory constructors, there really is no functional distinction between:

    class C { factory C.foo() => expr; }

    and

    class C { static C foo() => expr; }

    Constructors are intended to be a recognizable way to get objects of a type. If I want a Foo, I'll look at Foo constructors to see which one I can use.
    I could just as well be looking at static functions that return Foo.

    The reason factory constructors exists is that if you use a constructor, then the call points use "new", and then you can't replace the constructor with a static function. If there hadn't been a "new" operator, and being a constructor was a property of a method, not of its usage, then there would be no need for factory constructors.

    (By extension, a feature that makes sense for factory constructors, like being a delegating factory constructor, could just as well apply to all static methods).

  11. DartBot commented on Sep 1, 2014

    @DartBot

    This comment was originally written by @seaneagan


    Constructors are intended to be a recognizable way to get objects of a type. If I want a Foo, I'll look at Foo constructors to see which one I can use. I could just as well be looking at static functions that return Foo.

    Yep, the api doc tool could even consider those to be "Constructors" and group them for the user. With the current setup if the api user needs to first look through the constructors and static methods to determine all the ways to create an instance, and they need to remember which category each falls into rather than just remembering the name.

    The reason factory constructors exists is that if you use a constructor, then the call points use "new", and then you can't replace the constructor with a static function.

    But as an api user there's nothing that guarantees me that the api author won't refactor to a static method, if new were optional then api authors can omit it to protect themselves from such a refactoring. And same goes for the reverse refactoring from static method to refactoring, an optional new would protect users from that as well.

    If there hadn't been a "new" operator, and being a constructor was a property of a method, not of its usage, then there would be no need for factory constructors.

    Of course we would need generic methods (issue #254) for that, which would be great to have anyways. And there would need to be a way to create an unnamed static method, which wouldn't be too difficult to come up with a declaration syntax for.

  12. DartBot commented on Sep 2, 2014

    @DartBot

    This comment was originally written by @Emasoft


    A programming language must be EXPRESSIVE. Because if it is not, it is not easily readable. And if it is not easily readable it is much more difficult to learn, much more difficult to find errors in the code causing bugs, and much more difficult to integrate the code written by other developers and to understand how it works. Being EXPRESSIVE is now considered a major feature of a language. And:

    var car = Car();

    is less expressive than:

    var car = new Car();

    because just reading the former I cannot infer if Car() is a Method or a Class, while if I read the latter I can infer that Car() is a Class at a glance.

    This is why using the "new" keyword is so much better than not using it. There are other possible advantages, but this is the main one.

  13. Zectbumo commented on Sep 2, 2014

    @Zectbumo
    Author

    because just reading the former I cannot infer if Car() is a Method or a Class

    Incorrect, you can infer Car is a class because the C is capitalized.

  14. DartBot commented on Sep 2, 2014

    @DartBot

    This comment was originally written by @richardeakin


    because just reading the former I cannot infer if Car() is a Method or a Class

    Incorrect, you can infer Car is a class because the C is capitalized.

    I agree, and moreover you really don't need to know whether the method is a constructor or a class - you just need to know that it returns a new variable of type Car.

    I believe the use of new keyword is more familiar to those who have had the habit engrained into them by working with java, javascript, or c# for a long time. Many others find the following statements much more expressive:

    var pt = Point( 2, 3 ) + Point( 4, 5 ) + Point( 6, 7 );

    as compared to what is currently required (and appears to only be for stylistic and habitual reasons):

    var pt = new Point( 2, 3 ) + new Point( 4, 5 ) + new Point( 6, 7 );

    Honestly, when I was reading response #­12, I thought he/she was going to be in favor of making new optional until he/she began writing example code!

    About expressiveness, I think it is more than just being readable - it is also about being able to efficiently code your thoughts. I think writing new 3 times in one line hinders this goal, IMO.

  15. DartBot commented on Sep 2, 2014

    @DartBot

    This comment was originally written by @richardeakin


    Sorry for typos, meant to write:

    "...you really don't need to know whether Car() is a method or class constructor..."

    Anyway point being, it returns a variable that didn't exist before that line, that is sufficient.

  16. 22 remaining items

  17. Emasoft commented on Mar 31, 2017

    @Emasoft

    @hooluupog What? The Dart design team already made the code unreadable enough making 'new' optional. Now you suggest to make type names optional? How the hell I'm supposed to know what this line of code means, for example?

    myObject.MyMethod([(1,"abc"), (2,"abcd"),...])

    Somebody is forgetting that readability and understandability of code is the MOST IMPORTANT FEATURE of a programming language. Otherwise we would all be better to keep writing in binary 010101...

  18. hooluupog commented on Apr 1, 2017

    @hooluupog

    @Emasoft I do not suggest to make type names optional.In fact,I fully support strong type. What i mean is to remove unneeded redundancy. Even in Go(which is a very opinionated language),I
    can write var list = []A{{1,"abc"}, {2,"abcd"},...} //A is a struct type in Go.

  19. Emasoft commented on Apr 1, 2017

    @Emasoft

    @hooluupog I can still read the type in your Go example. The A is at the right side of the assignement operator. Not so in your proposal. At the right side of '=' you don't have type names anymore, and this is confusing.

    Showing it at the left side is not enough. Not only I cannot use the 'var' to infer the type, but also because If I can declare a List just like you say:

    List<A> list = [(1,"abc"), (2,"abcd"),...];

    ...then I should be able to pass the same expression to a method with the following signature:

    void MyMethod(List<A> list);

    ..resulting in:

    myObject.MyMethod([(1,"abc"), (2,"abcd"),...])

    But then how I'm supposed to know what this line of code means?

    Can you see what the problem is?

  20. lrhn commented on Apr 2, 2017

    @lrhn
    Member

    That particular shorthand is unlikely to be accepted. Apart from the lower readability, it's also ambiguous. It looks simple here because the A constructor takes two arguments, but what if it was just

    List<B> list = [(x + 2)];

    It's very non-obvious that you need to coerce x + 2 to B. Also, it assumes that you will use the empty-named constructor (new B(x + 2)), but there is no help in using a named constructor - if B.foo is the right one to use, this syntax doesn't allow it.
    I'm more interested in explicitly omitting the class name where it's given, so maybe something like:

    List<B> list = [.foo(x + 42)];

    would mean that the omitted thing before the . is the expected type.

  21. Emasoft commented on Apr 2, 2017

    @Emasoft

    @irhn That . is hard to spot. You can easily miss it, or type it by error. That is an even more unreadable expression.

    Readability must be paramount. Do you know that on average we spend 87% of the development time debugging and looking for errors in the code and only 13% of the time actually writing the code?
    After all this years there is still people (script kiddies, mostly) who think that typing less characters is cool or smart... well, I have bad a news for them: it is dumb. The dumbest thing you can do.

  22. zoechi commented on Apr 2, 2017

    @zoechi
    Contributor

    I don't think the . is too hard to spot (I guess better syntax ideas are always welcome though).
    Also I'd expect the analyzer to generate an error in case it is typed unintentionally.

    I also don't think writing less code is an important goal, but more code is more to read and redundant information, like repeated type annotations, often make code harder to read, which should be a good enough reason to try to get rid of them.

  23. Emasoft commented on Apr 4, 2017

    @Emasoft

    The . is the smallest character of all, of course it is hard to spot! It is also used for MULTIPLE functions. You can have many dots one near each other, with different functions, when you use floating point numbers (0.011*-1.2/4-.A*4.21-.B*0.11-.A-.102+1.2-.A*0.1-.B-.01/.A+.3 <- try to guess if there is a dot that is not right). There is a basic language design imperative, and that is to make errors easy to spot.

  24. zoechi commented on Apr 4, 2017

    @zoechi
    Contributor

    It takes as many space as any other character ;-) and there are no other places where . comes before a non-numeric character, therefore I find it quite distinctive. . before numeric characters is quite seldom and usually stands out as number value. As mentioned I can imagine that there are better options, which is why I wrote "(I guess better syntax ideas are always welcome though)"
    And the options are quite limited, because other symbol characters are already in use for other constructs.

  25. eernstg commented on Feb 20, 2018

    @eernstg
    Member

    Closing: With the feature specification on implicit creation, it has been decided that Dart will have the feature which is requested here. ;-)

    For an instance creation expression (say, new C(42) or const C(42)) it is allowed to leave out the new or const keyword (yielding C(42)). The decision about whether such an expression means new ... or const ... is a little bit involved, but the main idea is that it will be const whenever possible, and otherwise new; said feature specification has the details.

    Implementation of this feature is ongoing.

  26. sethladd commented on Feb 20, 2018

    @sethladd
    Contributor

    Cool! is there a tracking issue for the implementation?

  27. eernstg commented on Feb 20, 2018

    @eernstg
    Member

    Yep: #30921. Note that the 'Specification' subtask isn't checked, but that is the language specification proper. The design has been finalized and agreed to, and it is documented in the feature specification for implicit creation. That material will later be integrated into the language specification.

  28. redradist commented on Aug 11, 2019

    @redradist

    Guys, from my point of view having "new" keyword for instance creation and without it, seems like noisy
    ... Because it is two different ways of creation of object ...

    Will be new keyword removed in future completly ?

  29. lrhn commented on Aug 12, 2019

    @lrhn
    Member

    No promises. I hope it will be removed at some point, but it's a low-priority and heavily breaking change, so the cost/benefit ratio is not in its favor as a stand-alone change.

    If we have another related language change, we may be able to roll the removal of new into that (if you are going to run a migration program on your code, we can remove the new for you as well).
    It's probably not something we'll do as part of an otherwise unrelated language change.

  30. eernstg commented on Aug 12, 2019

    @eernstg
    Member

    Eliminating new completely is not obviously an improvement. If you use new e with some term e rather than e on its own then you've specified that evaluation must invoke a constructor. This is not an ironclad guarantee that it will yield a fresh object (but the exception, a factory constructor, is written knowing that it should be OK to view the returned object as fresh). So a few well chosen new keywords might be helpful for the reader of a piece of code.

    A lot of valuable work has been done in the area of lints for Dart, and it seems that the community is quite happy about having support for specifying various constraints on code. The ability of the new keyword to specify a constraint on the code ("this expression builds a new object") and have tool support for verifying it makes it fit in with this trend.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).customer-fluttertype-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions