Repository navigation
Description
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</u>');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
DartBot commentedon Aug 29, 2014
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.
DartBot commentedon Aug 29, 2014
This comment was originally written by norman...@gmail.com
'new' makes it clear that we instantiate new object, not referencing to existing variable.
Zectbumo commentedon Aug 29, 2014
No. Nameless constructors are fine the way they are.
For consistency sake I would say make
newoptional there as well.var buf = new StringBuffer();
or
var buf = StringBuffer();
I think it's pretty clear what is going on here. Even if
newis 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.DartBot commentedon Aug 30, 2014
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.
DartBot commentedon Aug 30, 2014
This comment was originally written by @richardeakin
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.
anders-sandholm commentedon Sep 1, 2014
Added Area-Language, Triaged labels.
DartBot commentedon Sep 1, 2014
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
Zectbumo commentedon Sep 1, 2014
No, optional const has it's own issues. See issue #18241
Zectbumo commentedon Sep 1, 2014
If the use of
newis important to you then it should be an entry in your style guide to prefernew.lrhn commentedon Sep 1, 2014
Since we have factory constructors, there really is no functional distinction between:
and
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).
DartBot commentedon Sep 1, 2014
This comment was originally written by @seaneagan
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.
But as an api user there's nothing that guarantees me that the api author won't refactor to a static method, if
newwere 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 optionalnewwould protect users from that as well.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.
DartBot commentedon Sep 2, 2014
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.
Zectbumo commentedon Sep 2, 2014
Incorrect, you can infer Car is a class because the C is capitalized.
DartBot commentedon Sep 2, 2014
This comment was originally written by @richardeakin
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.
DartBot commentedon Sep 2, 2014
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.
22 remaining items
Emasoft commentedon Mar 31, 2017
@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...
hooluupog commentedon Apr 1, 2017
@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.Emasoft commentedon Apr 1, 2017
@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?
lrhn commentedon Apr 2, 2017
That particular shorthand is unlikely to be accepted. Apart from the lower readability, it's also ambiguous. It looks simple here because the
Aconstructor takes two arguments, but what if it was justIt's very non-obvious that you need to coerce
x + 2toB. 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 - ifB.foois 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:
would mean that the omitted thing before the
.is the expected type.Emasoft commentedon Apr 2, 2017
@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.
zoechi commentedon Apr 2, 2017
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.
Emasoft commentedon Apr 4, 2017
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.zoechi commentedon Apr 4, 2017
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.
eernstg commentedon Feb 20, 2018
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)orconst C(42)) it is allowed to leave out theneworconstkeyword (yieldingC(42)). The decision about whether such an expression meansnew ...orconst ...is a little bit involved, but the main idea is that it will beconstwhenever possible, and otherwisenew; said feature specification has the details.Implementation of this feature is ongoing.
sethladd commentedon Feb 20, 2018
Cool! is there a tracking issue for the implementation?
eernstg commentedon Feb 20, 2018
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.
redradist commentedon Aug 11, 2019
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 ?
lrhn commentedon Aug 12, 2019
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
newinto that (if you are going to run a migration program on your code, we can remove thenewfor you as well).It's probably not something we'll do as part of an otherwise unrelated language change.
eernstg commentedon Aug 12, 2019
Eliminating
newcompletely is not obviously an improvement. If you usenew ewith some termerather thaneon 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 chosennewkeywords 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
newkeyword 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.