-
Notifications
You must be signed in to change notification settings - Fork 121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New tall style: Automated trailing commas and other formatting changes #1253
Comments
I like it. I manually add trailing commas a lot in just the style that this proposal would handle automatically. This would save me time and effort. Below are a few comments after trying out the prototype implementation. Tall style readabilityI often have a series of @override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Padding(
padding: EdgeInsets.all(8.0),
child: Center(
child: Column(children: [
Text('Hello'),
Text('Dart'),
Text('World')
])))),
);
} I usually add in trailing commas like this: @override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Padding(
padding: EdgeInsets.all(8.0),
child: Center(
child: Column(
children: [
Text('Hello'),
Text('Dart'),
Text('World'),
],
),
),
),
),
);
} However, I noticed the proposed formatter takes my carefully crafted formatting and does the following with it: @override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Padding(
padding: EdgeInsets.all(8.0),
child: Center(
child:
Column(children: [Text('Hello'), Text('Dart'), Text('World')]),
),
),
),
);
} That's not terrible, but putting all of the Column elements on one line just because they fit isn't the most readable way of displaying them. It's possible to use a comment hack (see the next section) to force tall style, but I don't know if that's what you intend to become common practice. Forcing tall styleWhen I make enums, sometimes I like the tall style even if they would fit on one line: enum Colors {
red,
green,
blue,
} The proposed formatter wouldn't allow that anymore and would reformat the code above to the following: enum Colors { red, green, blue } That's no problem with me. I can get used to that. And if I really want to keep the tall style, I can add a comment after the last item like so: enum Colors {
red,
green,
blue, //
} Now the proposed formatter leaves my code style alone. The following is a bug, I think, but if I add a comment after the second item like so: enum Colors {
red,
green, //
blue,
} The proposed formatter breaks the code (and its promise not change more than the style): enum Colors { red, green, // blue } |
Thank you for the feedback! Re: child:
Column(children: [Text('Hello'), Text('Dart'), Text('World')]), Yeah, that looks like a bug in the prototype. I wouldn't expect it to split after a named parameter like this. It should produce output closer to what you have with the current formatter and explicit trailing commas.
That's definitely a bug. The prototype is, uh, pretty prototype-y. :) |
I find the proposed style quite a bit less consistent. This example comes from https://github.com/dart-lang/sdk/blob/main/pkg/js_ast/lib/src/nodes.dart Old - there are basically two formats for the visitor methods, one-line and two-line. T visitVariableDeclarationList(VariableDeclarationList node) =>
visitExpression(node);
T visitAssignment(Assignment node) => visitExpression(node);
T visitVariableInitialization(VariableInitialization node) =>
visitExpression(node); New - there are now three formats, depending on where the line splits are. T visitVariableDeclarationList(
VariableDeclarationList node,
) => visitExpression(node);
T visitAssignment(Assignment node) => visitExpression(node);
T visitVariableInitialization(VariableInitialization node) => visitExpression(
node,
); The formatting does not help me see these methods all do the same thing. The line-breaks here fight against a cognitive principle. Programs, like sentences, have structure. The big things are composed of little things, and it is helpful to ingest the small concepts completely. Line breaks in the middle of small things hinder that. Breaks higher up the semantic structure are less disruptive: The nervous chicken is clearer than The nervous The proposed formatting is too much like the latter. Here is an example from the same package where the main point gets lost Instantiator visitLiteralExpression(LiteralExpression node) =>
TODO('visitLiteralExpression'); ⟶ Instantiator visitLiteralStatement(LiteralStatement node) => TODO(
'visitLiteralStatement',
); I believe there is a middle ground that is a little bit of the old style for smaller statements, expressions and definitions, and a little bit of the proposed style for larger constructs. |
Generally in agreement. I do generally prefer my commas a the start of the line as it's easier to see that it's a continuation but I suspect I'm in the minority. callSomething(a
, b
, c); |
I agree. Manually adding trailing commas has been such a pain! Having to not type them manually for better formatting would be great! |
Love it! The formatter using "short style" is the main reason why I actually don't use it, and tell my team to disable it when working on Flutter projects. Tall style is much more my style and I'd be way more likely to use the formatter consistently if it switched to that. Regarding T visitVariableInitialization(VariableInitialization node) =>
visitExpression(node); vs T visitVariableInitialization(VariableInitialization node) => visitExpression(
node,
); I would personally aim for the first version for shorter constructs, but in general, the second version does scale better for longer expressions. So I'd understand if the formatter picked the "wrong" one because humans disagree on this too. |
I really like the proposal! One nit I have is this: // Before:
var something =
function(argument);
// After:
var something = function(
argument,
); I like Before better. To me, in this particular case, it's more readable, because we're keeping the I feel quite strongly about this when it comes to functions. I'm not so sure when it comes to constructors ( I agree with @Levi-Lesches's comment above (#1253 (comment)). |
A good idea but to know if the implementation is indeed good will take time |
There are a few cases where I don't use trailing comma.
// Single token single argument
foo(10); // <--- No trailing comma
// Multi token single argument
foo(
numberFromText('ten'),
);
foo(1, 2, 3); // <--- No trailing comma
// Instead of
foo( // <--- Unnecessarily long
1,
2,
3,
) Other than that, I always use trailing comma. Overall, I think this is a good change. I think I would only avoid the case (1), as it's really unnecessary, but it would obviously make things more complicated. |
My observation is that adding optional trailing commas almost always improves code readability, because it forces the formatter to put everything on a separate line, which implicitly enforces a "one concept per line"-rule, and I have found that to be very helpful when reading code.
I think that automatically adding optional trailing commas could be helpful and I wouldn't be against that, but I think I wouldn't want the formatter to remove anything from my code except empty newlines. I want things to be on separate lines more often than not, and an explicit optional trailing comma has worked well as a way to tell the formatter that that's what I want. If this moves forward, I think it would be great if this could be part of a bigger effort to promote more optional trailing commas as the preferred style (in, e.g., the form of recommended guidelines) + new syntax to support optional trailing commas in more places (e.g. dart-lang/language#2430) |
Could this also account for pattern-matching formatting? Currentfinal child = switch (a) {
B() => BWrapper(
child: const Text('Hello B'),
), // two spaces that feel redundant
C() => CWrapper(
child: const Text('Hello C'),
), // two spaces that feel redundant
}; Desiredfinal child = switch (a) {
B() => BWrapper(
child: const Text('Hello B'),
),
C() => CWrapper(
child: const Text('Hello C'),
),
}; UPD: I've used final child = switch (a) {
B() =>
BWrapper(child: const Text('Hello B'), prop: 'Some long text goes here'),
C() =>
CWrapper(child: const Text('Hello C'), prop: 'Some long text goes here'),
}; |
Yeah, there's probably some tweaks needed there to harmonize with the proposal. Thanks for bringing that example up. :) |
This hurts my eyes so bad 😆 Getting rid of this would lift a lot of OCD pain when writing code |
Thanks for getting this prototype together and soliciting feedback! After trying it on some of our code, the main piece of feedback that wasn't already mentioned already is that being able to force the "tall" style with trailing commas is unfortunate. It doesn't happen often, but when using longer line lengths where function calls don't "need" to wrap as often, you can get code that's a bit harder to read (especially when it's parentheses-heavy 😅). For example, at line length 120: // Current
(Dom.div()..addProps(getModalBodyScrollerProps()))(
renderCalloutIcons(),
props.calloutHeader,
props.children,
),
// Prototype
(Dom.div()..addProps(getModalBodyScrollerProps()))(renderCalloutIcons(), props.calloutHeader, props.children), This problem also exists for map literals, which, unlike the example above, seem to be affected more often at smaller line lengths.
We'd probably end up decreasing our line lengths to get better wrapping, which isn't ideal for some of our packages with longer class and variable names. I realize, though, that 120 is quite a bit larger that dart_style's preferred line length of 80, so I'd understand if we'd have to move closer to that to get good formatting. But for map literals, perhaps the rules could be tweaked to prefer "tall" style more often? For example, force “tall” style if a map has more than 2 or 3 elements, or if it contains more than 1 |
I prefer the old version generally, but I'm willing to accept that I'm in the minority on that one and global consistency is more important than my preferences. I'll echo that I don't like the splitting behavior for formerly-2-line ModifiableCssSupportsRule copyWithoutChildren() =>
ModifiableCssSupportsRule(condition, span); becomes ModifiableCssSupportsRule copyWithoutChildren() => ModifiableCssSupportsRule(
condition,
span,
); which is actually taller than ModifiableCssSupportsRule copyWithoutChildren() {
return ModifiableCssSupportsRule(condition, span);
} ...which goes against the grain of |
Nice! Overall, I'm in favor, though I'm not sure which heuristics would work well for all cases, particularly involving collections. For example, in a layout container, I'd never want it to smash all children into a single line: return Center(
child: Column(
children: [Text('Loading... please wait'), CircularProgressIndicator()],
),
); Also, since this extra indentation of 2 levels goes completely against the grain, I'm guessing it wasn't intentional? placeholder: (context, url) => Center(
- child: CircularProgressIndicator(
- backgroundColor: Colors.white,
- ),
-),
+ child: CircularProgressIndicator(
+ backgroundColor: Colors.white,
+ ),
+ ), |
I think enums should always be in the tall style just because reading each enumeration one line at a time makes it much easier to grasp what it's doing. I'd even support the tall style for enums that have just one member. For functions, perhaps we should switch short vs tall based on the number of arguments, where one or two is short but 3 or more becomes tall (which is usually what I already do manually by adding commas), as well as basing it on column widths. We can even combine short and tall, perhaps: ModifiableCssSupportsRule copyWithoutChildren() =>
ModifiableCssSupportsRule(
condition,
span,
anotherArgument,
); This is because I generally don't want to scroll all the way right just to see what is being returned in the arrow syntax. It is in the same vein as: return Center(
child: Column(
children: ...
),
);
// instead of
return Center(child:
Column(children:
...
),
); That is to say, the first (and current) example keeps things as left aligned as possible which makes scanning files much easier. Tthe combination of both short and tall as above feels to me to be a good compromise and is even more readable left to right, top to bottom, than either short or tall alone. With regards to column widths, the formatter should check that first, then the number of arguments in a function or elements in an array or map, ie even if the following only has two elements, it should still force the tall version: return Center(
child: Column(
children: [
Text('Loading... please wait'),
CircularProgressIndicator(),
],
),
); Beyond that, I like the proposal as it saves a lot of time manually adding commas. I generally prefer the tall style for consistency. |
Why not adding a formater config so users can choose their style.... dartformat.yaml |
https://github.com/dart-lang/dart_style/wiki/FAQ#why-cant-i-configure-it |
This one's a bug in the prototype. If a named argument's value is a closure, then it shouldn't add an extra +4 indentation like that. I'll fix that in the real implementation. |
Gets my 👍! I tend to use trailing commas a lot (even when not controlling the formatter, I like to not have extra modified lines in my diff if I'm appending new arguments to a "tall" list!). I do have some questions though:
|
Yes.
There won't be any permanent opt-in or opt-out because we don't have the resources to maintain two formatting styles in perpetuity. There will be an experimental period where the new style is hidden behind a flag, mostly so that I can land in-progress work on master, but I expect few users to see that. Once it's fully working and ready to ship, there may be a temporary opt-in (or out, not sure about the default) in order to ease the migration for users. I'm waiting for feedback to come in to get a sense of how important it is. So far, based on survey results, it doesn't seem to be a high priority for most users. I'll try to get a better feel for what will help the community when a real implementation is farther along. I definitely want to minimize pain. |
I don't think it's necessarily high priority in terms of timeline (as I believe many will wait and adopt it when they wish to migrate) but it confers quite a large benefit to mental overhead as other languages don't really have this notion of changing commas to fix formatting, I've really only seen that in Dart. Most languages have their own fixed formatter, ie |
I think it is quite important to have this ability for Flutter code. Take for example this snippet: Row(children: [
Left(),
Right(),
]); This is not just a bunch of functions. It's a widget tree and formatting it in tall style reflects that. For this reason the Flutter documentation explicitly recommends to always add trailing commas in widgets to take advantage of this formatting behavior.
I find that enforcing trailing commas in places where wrapping happened anyway is not a problem in practice, since the |
I always thought controlling the formatter by just appending a The workaround to use a |
Yeah, that's not a bad idea. I'm interested in exploring this too. There is something roughly in the same direction in the current formatter in that it will split an outer collection literal if it contains another collection literal, even if the outer one otherwise doesn't need to split. I've considered other rules around splitting when not strictly necessary to fit the line length, but I haven't really tried to implement anything because it's not clear what those rules should be and how they should best adapt to different line lengths. One thing I've talked with @Hixie about is having the line length restriction work more like Prettier:
So instead of treating it like a hard limit (which it currently does), it would be a softer boundary where lines are somewhat punished for going over when calculating the cost, but not heavily. I'm interested in exploring this approach, but I'm not planning to do that for this proposed set of changes. There are enough changes already queued up with this as it is. :) |
Thanks @munificent for this proposal. Overall, I'm quite happy with the change. I was wondering how would this affect (or if it has been considered) matrix representation, since currently it is not very convenient to read matrices. I would like: Matrix4 m =
Matrix4(11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44); To be something as: Matrix4 m = Matrix4(
11, 12, 13, 14,
21, 22, 23, 24,
31, 32, 33, 34,
41, 42, 43, 44); Definitely not something as: Matrix4 m = Matrix4(
11,
12,
13,
14,
21,
22,
23,
24,
31,
32,
33,
34,
41,
42,
43,
44,
); The overall idea is simply to read the matrix as it is usually written in mathematics. This comment is somewhat related to what was mentioned here. |
@alestiago Matrix4 m = Matrix4(
11, 12, 13, 14, //
21, 22, 23, 24, //
31, 32, 33, 34, //
41, 42, 43, 44, //
); I hope this is still going to be a valid solution after the suggested change in this proposal. |
@julemand101 , thanks for hopping in! I also use the comments to avoid the new line, and also hope that this behaviour is improved or kept the same after the proposed changed. |
I use var value = function(val1, val2, val3, //
named4: val4,
named5: val5,
// ...
namedN: valN); Except definitions, I mostly use trailing comma only for constructor calls. |
I want to discuss the case of adding dartdoc and refactoring changing the method to Future. Take the case where someone creates an enum and I add a dartdoc. In this case, whether the new format diffs only dartdoc or the entire enum depends on the number of enums and the length of their names. // before (short)
enum SomeReasonableEnum { reasonA, reasonB }
// after
enum SomeReasonableEnum {
/// The reason of A
reasonA,
/// The reason of B
reasonB,
}
// before (long)
enum SomeReasonableLoooooongEnum {
reasonA,
reasonB,
}
// after (long)
enum SomeReasonableLoooooongEnum {
/// The reason of A
reasonA,
/// The reason of B
reasonB,
} Take the case where a method is changed from a synchronous to an asynchronous type. In the new format, the entire method definition tends to be the point of change, even if the only change is the return value. // before
SomeResponse someGoodMethod({ required SomeEnum key, required String value }) {
// after
Future<SomeResponse> someGoodMethod({
required SomeEnum key,
required String value,
}) async { Given this change, I basically feel that adding a trailing comma would make for a more readable code base. (If I write flutter at work, these changes occur frequently.) However, it is also understandable that many people want to write shorter code. For this reason, I feel it would be more appropriate to remove the traling comma in the following two cases, but add it in the others.
Thanks for asking for feedback. I love the dart and flutter community! |
Here's one case where this change will produce code that IMO is worse to read. I register all of my dependencies with getIt
..registerSingleton(AuthRepository(firebaseAuth: getIt(), mediaRepository: getIt(), authRemoteDataSource: getIt(), credentialsRepository: getIt(), userRepository: getIt(), webSocketDataSource: getIt()))
..registerSingleton(NotificationRepository(authRepository: getIt(), oneSignalAppId: oneSignalAppId)) With this style modification, a trailing comma will be added and it will turn into this: getIt
..registerSingleton(AuthRepository(
firebaseAuth: getIt(),
mediaRepository: getIt(),
authRemoteDataSource: getIt(),
credentialsRepository: getIt(),
userRepository: getIt(),
webSocketDataSource: getIt(),
))
..registerSingleton(NotificationRepository(
authRepository: getIt(),
oneSignalAppId: oneSignalAppId,
)) This app has over 100 lines of registered dependencies (400 after the new style), so keeping them one per line is really helpful to quickly scroll past them. As you can see the named parameters in this file are not very relevant (as the only thing they do is get a reference from |
Coming back to this: What about newlines? For example: a();
b();
c(); vs: a();
b();
c(); To me, newlines and trailing commas are fairly similar in purpose. They are small opinionated formatting tweaks. I assume folks in the team of "let's automate commas" would want automated newlines. Conversely, I'm sure folks who are sad to see trailing commas go away would disagree with the automation of newlines. |
I like when every enum member is on its own line, like this. enum Category {
food,
travel,
leisure,
work,
} Will there be any possibility to tune a formatter for this? |
As of #1578, the "tall-style" experiment is now enabled in the dart_style repo. 🎉 I'm not going to close this issue just yet because first it will need to roll into the Dart SDK and a few other places and I'm sure there will be loose ends to tie up, but it's getting close! |
I have this piece of code in my .dart file and it would be nice for the formatter to not move the Expected @override
Future<Result> onCommand(
PlanDiscountSelectorDialogViewModelCommand command,
) => switch (command) {
Load() => _onLoad(command),
}; Restult @override
Future<Result> onCommand(
PlanDiscountSelectorDialogViewModelCommand command,
) =>
switch (command) {
Load() => _onLoad(command),
}; |
@pedromassango I suggest you to adhere to Flutter's styleguide and only use fat-arrows for small single-line expressions, so: @override
Future<Result> onCommand(
PlanDiscountSelectorDialogViewModelCommand command,
) {
return switch (command) {
Load() => _onLoad(command),
};
} |
@pedromassango, would you mind filing a separate issue for that? Thanks. |
We're in [the process of](dart-lang/dart_style#1403) moving dart_style to [a new formatting style](dart-lang/dart_style#1253). That involves making the formatter [aware of the language version of what it's formatting](dart-lang/dart_style#1402). That in turn means that the library API now lets you pass in a language version. In dart_style 2.3.7 [you can pass in a language version but the parameter is optional](https://pub.dev/documentation/dart_style/latest/dart_style/DartFormatter/DartFormatter.html). In the forthcoming 3.0.0 release, that parameter will become mandatory. This updates every call to `DartFormatter()` to pass in the latest language version. If there's a more specific version that should be used, let me know and I'll update the PR. Thanks!
* Update dart_style to pass in a language version to DartFormatter. We're in [the process of](dart-lang/dart_style#1403) moving dart_style to [a new formatting style](dart-lang/dart_style#1253). That involves making the formatter [aware of the language version of what it's formatting](dart-lang/dart_style#1402). That in turn means that the library API now lets you pass in a language version. In dart_style 2.3.7 [you can pass in a language version but the parameter is optional](https://pub.dev/documentation/dart_style/latest/dart_style/DartFormatter/DartFormatter.html). In the forthcoming 3.0.0 release, that parameter will become mandatory. This updates every call to `DartFormatter()` to pass in the latest language version. * Update CHANGELOG and analysis_options.yaml. * Require Dart SDK 3.5.0.
We're in [the process of](dart-lang/dart_style#1403) moving dart_style to [a new formatting style](dart-lang/dart_style#1253). That involves making the formatter [aware of the language version of what it's formatting](dart-lang/dart_style#1402). That in turn means that the library API now lets you pass in a language version. In dart_style 2.3.7 [you can pass in a language version but the parameter is optional](https://pub.dev/documentation/dart_style/latest/dart_style/DartFormatter/DartFormatter.html). In the forthcoming 3.0.0 release, that parameter will become mandatory. This updates the call to `DartFormatter()` to pass in the latest language version. If there's a more specific version that should be used, let me know and I'll update the PR.
We're in [the process of](dart-lang/dart_style#1403) moving dart_style to [a new formatting style](dart-lang/dart_style#1253). That involves making the formatter [aware of the language version of what it's formatting](dart-lang/dart_style#1402). That in turn means that the library API now lets you pass in a language version. In dart_style 2.3.7 [you can pass in a language version but the parameter is optional](https://pub.dev/documentation/dart_style/latest/dart_style/DartFormatter/DartFormatter.html). In the forthcoming 3.0.0 release, that parameter will become mandatory. This updates the two calls to `DartFormatter()` in intl_translation/bin to pass in a language version. It attempts to look for a surrounding package_config.json file and uses the language version from that (which is what other Dart tools do). If that files, it just defaults to using the latest language version that the formatter supports.
We're in [the process of](dart-lang/dart_style#1403) moving dart_style to [a new formatting style](dart-lang/dart_style#1253). That involves making the formatter [aware of the language version of what it's formatting](dart-lang/dart_style#1402). That in turn means that the library API now lets you pass in a language version. In dart_style 2.3.7 [you can pass in a language version but the parameter is optional](https://pub.dev/documentation/dart_style/latest/dart_style/DartFormatter/DartFormatter.html). In the forthcoming 3.0.0 release, that parameter will become mandatory. This updates the call to `DartFormatter()` to pass in the latest language version. If there's a more specific version that should be used, let me know and I'll update the PR.
…rt-archive/code_builder#466) * Update dart_style to pass in a language version to DartFormatter. We're in [the process of](dart-lang/dart_style#1403) moving dart_style to [a new formatting style](dart-lang/dart_style#1253). That involves making the formatter [aware of the language version of what it's formatting](dart-lang/dart_style#1402). That in turn means that the library API now lets you pass in a language version. In dart_style 2.3.7 [you can pass in a language version but the parameter is optional](https://pub.dev/documentation/dart_style/latest/dart_style/DartFormatter/DartFormatter.html). In the forthcoming 3.0.0 release, that parameter will become mandatory. This updates every call to `DartFormatter()` to pass in the latest language version. * Update CHANGELOG and analysis_options.yaml. * Require Dart SDK 3.5.0.
-- f9f3ade by Robert Nystrom <rnystrom@google.com>: Pass a language version to DartFormatter(). We're in [the process of](dart-lang/dart_style#1403) moving dart_style to [a new formatting style](dart-lang/dart_style#1253). That involves making the formatter [aware of the language version of what it's formatting](dart-lang/dart_style#1402). That in turn means that the library API now lets you pass in a language version. In dart_style 2.3.7 [you can pass in a language version but the parameter is optional](https://pub.dev/documentation/dart_style/latest/dart_style/DartFormatter/DartFormatter.html). In the forthcoming 3.0.0 release, that parameter will become mandatory. This updates the two calls to `DartFormatter()` in intl_translation/bin to pass in a language version. It attempts to look for a surrounding package_config.json file and uses the language version from that (which is what other Dart tools do). If that files, it just defaults to using the latest language version that the formatter supports. PiperOrigin-RevId: 689754530
TL;DR: We're proposing a set of style changes to
dart format
that would affect about 10% of all Dart code. We want to know what you think.The main change is that you no longer need to manually add or remove trailing commas. The formatter adds them to any argument or parameter list that splits across multiple lines and removes them from ones that don't. When an argument list or parameter list splits, it is formatted like:
longFunction( longArgument, anotherLongArgument, );
This change means less work writing and refactoring code, and no more reminding people to add or remove trailing commas in code reviews. We have a prototype implementation that you can try out. There is a detailed feedback form below, but you can give us your overall impression by reacting to the issue:
We have always been very cautious about changing the formatter's style rules to minimize churn in already-formatted code. Most of these style rules were chosen before Flutter existed and before we knew what idiomatic Flutter code looked like.
We've learned a lot about what idiomatic Dart looks like since then. In particular, large deeply nested function calls of "data-like" code are common. To accommodate them, the formatter lets you partially opt into a different formatting style by explicitly authoring trailing commas in argument and parameter lists. I think we can do better, but doing so would be the largest change we've ever made to the formatter.
I'm starting this change process to determine whether or not it's a change the community is in favor of. Details are below, but in short, I propose:
The formatter treats trailing commas in argument lists and parameter lists as "whitespace". The formatter adds or removes them as it sees fit just as it does with other whitespace.
When an argument or parameter list is split, it always uses a "tall" style where the elements are indented two spaces, and the closing
)
is moved to the next line:longFunction( longArgument, anotherLongArgument, );
The formatting rules for other language constructs are adjusted to mesh well with argument and parameter lists formatted in that style. For example, with that style, I think it looks better to prefer splitting in an argument list instead of after
=
in an assignment or variable declaration:The overall goal is to produce output that is as beautiful and readable as possible for the kind of code most Dart users are writing today, and to give you that without any additional effort on your part.
Background
The formatter currently treats a trailing comma in an argument or parameter list as an explicit hand-authored signal to select one of two formatting styles:
A trailing comma also forces the surrounding construct to split even when it would otherwise fit within a single line:
force( arg, );
The pros of this approach are:
Before Dart allowed trailing commas in argument and parameter lists, they were formatted in the short style. Having to opt in to the tall style by writing an explicit trailing comma, avoids churn in already-formatted code.
Users who prefer either the short or tall style can each have it their way.
If a user wants to force an argument or parameter list to split that would otherwise fit (and they want a tall style), they can control this explicitly.
The cons are:
The short style is inconsistent with how list and map literals are formatted, so nested code containing a mixture of function calls and collections—very common in Flutter code—looks inconsistent.
If a user wants the tall style but doesn't want to force every argument or parameter list to split, they have no way of getting that. There's no way to say "split or unsplit this as needed, but if you do split, use a tall style".
Instead, users who want a tall style must remember to manually remove any trailing comma on an argument or parameter list if they want to allow it fit on one line. This is particularly painful with large scale automated refactorings where it's infeasible to massage the potentially thousands of modified lists to remove their trailing commas.
Worse, there's no way to tell if a trailing comma was authored to mean "I want to force this to split" versus "I want this to have tall style", so anyone maintaining the code afterwards doesn't know whether a now-unnecessary trailing comma should remain or not.
Users must be diligent in maintaining trailing commas in order to get the same style across an entire codebase.
The goal of automated formatting is to get users out of the business of making style choices. But the current implementation requires them to hand-author formatting choices on every argument and parameter list.
For users who prefer a tall style, they must be careful to add a trailing comma and then reformat whenever an existing argument or parameter list that used to fit on one line no longer does and gets split. By default, as soon as the list overflows, it will get the short style.
Again, this is most painful with large scale refactorings. A rename that makes an identifier longer could lead to thousands of argument lists splitting. If those are in code that otherwise prefers a tall style, the result is a mixture of short and tall styles.
The rest of the style rules aren't designed to harmonize with tall style argument and parameter lists since they don't know whether nearby code will use a short or tall style. There's no way to opt in to a holistic set of style rules designed to make all Dart code look great in that style.
This leads to a long tail of bug reports where some other construct clearly doesn't look good when composed with tall-style argument and parameter lists, but there's not much we can do because the construct does look fine when composed with short style code.
I believe the cons outweigh the pros, which leads to this proposal.
Proposal
There are basically three interelated pieces to the proposal:
Trailing commas as whitespace
Trailing commas in argument and parameter lists are treated as "whitespace" characters and under the formatter's purview to add and remove. (Arguably, they really are whitespace characters, since they have zero effect on program semantics.)
The rule for adding and removing them is simple:
If a comma-separated construct is split across multiple lines, then add a trailing comma after the last element. This applies to argument lists, parameter lists, list literals, map literals, set literals, records, record types, enum values, switch expression cases, and assert arguments.
(There are a couple of comma-separated constructs that don't allow trailing commas that are excluded from this like type parameter and type argument lists.)
Conversely, if the formatter decides to collapse a comma-separated construct onto a single line, then do so and remove the trailing comma.
The last part means that users can no longer hand-author a trailing comma to mean, "I know it fits on one line but force it to split anyway because I want it to." I think it's worth losing that capability in order to preserve reversibility. If the formatter treated trailing commas as user-authored intent, but also inserted them itself, then once a piece of code has been formatted once, it can no longer tell which commas came from a human and which came from itself.
Always use tall style argument and parameter lists
If a trailing comma no longer lets a user choose between a short or tall style, then the formatter has to choose. I think it should always choose a tall style.
Both inside Google and externally, the clear trend is users adding trailing commas to opt into the tall style. An analysis of the 2,000 most recently published Pub packages shows:
The two lines that are relevant here are:
Of the argument lists where either a short or tall style preference can be distinguished, users prefer the tall style ~71% of the time, even though they have to remember to hand-author a trailing comma on every argument list to get it.
Block-like argument lists
I've been talking about "short" and "tall" argument lists, but there are actually three ways that argument lists get formatted:
The third style is used when some of the arguments are function expressions or collection literals and formatting the argument list almost as if it were a built-in statement in the language looks better. The most common example is in tests:
This proposal still supports block-style argument lists. It does somewhat tweak the heuristics the formatter uses to decide when an argument list should be block-like or not. The current heuristics are very complex, subtle, and still don't always look right.
Format the rest of the language holistically to match
The set of formatting rules for the different language features were not designed to make each feature look nice in isolation. Instead, the goal was a coherent set of style rules that hang together and make an entire source file clear and readable.
Those rules currently assume that argument and parameter lists have short formatting. With this proposal, we also adjust many of those other rules and heuristics now that we know that when an argument or parameter list splits, it will split in a tall style way.
There are many of these mostly small-scale tweaks. Some examples:
Prefer to split in the initializer instead of after "=":
Less indentation for collection literal
=>
member bodies:Don't split after
=>
if a parameter list splits:I used the Flutter repository as a reference, which uses tall style and has been very carefully hand-formatted for maximum readability, and tweaked the rules to follow that wherever I could. Many of the changes are subtle in ways that are hard to describe here. The best way to see them in action is to try out the prototype implementation, described below.
Risks
While I believe the proposed style looks better for most Dart code and makes users' lives simpler by not having to worry about maintaining trailing commas, this is a large change with some downsides:
Churn
Formatting a previously formatted codebase with this new style will cause about 10% of the lines of code to change. That's a large diff and can be disruptive to codebases where there are many in-progress changes.
Migrating to the new style may be painful for users, though of course it is totally automated.
Users may dislike the style
Obviously, if a large enough fraction of users don't want this change, we won't do it, which is what the change process aims to discover. But even if 90% of the users prefer the new style, that still leaves 10% who now feel the tool is worse than it was before.
Realistically, no change of this scale will please everyone. One of the main challenges in maintaining an opinionated formatter that only supports one consistent style is that some users are always unhappy with it. At least by rarely changing the style, we avoid drawing user attention to the style when they don't like it. This large, disruptive change will make all users at least briefly very aware of automated formatting.
Two configurable styles
An obvious solution to user dislike is to make the style configurable: We could let you specify whether you want the old formatting rules or the new ones. The formatter could support two separate holistic styles, without going all the way towards full configurability (which is an anti-goal for the tool).
There are engineering challenges with this. The internal representation the formatter uses to determine where to split lines has grown piecemeal over the formatter's history. The result is hard to extend and limited in the kind of style rules it can represent. When new language features are added it's often difficult to express the style rules we want in terms that the internal representation supports. Many long-standing bugs can't be fixed because the rule a user wants can't be modeled in the current representation.
This became clear when working on a prototype of the proposal. Getting it working was difficult and there are edge cases where I can't get it to model the rules I want.
If this proposal is accepted and we make large-scale changes to the formatting rules, we intend to take the opportunity to also implement a better internal representation. That's a large piece of work for a tool that generally doesn't have a lot of engineering resources allocated to it.
We don't have the bandwidth during this change to write a new IR, a new set of style rules and migrate the old style rules to the new IR. There may be old rules the new IR can't represent well.
We could keep the old IR around for the old style and use the new IR only for the new style. But going forward, we don't have the resources to maintain two sets of style rules and two separate internal representations, one for each. Every time a new language feature ships, the formatter needs support for it. Bugs would have to get fixed twice (or, more likely, only fixed for one style).
We might be able to temporarily support both styles in order to offer a migration period. But we don't have the resources to support both styles in perpetuity. We would rather spend those resources supporting one style really well instead of two styles poorly.
Evaluation
This is a large style change. Because the formatter is deliberately opinionated and non-configurable, it will affect all users of
dart format
. That means it's important to make sure that it's a good change in the eyes of as many users as possible. We can't please everyone, but we should certainly please a clear majority.To that end, we need your feedback. That feedback is most useful when it's grounded in concrete experience.
Prototype implementation
To help with that, we have a prototype implementation of the new style rules. The prototype has known performance regressions and doesn't get the style exactly right in some cases. But, for the most part, it should show you the proposed behavior.
Diff corpus
We ran this prototype on a randomly selected corpus of code, which yields the resulting diff. This shows you how the new formatting compares to the behavior of the current formatter. Keep in mind that a diff focuses your attention on places where the style is different. It doesn't highlight the majority of lines of code that are formatted exactly the same under this proposal as they are today.
Running it yourself
To get a better sense of what it feels like to use this proposed behavior, you can install the prototype branch of the formatter from Git:
You can run this using the same command-line options as
dart format
. For example, to reformat the current directly and its subdirectories, you would run:$ dart pub global run dart_style:format .
To format just a single file,
example.dart
, you would run:Give us your feedback
Once you've tried it out, let us know what you think by taking this survey. You can also reply directly on this issue, but the survey will help us aggregate the responses more easily. We'll take the survey responses and any comments here into account and try our best to do what's right for the community.
After a week or, to give people time to reply, I'll update with what we've learned.
This is an uncomfortably large change to propose (and a hard one to implement!), so I appreciate your patience and understanding while we work through the process.
Thank you!
– Bob
The text was updated successfully, but these errors were encountered: