SE-0250: Swift Code Style Guidelines and Formatter

(Šimon Javora) #83

I’ve seen this argument repeated here many times, but I’ve never actually witnessed this. I’m told this formatter / style guide will save us from debating formatting and yet the only such debate I can see is in the threads discussing this very proposal. Can anyone point me to some of these supposed endless debates?

6 Likes
#84
  • What is your evaluation of the proposal?

+1. I don't agree with everything (I'd prefer zero configuration), but it would be nice to have a tool that ships with Swift and ideally works with Xcode and LSP editors.

  • Is the problem being addressed significant enough to warrant a change to Swift?

Sure, many waste a lot of time not only coming up with style guides, but adhering to them and enforcing them. If Swift can provide an easy-to-use solution to saving this time, I'm all for it.

  • Does this proposal fit well with the feel and direction of Swift?

Yes. Swift would be joining the footsteps of many other modern languages.

  • If you have used other languages with a similar feature, how do you feel that this proposal compares to those?

I've used formatters like Prettier, elm-format, gofmt, and even clang-format, as well linters that happen to enforce certain formatting, like JS/ES/TSLint, Rubocop, SwiftLint, etc. This proposal prefers some more flexibility in configuration than the former group, and less flexibility than the latter. Configuration is just one more thing to waste time with, but with a default hopefully we won't have to worry our time if we don't want to.

  • How much effort did you put into your review? A glance, a quick reading, or an in-depth study?

Medium read.

2 Likes
#85

I've worked on a number of teams that internally spent a lot of time coming up with a style guide, maintaining it, and enforcing it, and that doesn't count the time people spend up front avoiding those less helpful code review comments. Those hours added up! I'm in the camp of: I don't care, just automate the problem away from me, and this is what these tools can do.

Even away from those kinds of teams, formatting tools still save you time: I don't even have to maintain that little subprocess in my brain that manages indentation during refactors and cutting and pasting code around my project. Using gofmt, Prettier, and elm-format can feel :sparkles: magical :sparkles: because you can just write a bunch of code without thinking about formatting (or even doing any formatting), and when you hit save, everything is fixed in an instant.

18 Likes
#86

I'm not familiar with RuboCop but it doesn't seem that relevant here. It is a self-described “Ruby static code analyzer and code formatter” not the simple formatter that's described here. Clicking on your link for inline directives shows me a ton of directives that seem to be disabling linting or static analysis rules like Metrics/ClassLength, Metrics/MethodLength, RSpec/FactoriesInMigrationSpecs, QA/ElementWithPattern, etc. I also don't think anyone has suggested allowing people to disable formatting on a line-by-line and rule-by-rule basis. Just being able to set some project-specific rules that are automatically applied appears to be the main request.

Several people have given a negative opinion on the proposal saying some variant of “I don't want to get involved in a debate about the style guide”, but I don't find this a convincing point. Everyone is obviously free to ignore the discussion and the resulting formatting tool, so it just comes down to your personal tolerance for discussion and having the self-control to ignore it if desired.

(Paul Cantrell) #87

You’re rather missing the point of the RuboCop comparison.

Both in the pitch and in the discussion, advocates of the proposal present two selling points that are in direct conflict:

  1. No more mental overhead due to style! No more inconsistency! No more per-project variation! No more argument! Code from different projects from across the land of Swift will be styled consistently!
  2. It preserves odd whitespace and dangling parentheses! Really, it hardly formats your code at all! It’s not enforced! You’re free to ignore it altogether!

You can’t have that cake and eat it too. Either it’s strict and widely adopted, or you still have widespread style variation (and the putative cognitive burden thereof, which I’m skeptical of).

So, why do I mention RuboCop? It’s a tool with a lot of style rules, and it’s pretty strict by default. Its out-of-the-box behavior is closer to #1 above. That in my experience has been awkward with a language that (1) takes on many different idioms for many different kinds of programming and (2) grew popular before style was standardized.

Trying to apply the sort of strictness that engenders consistency to a language like that, programmers in practice have to make lots of little exceptions. That’s the point of the GitHub search.

