dart-lang / dart-lang/language

Deprecate and remove adjacent strings

Open
#1,982 16 comments 9 reactions 0 assignees View on GitHub
technical-debt
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

Early in Dart's history, the `+` operator was removed on strings. You could not write:

```dart
var hello = 'Hello';
print(hello + 'world!');
```

The argument at the time was that in other languages, users would build up long strings using a series of `+` concatenations which could involve allocating many many intermediate strings and was much less efficient than using StringBuffer. To prevent users from accidentally writing this suboptimal code, the core library outright forbid concatenating strings with `+` *at all*.

This presented a problem. Sometimes, a string literal does not fit in a single line. Without `+`, there is no easy way to break that literal into multiple lines:

```
// Long line. :(
var someQuiteLongVariableName = 'This string literal contains no newlines but does not fit on one line.';
```

To alleviate that, Dart added support for *adjacent strings*. Like C/C++ (well, really, the C preprocessor that both share), you are allowed to have multiple string *literals* one after each other. When you do, the language implicitly concatenates them at compile-time into a single string literal.

Some time later, the user-hostile removal of `+` was reverted and you could use `+` on strings again like almost every other language. That left two ways to concatenate string literals. Since adjacent strings are shorter, idiomatic Dart code continues to use those.

However, adjacent strings are prone to subtle errors. Consider:

```dart
var fruits = [
'apple',
'banana'
'cherry',
'date'
];
```

Spot the bug? The compiler won't. This is perfectly valid Dart code. It's just valid Dart code that happens to think "bananacherry" is some kind of exotic fruit. When adjacent strings appear in argument lists, the Dart formatter tries to insert indentation to make bugs like more obvious, but it's still a footgun.

It's also a redundant feature now that we have `+` one strings. (And any reasonable Dart implementation can evaluate the `+` at compile time when it sees that the two operands are string literals.)

We are considering simplifying the language and cleaning up some cruft in a future Dart 3.0 release. I propose that we:

1. Change the style guide to recommend avoiding adjacent strings.
2. Add support in `dart fix` to automatically insert `+` between adjacent strings.
3. Some time later, mark them deprecated.
4. Remove adjacent strings in Dart 3.0.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.