I don’t want to get into style arguments, on this forum or off of it — but I also don’t want to have to live with the style decisions made by the few who do relish that sort of argument.

And do I have to live with those decisions? Yes, clearly, I’ll continue to follow my own personal style in personal code. But on projects I don’t own, well … it’s the 1 vs. 2 contradiction above: if people mostly ignore the formatting tool, then it doesn’t achieve consistency; if it does achieve consistency, then we’re all living with the result of that discussion. Ignoring the coming Style Wars thus isn’t just a matter of “self-control.”

8 Likes
#88

You're very much exaggerating both of the selling points you've taken from the proposal, and using that exaggeration to claim that they must be in irreconcilable conflict. On 1., nowhere has it been implied that the formatter will be a sort of pretty printer for an AST, in the sense that it will take code with arbitrary whitespace variation and unify the presentation. On 2., nowhere has it been claimed that it preserves all existing “odd whitespace” or similar. Like all style guides that I'm aware of, it will specify some things and leave some things to personal style and judgement. e.g. it might specify the spacing of the colon in Dictionaries and protocol conformances, but allow you to either write all the elements in an array literal on a single line or split it into one element per line.

Sure, the Swift style guide and formatter doesn't need to be either of those things, though. It would still be a very useful tool to address intra-project formatting differences (really the more important aspect to me), while also reducing some inter-project variation through default settings and the natural limitations of configurability.

And my point was that the Github search is very misleading, because the results seem to consist mostly of opting out of rules that are not in the domain of this proposal. Again, I'm not that familiar with the tool, but it seems like this search might be more relevant here, showing that disabling the layout rules is much less common (very roughly 0.4% of the RuboCop rule disabling on Github).

I don't understand. You've never controlled the style of projects that you don't own, and consistency isn't a binary thing here.

(Daryle Walker) #89

A -0 for me. From this thread, I've read of several languages (Go, Rust, Dart, Elm, Python) that have official formatters (and style guides), but I'm not sure that the official Swift distribution should join in or if we leave this to third-party opportunities.

(👑🦆) #90

Yeah, formatting tools are awesome, no doubt about it.

But just like clang-format doesn't declare a certain style to be "official" C, I see no reason why we should make a certain style "official" Swift. That's the point that I think needs more explanation and justification. Why should we even start labelling code like that?

Currently, we have "valid code" vs. "invalid code" (stuff which doesn't match the documented grammar rules).

If this proposal is accepted, we will also have "valid code" which is also "not official" (stuff which follows the documented grammar rules, but not the formatter's preferred way of writing it).

Please, anybody, justify why it is worth making such a distinction. To be blunt, it seems like a thing for people who don't have the guts to change the language's grammar rules proper. Either make it mandatory (i.e. change the language's grammar rules), or stop trying to pretend your way of writing things is better by attaching meaningless labels like "official" to it.

:microphone::arrow_down:

11 Likes
(Tony Arnold) #91

This entire conversation is nuts. The Swift police aren't going to come knock on your door if you don't format your code according to the guidelines :roll_eyes:

I'm a solid +1 for both a set of guidelines, and for including an official formatting tool with Swift.

Great work to everyone involved to date :heart_eyes:

11 Likes
(Tino) #92

I guess many support the proposal because they consider themselves to be style-agnostic, or they believe an official style wouldn't have any impact on them - but I think neither is true.

Have a look at this style:

internal class Test
  {

    internal let ci_someConstant: Int = 42;

//----------------------------------------------------

    internal var cm_counter: Int = 0;

//----------------------------------------------------

    private var m_limit: Int = 100;

//----------------------------------------------------

    internal func doStuff(input input: Int) -> Void
      {
        return ();
      };

  };

I don't expect this to become official style, but that's not the point:
Everybody should be able to spot something in this snippet that appears more or less stupid to him - and still, I've encountered variations of those "crazy" rules in real-world code, and there are people who consider this to be good style.

So I'm sure no matter how smart the "official" style will be, many people will disagree with it.
Just for the sake of the argument, imagine that surprisingly you will be one of those who disagree:
What effect would this have on you?
Are you sure you can ignore it? Maybe if you work alone in a dark chamber, because whenever you enter a new team or codebase, you'll have to fight against those braindead rules, or silently accept defeat.
Even if your full team shares your critique, would you be comfortable working with a language that promotes rules which contradict your believes?

So, there definitely will be people who are unhappy with any sort of official style, no matter how it's called or enforced. It might be a very small minority (and most likely, you'll be with the majority, won't you?)… but what will we get in return for making some percentage of potential and existing users of Swift unhappy?
With a strict policy (like go has), you could be pretty sure that there won't be any debates about style anymore, and nearly all code would be more or less uniform, which definitely is a big advantage.

But: This won't be the case here - instead of avoiding fights, we'll just give one party a big hammer to bludgeon those who don't share the "official" opinion.
There won't be uniformity, but there will always be debates about style.

4 Likes
(Goffredo Marocchi) #93

I see plumbing efforts to improve the plumbing behind linters and formatters (enabling to make their job, without Xcode necessarily, better) as good pragmatic use of time and resources and helping tools such as the much faster, configurable, and quite mature SwiftFormat.

Not meaning to offend or be rude, but I see trying to get this mountaintop proposal searching to select the one true style and one of the many formatters as the one true one before even talking about its requirements (and the ensuing “select a single style after 5 years of the language being used in the wild by tons of people” endless debates) as a waste of engineering time and patience for both Core Team and the community here.

All towards what I feel is a non serious problem (work in a team long enough, look at the rules enabled and disabled for the formatter in use and beyond the first day you can live happily) or an edge case (moving from codebase to codebase faster than you can adapt to the style in use). Yes, in some cases people can stop a formatter options discussion if they can just shout “Officially Swifty Swift formatting style rules” of and only if the formatter chosen allows NO configuration and the style tries to regulate pretty much about everything as that makes this whole “a blessed style and formatter would all formatting discussions / wastes of time learning new styles” void and inaccurate.

4 Likes
(Thomas Krajacic) #94

I think it is super sad that time is wasted (my personal opinion) on talking about this while SPM still can't handle resources for example. There are much more important problems to solve in Swift at the moment than talking about code style.

I don't want to reject the proposal because I believe that having style guidelines is a good thing (and the authors have put a lot of effort in it), it's just very very far down the list of things that Swift needs imho.

Please can we have a "defer for later discussion" option when voting on proposals?

Otherwise I do like the idea that someone from the core team just decides what good style is, and that's it. Making this a democratic decision is bound to fail in my opinion.

8 Likes
(David Hart) #95

FWIW, time spent on this discussion is not taking resources away from working on SPM support for resources.

9 Likes
(Goffredo Marocchi) #96

Mental space is not free, people working on things are not infinite, and pretending that starting the mother of all discussions (coding style and officia formatting) on a language that has been expanding like crazy for five years in production (one of the gotchas of putting in production systems newborn languages I guess...) is pragmatic and best use of resources is odd for me...

3 Likes
(Tino) #98

But I don‘t think Apple will delete your developer account if you use a third party tool either :-)

1 Like
(Pierpaolo Frasa) #99

-0.5, after some consideration.

I don't really see how this proposal improves the situation significantly. I do agree that extensive style debates in dev teams are a nuisance, but there are already tools that can address this and come with their own sets of defaults. If someone is leading a software team, they should be able to say "let's use swift-format (or some other tool) and/or a linter like SwiftLint". Such tools come with default behaviour, so people who are happy using that behaviour don't need to configure anything. Meanwhile, I don't think it's a problem if style is not consistent across different repositories (and people have made good arguments as to why code differences might be due to the different nature of software projects).

The one thing that I currently do find lacking is XCode's inability to use such outside tooling (in a very good way; you can use SwiftLint with it, but I don't find the experience very compelling); and while I personally don't care that much about XCode, it's still kind of the default IDE for Swift. But such a thing can't be fixed by this proposal.

Meanwhile I have to agree with @Paul_Cantrell's reservations about the choice of the tool. I don't think that blessing a particular tool by committee is a good approach when it comes to programming language communities; if something like that happens, then it should happen only after that tool has proved its worth over years and years (e.g. like Ruby officially adopting Bundler). Otherwise, the benefit of open source tool development is that those tools that people end up liking a lot will be used extensively, and so there's a process of natural selection happening. Nobody officially selected Rubocop or JSHint or any other such tool, they just became community "standards" because they were seen as useful. Also, the failure of SPM to deliver upon its promise is a valid point.

4 Likes
(Paul Cantrell) #100

See here:

…and this reply:

Matt’s “dangling parens” example is IMO appropriate for its context, but certainly not how you’d want most code to look. A formatter that allows it is not a formatter that is going to achieve a high degree of stylistic consistency.


From the proposal:

  1. Developers can move from one codebase to another without incurring the mental load of learning and conforming to a different style or being required to reconfigure their development environment.
  2. Developers spend less time worrying about how to format their code and more on the program's logic.
  3. Likewise, code reviewers spend less time commenting on code formatting issues and more on its logic and design.

These points all imply the proposal will remove most style decisions. Upvoters in this thread echo these points: no more style decisions, they just happen, you don’t have to think about it, easing cognitive load, projects look the same, no “formatting shock” in an unfamiliar codebase, etc.

Achieving those goals is inconsistent with the tool Tony describes above. If it allows parens like that, there will still be formatting shock.

Either we have a strict formatter and consistent style, or a loose formatter and inconsistent style. That’s strictly a zero-sum game.

In that tradeoff, I tend to err on the side of nuance — but whichever end of the continuum you prefer, we should be clear about where on that continuum this proposal sits. It seems it’s getting support from people who imagine it to exist at both ends.

I’ve said plenty in this discussion at this point, so I’m bowing out now.

10 Likes
(Joe Spadafora) #101

What is your evaluation of the proposal?

+1 to having a default style guide
+1 to having a (very limited or no configuration) formatter that can apply the default style

In spite of the fact that I read the proposal multiple times along the way and the both the proposal thread and this thread, I felt confused when the proposal included picking swift-format as the tool.

Currently I have also been writing Kotlin in android studio, and the build in formatter changes the : spacing foo : as opposed to foo:. As long as the rules are consistent and applied automatically I don't care exactly which format rules are included.

Is the problem being addressed significant enough to warrant a change to Swift?

Yes. Having a standard tool solves the problems of working with contractors or new team members by removing stylistic variation. Fewer stylistic differences / changes means that we can focus on the business logic, not what it should look like.

Does this proposal fit well with the feel and direction of Swift?

Yes

If you have used other languages with a similar feature, how do you feel that this proposal compares to those?

I have previously used swiftlint as a prior art reference.

How much effort did you put into your review? A glance, a quick reading, or an in-depth study?

Read the proposal several times, read ~95% of the comments in both threads.

2 Likes
#102

You've quoted me saying “nowhere has it been claimed that it preserves all existing “odd whitespace”” then shown one example where it does currently preserve whitespace, specified explicitly as how the tool “handles that today” and not necessarily in future, and somehow find those contradictory? They aren't at all.

They don't imply this to me. Firstly, there is a whole section in the proposal about configurability. Secondly, even where the styles are configured slightly differently in different projects (i.e. there is inter-project variation), point 2. still generally applies because developers don't need to learn or conform to the style (it is applied automatically by the tool using settings files in the project directory), 3. still applies because of the same reason, and 4. still applies for the same reason. Again, the major benefit from my perspective is the reduction in intra-project formatting variation; that there will be a reduction in inter-project variation (due to default settings and the limitations of configurability) is just a bonus.

#103

I think most arguments are dead in the water without agreeing on common definitions. In this case I don't think the "official" being used in the proposal matches your definition, and I don't think a single person would argue that having an "official" style guide would make code that doesn't follow it "not official". There's plenty of code out there that doesn't follow the API design guidelines (it's quite difficult to do, and building a swift-design-guidelines tool seems like a much taller order), and no one calls this code "not designed".

I think "official" here only means providing a tool that ships with the toolchain, and it needs to be coded to format in specific ways, though maybe those behind the proposal can flesh out some of these definitions so that we can all be on the same page. If this proposal called it "default style" instead I think a lot of these arguments would disappear.

5 Likes