This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Proposed Style Guide

70 replies
daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
One of the things about Scala which has always bugged me is the lack of an official style guide.  There is simply no "right" way of doing things, syntactically speaking.  Over the years, the Scala community has attempted to fill the void (as it were) by defining a set of unofficial, word-of-mouth conventions.  Things like when to add parentheses to no-arg methods or what the preferred function literal definition style may be.

This works fine for experienced Scala community members, but newcomers to the language are understandably baffled.  This also causes a great deal of frustration on larger Scala projects with less-experienced Scala developers as some code will be stylized in one way, while other code will use a different convention.

A few months ago, I decided that I had run into this problem one too many times, and so I took the time (with the generous support of my employer) to create a full (-ish) style guide for Scala syntax, naming conventions and project management.  The guidelines it contains are based on what I have heard from the community and do not necessarily reflect my own preferences (e.g. function types).  When in doubt about a particular convention, I have alternately looked at Martin Odersky's code or simply relied on my own knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and criticisms are very welcome.

I would like to submit this guide for adoption by the larger Scala community.  I know that sounds like I'm trying to foist my opinions on everyone else, but I'm really just hoping to get the ball rolling.  Ideally, this guide should be used as a starting point from which a proper, officially-blessed and better-typeset guide can be fashioned.  Until that happens, I'm more than happy to host the guide at Code Commit, incorporating any revisions the community as a whole deems necessary.

The source for the guide is in reStructuredText, which is easily convertible to distributable formats like HTML, LaTeX, TWiki markup and more.  For convenience, I have compiled the guide to a PDF (using rst2newlatex and pdflatex) and uploaded it along with the source.  The document does not include a license declaration, but you can pretty much consider the material to be Public Domain.

Enjoy!

Daniel
Kris Nuttycombe
Joined: 2009-01-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide

The package naming conventions section will no longer be quite right
after 2.8, correct? In that one will no longer need to use __root__ so
much in imports - a package declaration will not include each level in
the hierarchy in scope for imports, correct?

Kris

On Wed, Nov 11, 2009 at 4:02 PM, Daniel Spiewak wrote:
> One of the things about Scala which has always bugged me is the lack of an
> official style guide.  There is simply no "right" way of doing things,
> syntactically speaking.  Over the years, the Scala community has attempted
> to fill the void (as it were) by defining a set of unofficial, word-of-mouth
> conventions.  Things like when to add parentheses to no-arg methods or what
> the preferred function literal definition style may be.
>
> This works fine for experienced Scala community members, but newcomers to
> the language are understandably baffled.  This also causes a great deal of
> frustration on larger Scala projects with less-experienced Scala developers
> as some code will be stylized in one way, while other code will use a
> different convention.
>
> A few months ago, I decided that I had run into this problem one too many
> times, and so I took the time (with the generous support of my employer) to
> create a full (-ish) style guide for Scala syntax, naming conventions and
> project management.  The guidelines it contains are based on what I have
> heard from the community and do not necessarily reflect my own preferences
> (e.g. function types).  When in doubt about a particular convention, I have
> alternately looked at Martin Odersky's code or simply relied on my own
> knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and
> criticisms are very welcome.
>
> I would like to submit this guide for adoption by the larger Scala
> community.  I know that sounds like I'm trying to foist my opinions on
> everyone else, but I'm really just hoping to get the ball rolling.  Ideally,
> this guide should be used as a starting point from which a proper,
> officially-blessed and better-typeset guide can be fashioned.  Until that
> happens, I'm more than happy to host the guide at Code Commit, incorporating
> any revisions the community as a whole deems necessary.
>
> The source for the guide is in reStructuredText, which is easily convertible
> to distributable formats like HTML, LaTeX, TWiki markup and more.  For
> convenience, I have compiled the guide to a PDF (using rst2newlatex and
> pdflatex) and uploaded it along with the source.  The document does not
> include a license declaration, but you can pretty much consider the material
> to be Public Domain.
>
> Enjoy!
>
> Daniel
>
> http://www.codecommit.com/scala-style-guide.txt
> http://www.codecommit.com/scala-style-guide.pdf

Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide

"The Scala language encourages a startling amount of nested scopes and
logical blocks (function values and such)."

I think this is false. If it happens to be true, you're not "doing it
properly."

Daniel Spiewak wrote:
> One of the things about Scala which has always bugged me is the /lack/
> of an official style guide. There is simply no "right" way of doing
> things, syntactically speaking. Over the years, the Scala community
> has attempted to fill the void (as it were) by defining a set of
> unofficial, word-of-mouth conventions. Things like when to add
> parentheses to no-arg methods or what the preferred function literal
> definition style may be.
>
> This works fine for experienced Scala community members, but newcomers
> to the language are understandably baffled. This also causes a great
> deal of frustration on larger Scala projects with less-experienced
> Scala developers as some code will be stylized in one way, while other
> code will use a different convention.
>
> A few months ago, I decided that I had run into this problem one too
> many times, and so I took the time (with the generous support of my
> employer) to create a full (-ish) style guide for Scala syntax, naming
> conventions and project management. The guidelines it contains are
> based on what I have heard from the community and do not necessarily
> reflect my own preferences (e.g. function types). When in doubt about
> a particular convention, I have alternately looked at Martin Odersky's
> code or simply relied on my own knowledge of Java, C#, Standard ML and
> Haskell conventions. Comments and criticisms are very welcome.
>
> I would like to submit this guide for adoption by the larger Scala
> community. I know that sounds like I'm trying to foist my opinions on
> everyone else, but I'm really just hoping to get the ball rolling.
> Ideally, this guide should be used as a starting point from which a
> proper, officially-blessed and better-typeset guide can be fashioned.
> Until that happens, I'm more than happy to host the guide at Code
> Commit, incorporating any revisions the community as a whole deems
> necessary.
>
> The source for the guide is in reStructuredText, which is easily
> convertible to distributable formats like HTML, LaTeX, TWiki markup
> and more. For convenience, I have compiled the guide to a PDF (using
> rst2newlatex and pdflatex) and uploaded it along with the source. The
> document does not include a license declaration, but you can pretty
> much consider the material to be Public Domain.
>
> Enjoy!
>
> Daniel
>
> * http://www.codecommit.com/scala-style-guide.txt
> * http://www.codecommit.com/scala-style-guide.pdf
>

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide

"The Scala language encourages a startling amount of nested scopes and
logical blocks (function values and such)."

I think this is false. If it happens to be true, you're not "doing it
properly."

It depends.  Based on my experience, Scala tends to have a lot more nested scopes than either object-oriented languages or functional languages.  I suspect the reason for this is unlike a purely-functional language, Scala functions may consist of numerous statements and expressions; and unlike an object-oriented language, Scala encourages anonymous functions, pattern matching and "blocks as expressions", all of which tend to push up the number of scopes.  That's not really "doing it wrong" where Scala is concerned, it's just using the language in a way which would be wrong in Java or Haskell.

Daniel
Nadav Wiener
Joined: 2009-11-12,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide

Regarding "Packages" on page 4:
<----
Scala packages should follow the Java package naming conventions:
// right!
package com.novell.coolness
// wrong!
package coolness
---->
and the final point on page 22:
<----
All multi-unit files should be given camelCase names with a lower-case first
letter. This is a very important convention. It differentiates multi- from
single-unit files, greatly easing the process of finding declarations. These
filenames may be based upon a significant type which they contain (e.g.
option.scala for the example above) or may be descriptive of the logical
property shared by all units within (e.g. ast.scala).
---->

NOTE: This developed into a bit of a rant, so I summarized a few points at the
bottom.

I like camelCase on multi-unit files a lot, but I'm missing some recommendation
for (or against) them hosting packages.

While the guidelines are for Java's strict unit structure, which would work out
very well in large projects, not all situations warrant such a full-fledged and
meticulous solution.

Java was built for enterprise from day 1, but Scala also strives to find other
niches. One such niche is small (but not ad-hoc) libraries, developed by
individuals. Another (important!) use is sample code. The prevalence of the
"enterprise" mindset in Java makes sample code feel dirty and incomplete, and
sends homebrew developers scurrying after domain names (in other words: "package
net.sf.foobar considered excessive"). It also generally hampers prototyping, and
once habitualized makes ad-hoc programming, well, difficult...

While enterprise projects would be right to shun such practices in their own
codebase, they should be comfortable using such small projects when appropriate.
That's why I think a double standard should be applied here: In order for small
libraries not to *smell*, and a guidelines document's wording has immense
influence on this -- it should be a little more homebrew friendly.

In summary, my 4 cents:
1. Multi-unit files can better obey the principle of least surprise by giving
their very own package and naming them after it. There may be reasons against it
(such as wanting several multi-unit files in the same package) but it would be
helpful to either condone or condemn it in the guidelines.
2. Organizational package names are problematic with scala's current import
semantics. "com." "org." "net." needlessly burden the package namespace, and
should enable only minimal "." breakdown. This:
"com.novell.department.project.component", could be better served by the (I
know - ugly, unconventional) "com-novell-department.project.component". You'd
hardly ever want to "import com._" or even "com.novell._", and the potential for
importing the wrong package due to nested import will be greatly diminished.
Since I seriously doubt using "-" would ever be adopted, at least discarding top
level domains (com, net , org) and minimizing organizational structure (e.g.
".department." is nice to have in Java but often clutter in Scala) should be
considered.

-Nadav.

Nadav Wiener
Joined: 2009-11-12,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide

Nadav Wiener gmail.com> writes:

EDIT: My last point regarding package imports will be irrelevant in Scala 2.8,
(see http://www.jetbrains.net/devnet/message/5245213#5245213).

-Nadav.

Jonas Bonér
Joined: 2008-12-19,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide

Good initiative.

This came up at my Scala workshop yesterday (and many times before).
Now I just have to see if I agree ;-)

/Jonas

2009/11/12 Daniel Spiewak :
> One of the things about Scala which has always bugged me is the lack of an
> official style guide.  There is simply no "right" way of doing things,
> syntactically speaking.  Over the years, the Scala community has attempted
> to fill the void (as it were) by defining a set of unofficial, word-of-mouth
> conventions.  Things like when to add parentheses to no-arg methods or what
> the preferred function literal definition style may be.
>
> This works fine for experienced Scala community members, but newcomers to
> the language are understandably baffled.  This also causes a great deal of
> frustration on larger Scala projects with less-experienced Scala developers
> as some code will be stylized in one way, while other code will use a
> different convention.
>
> A few months ago, I decided that I had run into this problem one too many
> times, and so I took the time (with the generous support of my employer) to
> create a full (-ish) style guide for Scala syntax, naming conventions and
> project management.  The guidelines it contains are based on what I have
> heard from the community and do not necessarily reflect my own preferences
> (e.g. function types).  When in doubt about a particular convention, I have
> alternately looked at Martin Odersky's code or simply relied on my own
> knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and
> criticisms are very welcome.
>
> I would like to submit this guide for adoption by the larger Scala
> community.  I know that sounds like I'm trying to foist my opinions on
> everyone else, but I'm really just hoping to get the ball rolling.  Ideally,
> this guide should be used as a starting point from which a proper,
> officially-blessed and better-typeset guide can be fashioned.  Until that
> happens, I'm more than happy to host the guide at Code Commit, incorporating
> any revisions the community as a whole deems necessary.
>
> The source for the guide is in reStructuredText, which is easily convertible
> to distributable formats like HTML, LaTeX, TWiki markup and more.  For
> convenience, I have compiled the guide to a PDF (using rst2newlatex and
> pdflatex) and uploaded it along with the source.  The document does not
> include a license declaration, but you can pretty much consider the material
> to be Public Domain.
>
> Enjoy!
>
> Daniel
>
> http://www.codecommit.com/scala-style-guide.txt
> http://www.codecommit.com/scala-style-guide.pdf

Landei
Joined: 2008-12-18,
User offline. Last seen 45 weeks 4 days ago.
Re: Proposed Style Guide

Daniel Spiewak wrote:
>
> One of the things about Scala which has always bugged me is the *lack* of
> an
> official style guide. There is simply no "right" way of doing things,
> syntactically speaking. Over the years, the Scala community has attempted
> to fill the void (as it were) by defining a set of unofficial,
> word-of-mouth
> conventions. Things like when to add parentheses to no-arg methods or
> what
> the preferred function literal definition style may be.
>
> This works fine for experienced Scala community members, but newcomers to
> the language are understandably baffled. This also causes a great deal of
> frustration on larger Scala projects with less-experienced Scala
> developers
> as some code will be stylized in one way, while other code will use a
> different convention.
>
> A few months ago, I decided that I had run into this problem one too many
> times, and so I took the time (with the generous support of my employer)
> to
> create a full (-ish) style guide for Scala syntax, naming conventions and
> project management. The guidelines it contains are based on what I have
> heard from the community and do not necessarily reflect my own preferences
> (e.g. function types). When in doubt about a particular convention, I
> have
> alternately looked at Martin Odersky's code or simply relied on my own
> knowledge of Java, C#, Standard ML and Haskell conventions. Comments and
> criticisms are very welcome.
>
> I would like to submit this guide for adoption by the larger Scala
> community. I know that sounds like I'm trying to foist my opinions on
> everyone else, but I'm really just hoping to get the ball rolling.
> Ideally,
> this guide should be used as a starting point from which a proper,
> officially-blessed and better-typeset guide can be fashioned. Until that
> happens, I'm more than happy to host the guide at Code Commit,
> incorporating
> any revisions the community as a whole deems necessary.
>
> The source for the guide is in reStructuredText, which is easily
> convertible
> to distributable formats like HTML, LaTeX, TWiki markup and more. For
> convenience, I have compiled the guide to a PDF (using rst2newlatex and
> pdflatex) and uploaded it along with the source. The document does not
> include a license declaration, but you can pretty much consider the
> material
> to be Public Domain.
>
> Enjoy!
>
> Daniel
>
> - http://www.codecommit.com/scala-style-guide.txt
> - http://www.codecommit.com/scala-style-guide.pdf
>
>

Thanks, good work!

On page 5/6 of the PDF I found a minor glitch:

class Company {
private val _name: String = _
def name = _name
def name_=(name: String) {
_name = name
}
}

_name should be a var here, right?

Regards,
Daniel

odersky
Joined: 2008-07-29,
User offline. Last seen 45 weeks 6 days ago.
Re: Proposed Style Guide

Thanks, Daniel that's really useful! By and large I agree with what's
proposed in the style guide, except for some reservations listed
below. It would be a good idea if we could evolve this to something
which we can put up on scala-lang as an official document (provided
you are happy with that).

Cheers

Joshua.Suereth
Joined: 2008-09-02,
User offline. Last seen 32 weeks 5 days ago.
Re: Proposed Style Guide
On the "Void methods" section, I have the following comments:

I think methods should *always* be followed by an =, specifically to avoid the following pitfall


def foo()
{
   //O HAI, IMMA NESTED SCOPE, NOT A METHOD!
}


Techinically your "Nested Blocks" section does require { to be on the same line, but I know in my shop that was a hard argument to win (it was 4 against 1).  So, instead, we just require = after all methods. 


- Josh


On Wed, Nov 11, 2009 at 6:02 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:
One of the things about Scala which has always bugged me is the lack of an official style guide.  There is simply no "right" way of doing things, syntactically speaking.  Over the years, the Scala community has attempted to fill the void (as it were) by defining a set of unofficial, word-of-mouth conventions.  Things like when to add parentheses to no-arg methods or what the preferred function literal definition style may be.

This works fine for experienced Scala community members, but newcomers to the language are understandably baffled.  This also causes a great deal of frustration on larger Scala projects with less-experienced Scala developers as some code will be stylized in one way, while other code will use a different convention.

A few months ago, I decided that I had run into this problem one too many times, and so I took the time (with the generous support of my employer) to create a full (-ish) style guide for Scala syntax, naming conventions and project management.  The guidelines it contains are based on what I have heard from the community and do not necessarily reflect my own preferences (e.g. function types).  When in doubt about a particular convention, I have alternately looked at Martin Odersky's code or simply relied on my own knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and criticisms are very welcome.

I would like to submit this guide for adoption by the larger Scala community.  I know that sounds like I'm trying to foist my opinions on everyone else, but I'm really just hoping to get the ball rolling.  Ideally, this guide should be used as a starting point from which a proper, officially-blessed and better-typeset guide can be fashioned.  Until that happens, I'm more than happy to host the guide at Code Commit, incorporating any revisions the community as a whole deems necessary.

The source for the guide is in reStructuredText, which is easily convertible to distributable formats like HTML, LaTeX, TWiki markup and more.  For convenience, I have compiled the guide to a PDF (using rst2newlatex and pdflatex) and uploaded it along with the source.  The document does not include a license declaration, but you can pretty much consider the material to be Public Domain.

Enjoy!

Daniel

davetron5000
Joined: 2009-06-07,
User offline. Last seen 2 years 31 weeks ago.
Re: Proposed Style Guide

This is really awesome.

* Content

I feel there are a FEW too many "if" statements.

** Unit/Void methods

I see no gains to

def voidMethod() { /* do something */ }

over

def voidMethod(): Unit = { /* do something */ }

Rules that are "always do X" are a lot easier to understand an apply. If
someone learning Scala NEVER sees the first form, that is a good thing.
Further, Unit methods should be rare,
so I see no need to shortcut their creation

** Type Parameters

Seeing something like this

class Foo[Bar]

in the scaladoc sent me ALL OVER THE PLACE trying to find the class definition
for "Bar". If it had been

class Foo[BAR]

I would've instantly realized it was a type parameter

I think type parameters should be all caps.

** Paren-less vs 0-arg functions/method

I found this confusing. I think the paren-less form should be reserved for DSLs
only and one should always use parens. It just makes things a LOT clearer;
when you see parens, you are seeing a function/method call.

** When to use dot-invocation and when not

I *think* I agree with the convention here, but found it pretty hard to follow.
Maybe a few more examples showing the "all-dot-invocation" form as comparison?

* Format

I realize it was probably most expedient to author this in one big file and
generate to PDF, but if this becomes accepted and generally "pointed-to" to
anyone interested in Scala, it should be:

* in multiple files
* on github
* published to Github pages (at least)

This would allow anyone to comment on specific things, to create issues, and
submit corrections/patches.

Anyway, overall, I think it's awesome and will be a huge benefit! Thanks for
putting it together!

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Proposed Style Guide

Commenting on a style guide would normally not be my thing, but since
martin did I'm afraid it'll end up gaining an aura of officialness,
so... My #1 suggestion is to separate it into sections which are
uncontroversial (at least mostly) and sections where there is a
diversity of opinion. That gives us at least a chance at a core of
consistency. Without that separation it'll only be ignored.

No endorsement implied regarding bits I didn't comment on (but for the
most part I agreed with the rest, modulo the fact that I skimmed.)

"Line Wrapping"

val result = 1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 +
15 + 16 + 17 + 18 + 19 + 20

This is needlessly error prone. Do this:

val result = (
1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 +
15 + 16 + 17 + 18 + 19 + 20
)

Now you can end your lines however you want. You can't have multiple
statements in there, so if you forget a + it won't compile.

"Packages"

It's _root_, not __root__.

"Parentheses"

I think this situation is hopeless and attempts to define when to use
empty parens vs. no parens can only have two results: 1) lots of
pointless arguing among people who have better things to do and 2) being
ignored by or unknown to 98% of scala programmers.

"Void" Methods

"You should prefer the former style (without the annotation or the
equals sign) as it reduces errors and improves readability."

Too many people think that the former style is a mistake for it to be a
good recommendation. Also, I much prefer : Unit on one line methods
because it means I can avoid the braces entirely and save 1-2 lines of
the vertical.

"Declarations"

"All class/object/trait members should be declared interleaved with
newlines."

No. There is no reason to make an exception for var and val but not
def, they're the same thing. It's a matter of sensible grouping, like
when to start a new paragraph in prose.

"Function Values"

"Of these styles, (1) and (4) are to be preferred at all times."

...except for all the times when one might prefer (2) or (3), which for
me is plenty often. Especially, I avoid curly braces almost whenever
possible, with the notable exception of situationally using them in
if/then/else situations if it looks easy to misread the logic.

"Omit braces if the ``case`` expression fits on a single line.
Otherwise, use curly braces for clarity (even though they are not
*required* by the parser)."

Oh god no, not having to use braces on case statements is one of their
greatest features.

"Comprehensions"

// wrong!
for (x <- board.rows; y <- board.files)
yield (x, y)

I'm going with "right", although the yield goes on the first line.

"Arity-1"

// wrong!
javaList add item

We got this one wrong in about 5000 spots in the compiler. I'm going
with "right" again.

David Pollak
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Proposed Style Guide


On Wed, Nov 11, 2009 at 11:36 PM, Nadav Wiener <2Bscala [at] gmail [dot] com" target="_blank" rel="nofollow">nadav.wiener+scala@gmail.com> wrote:
Regarding "Packages" on page 4:
<----
 Scala packages should follow the Java package naming conventions:
   // right!
   package com.novell.coolness
   // wrong!
   package coolness
---->
and the final point on page 22:
<----
 All multi-unit files should be given camelCase names with a lower-case first
letter. This is a very important convention. It differentiates multi- from
single-unit files, greatly easing the process of finding declarations. These
filenames may be based upon a significant type which they contain (e.g.
option.scala for the example above) or may be descriptive of the logical
property shared by all units within (e.g. ast.scala).
---->

NOTE: This developed into a bit of a rant, so I summarized a few points at the
bottom.

I like camelCase on multi-unit files a lot, but I'm missing some recommendation
for (or against) them hosting packages.

While the guidelines are for Java's strict unit structure, which would work out
very well in large projects, not all situations warrant such a full-fledged and
meticulous solution.

Java was built for enterprise from day 1

I'm sorry for responding to this... I know I shouldn't but...

Java was originally Oak, a language/runtime for setop boxes.  It was designed for the embedded space.  Then along came browsers and Java morphed into a secure runtime for highly interactive browser-based applications (what Flash is today).  The first "Java-fund" company, Marimba, was founded by some key Sun folks who built tools for authoring and distributing Java-based multi-media content.

It took some real lunatics (and I mean that as very high praise), Bob Pasker (WebLogic), Paul Ambrose (WebLogic) and Steve Yen (Kiva) come to mind, to see the true power of Java in the enterprise.

Yes, I ran the largest Java-powered web site on the net in 1996 on private builds of Java 1.0.  One of the Java engineers would drive from Cupertino to San Francisco with a weekly private build of Java to address the myriad of issues we were seeing running Java in production on the server side.  We were the first large-scale user of WebLogic and had the largest installation of Symantic's Java Cafe IDE in any one company at the time.

It wasn't until the launch of JDK 1.2 that Sun marketted Java as an enterprise/server focused language.

No, Java was not enterprise from day 1.
 
, but Scala also strives to find other
niches. One such niche is small (but not ad-hoc) libraries, developed by
individuals. Another (important!) use is sample code. The prevalence of the
"enterprise" mindset in Java makes sample code feel dirty and incomplete, and
sends homebrew developers scurrying after domain names (in other words: "package
net.sf.foobar considered excessive"). It also generally hampers prototyping, and
once habitualized makes ad-hoc programming, well, difficult...

While enterprise projects would be right to shun such practices in their own
codebase, they should be comfortable using such small projects when appropriate.
That's why I think a double standard should be applied here: In order for small
libraries not to *smell*, and a guidelines document's wording has immense
influence on this -- it should be a little more homebrew friendly.

In summary, my 4 cents:
1. Multi-unit files can better obey the principle of least surprise by giving
their very own package and naming them after it. There may be reasons against it
(such as wanting several multi-unit files in the same package) but it would be
helpful to either condone or condemn it in the guidelines.
2. Organizational package names are problematic with scala's current import
semantics. "com." "org." "net." needlessly burden the package namespace, and
should enable only minimal "." breakdown. This:
"com.novell.department.project.component", could be better served by the (I
know - ugly, unconventional) "com-novell-department.project.component". You'd
hardly ever want to "import com._" or even "com.novell._", and the potential for
importing the wrong package due to nested import will be greatly diminished.
Since I seriously doubt using "-" would ever be adopted, at least discarding top
level domains (com, net , org) and minimizing organizational structure (e.g.
".department." is nice to have in Java but often clutter in Scala) should be
considered.


-Nadav.




--
Lift, the simply functional web framework http://liftweb.net
Beginning Scala http://www.apress.com/book/view/1430219890
Follow me: http://twitter.com/dpp
Surf the harmonics
Nadav Wiener
Joined: 2009-11-12,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide

David Pollak gmail.com> writes:
>> Java was built for enterprise from day 1
>
> I'm sorry for responding to this... I know I shouldn't but...Java was
> originally Oak, a language/runtime for setop boxes.  It was designed
> for the embedded space.  Then along came browsers and Java morphed into
> a secure runtime for highly interactive browser-based applications
> (what Flash is today).  The first "Java-fund" company, Marimba, was
> founded by some key Sun folks who built tools for authoring and
> distributing Java-based multi-media content.It took some real lunatics
> (and I mean that as very high praise), Bob Pasker (WebLogic), Paul
> Ambrose (WebLogic) and Steve Yen (Kiva) come to mind, to see the true
> power of Java in the enterprise.Yes, I ran the largest Java-powered web
> site on the net in 1996 on private builds of Java 1.0.  One of the Java
> engineers would drive from Cupertino to San Francisco with a weekly private
> build of Java to address the myriad of issues we were seeing running Java in
> production on the server side.  We were the first large-scale user of
> WebLogic and had the largest installation of Symantic's Java Cafe IDE in any
> one company at the time.It wasn't until the launch of JDK 1.2 that Sun
> marketted Java as an enterprise/server focused language.No, Java was not
> enterprise from day 1. 
>

ichoran
Joined: 2009-08-14,
User offline. Last seen 2 years 3 weeks ago.
Re: Proposed Style Guide
I like the guide for the most part!

I have a few comments, of course.

(1) Methods with numerous arguments

There are cases where even the method name and first argument don't fit well:
  val myRatherLongValName = myOtherRatherLongVal.withARatherLongMethodName(yetAnotherRatherLongVal.withAnAccessorThatHasALongName)

In cases like these, I personally indent using ( ) as if they were { }:
  val myRatherLongValName =
    myOtherRatherLongValName(
      yetAnotherRatherLongVal.withAnAccessorThatHasALongName ,
      anotherThingWithAnAbsurdlyLongName.perhapsFromAJavaLibrary
    )

This also comes up all the time when using closures as arguments to things--you need a lot of space.

(2) The operator section seems a bit strongly worded.  Why open with "Avoid!" when in fact there are two commonly-used cases where operators are exactly what you need to make your language clearer?  (It is, however, good to point out that random operators strung together are no more comprehensible than random letters strung together and should not be used just because one can.)

(3) If a generic parameter actually means something, having it be descriptive is nice.  All caps is also nice to disambiguate it from a class:
  class FancyMath[NUM <: MyGenericNumber] {
    def addAndMultiply(a:NUM , b:NUM , c:NUM) = new NUM(a+b*c)
  }
This can be a lot clearer than starting with A (or T).

(4) Annotating types on every method name--is this *really* necessary or even advisable?  Ugh!  What if you decide to change an underlying representation and just let it percolate through the type system?

(5) The description of currying functions is actually not correct:
  def a(i:Int)(j:Int) = i+j
  def b(i:Int) = { (j:Int) => i+j }
do *not* generate the same code.  The former generates
  public static final int a(int,int)
while the latter generates
  public static final scala.Function1 b(int)

However, if you then pass a(5) into something that expects an Int=>Int, Scala will automatically generate something that looks the same as b(5).

So the first one is correct, but for two reasons:
  (a) It's clearer
  (b) It's more efficient, since it is a just-plain function that Scala can interpret in functional ways for you

(6) The definition of the val in the braces section is almost incomprehensible to my eye:
  val x = if (b)
    c
  else
    d
hardly looks like a assignment to x by the time you hit d.  This really ought not be the recommended style.  One line is fine:
  val x = if (b) c else d
or indented is fine:
  val x = if (b)
            c
          else
            d
or set off using parentheses is fine:
  val x = (
    if (b)
      c
    else
      d
  )
or some combination thereof:
  val x = (if (b) c
    else d
  )

(7) The word "tolerated" has a typo (two l's) on page 20

(8) Insisting on spaces around operators seems unwise:
// Wrong?
val a = 5*3 + 9*2

// Right?
val a = 5 * 3 + 9 * 2
It's most notable in cases where you use multiple operators (as above) where spaces help reinforce precedence.  Incidentally, spacing should always match precedence:
// Wrong!
val a = 5 * 3+9 * 2
I'd say instead that one should use spaces around operators *whenever doing so increases clarity*.  And then give some examples:

// Good
val a = i + j*k
actor ! message
println("Hello, "+yourName)
println("Hello, " + yourName)

// Bad
val a = i+j * k
actor!message

(9) Distinguishing multi-unit files from single-unit files with camel case seems like it's not helpful enough to be worth bothering with.  If you want to know where something is, use grep or a similar tool.  Simply knowing that you need one of fifteen files that begin with a lower case letter instead of one of the forty that start with upper case isn't that much help.  You're still much better off using a tool like grep.  Place the word "class" on the same line as the name of your class and you'll be fine.

On Wed, Nov 11, 2009 at 6:02 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:
A few months ago, I decided that I had run into this problem one too many times, and so I took the time (with the generous support of my employer) to create a full (-ish) style guide for Scala syntax, naming conventions and project management.  The guidelines it contains are based on what I have heard from the community and do not necessarily reflect my own preferences (e.g. function types).  When in doubt about a particular convention, I have alternately looked at Martin Odersky's code or simply relied on my own knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and criticisms are very welcome.

David Pollak
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Proposed Style Guide


On Thu, Nov 12, 2009 at 8:35 AM, Nadav Wiener <2Bscala [at] gmail [dot] com" rel="nofollow">nadav.wiener+scala@gmail.com> wrote:
David Pollak <feeder.of.the.bears <at> gmail.com> writes:
>> Java was built for enterprise from day 1
>
> I'm sorry for responding to this... I know I shouldn't but...Java was
> originally Oak, a language/runtime for setop boxes.  It was designed
> for the embedded space.  Then along came browsers and Java morphed into
> a secure runtime for highly interactive browser-based applications
> (what Flash is today).  The first "Java-fund" company, Marimba, was
> founded by some key Sun folks who built tools for authoring and
> distributing Java-based multi-media content.It took some real lunatics
> (and I mean that as very high praise), Bob Pasker (WebLogic), Paul
> Ambrose (WebLogic) and Steve Yen (Kiva) come to mind, to see the true
> power of Java in the enterprise.Yes, I ran the largest Java-powered web
> site on the net in 1996 on private builds of Java 1.0.  One of the Java
> engineers would drive from Cupertino to San Francisco with a weekly private
> build of Java to address the myriad of issues we were seeing running Java in
> production on the server side.  We were the first large-scale user of
> WebLogic and had the largest installation of Symantic's Java Cafe IDE in any
> one company at the time.It wasn't until the launch of JDK 1.2 that Sun
> marketted Java as an enterprise/server focused language.No, Java was not
> enterprise from day 1. 
>
> -- Lift, the simply functional web framework http://liftweb.netBeginning
> Scala http://www.apress.com/book/view/1430219890
>
> Follow me: http://twitter.com/dppSurf the harmonics
>


David,
I didn't mean "enterprise" as in "J2EE": despite Java's applet days in the
90's, it was my impression that some of the decisions that went into the
*language* were intended to enable easier collaboration of large teams of
developers (compared with, say,  C++).
In particular, omitting operator overloading and the rationalizations for it,
but several other decisions can also be seen in that context.

Yes, Java was "dumbed down" from C++.  This was not an "Enterprise" decision.  Enterprise developers were, at the time, considered to be skilled enough to use the power of C++.  In fact, C++ prevailed over a number of less "powerful" (read syntactically simple) languages (e.g., Pascal, Objective-C, Smalltalk, VB) in the same era that Java was released.  Java was never conceived as an Enterprise language.  The runtime (JVM) was not designed for or tested against server-side scenarios in the early days.
It was the passion and technical excellence of some Java ecosystem ISVs (I've named some above) combined with the need for dynamic web apps in the enterprise (and elsewhere) that dragged Sun and Java into the space (well, that combined with Microsoft's decision to kill Java in the browser and the weak Netscape Java implementation).
At the end of the day, Java's built in garbage collection (lacking in most competing languages at the time), reasonable object model (including no base class fragility problems), price (free download vs. > $1K per seat for Smalltalk) and exception model made it the most practical language for doing a wide range of applications.  It was not planned or intended... although in many ways, write on your Windows desktop, deploy on your Sparc server saved Sun during the 90s.

-Nadav.





--
Lift, the simply functional web framework http://liftweb.net
Beginning Scala http://www.apress.com/book/view/1430219890
Follow me: http://twitter.com/dpp
Surf the harmonics
boisvert
Joined: 2009-11-11,
User offline. Last seen 38 weeks 5 days ago.
Re: Re: Proposed Style Guide
BTW, Java's original design principles are well documented in the "Feel of Java" paper by James Gosling.
http://www.dfjug.org/DFJUG/thefeelofjava.pdf

As David was pointing out, Java was initially designed with the considerations for "consumer electronics" above those of "commercial software" (see table 1 in the article)

alex

On Thu, Nov 12, 2009 at 8:51 AM, David Pollak <feeder.of.the.bears@gmail.com> wrote:


On Thu, Nov 12, 2009 at 8:35 AM, Nadav Wiener <2Bscala [at] gmail [dot] com" target="_blank" rel="nofollow">nadav.wiener+scala@gmail.com> wrote:
David Pollak <feeder.of.the.bears <at> gmail.com> writes:
>> Java was built for enterprise from day 1
>
> I'm sorry for responding to this... I know I shouldn't but...Java was
> originally Oak, a language/runtime for setop boxes.  It was designed
> for the embedded space.  Then along came browsers and Java morphed into
> a secure runtime for highly interactive browser-based applications
> (what Flash is today).  The first "Java-fund" company, Marimba, was
> founded by some key Sun folks who built tools for authoring and
> distributing Java-based multi-media content.It took some real lunatics
> (and I mean that as very high praise), Bob Pasker (WebLogic), Paul
> Ambrose (WebLogic) and Steve Yen (Kiva) come to mind, to see the true
> power of Java in the enterprise.Yes, I ran the largest Java-powered web
> site on the net in 1996 on private builds of Java 1.0.  One of the Java
> engineers would drive from Cupertino to San Francisco with a weekly private
> build of Java to address the myriad of issues we were seeing running Java in
> production on the server side.  We were the first large-scale user of
> WebLogic and had the largest installation of Symantic's Java Cafe IDE in any
> one company at the time.It wasn't until the launch of JDK 1.2 that Sun
> marketted Java as an enterprise/server focused language.No, Java was not
> enterprise from day 1. 
>
> -- Lift, the simply functional web framework http://liftweb.netBeginning
> Scala http://www.apress.com/book/view/1430219890
>
> Follow me: http://twitter.com/dppSurf the harmonics
>


David,
I didn't mean "enterprise" as in "J2EE": despite Java's applet days in the
90's, it was my impression that some of the decisions that went into the
*language* were intended to enable easier collaboration of large teams of
developers (compared with, say,  C++).
In particular, omitting operator overloading and the rationalizations for it,
but several other decisions can also be seen in that context.

Yes, Java was "dumbed down" from C++.  This was not an "Enterprise" decision.  Enterprise developers were, at the time, considered to be skilled enough to use the power of C++.  In fact, C++ prevailed over a number of less "powerful" (read syntactically simple) languages (e.g., Pascal, Objective-C, Smalltalk, VB) in the same era that Java was released.  Java was never conceived as an Enterprise language.  The runtime (JVM) was not designed for or tested against server-side scenarios in the early days.
It was the passion and technical excellence of some Java ecosystem ISVs (I've named some above) combined with the need for dynamic web apps in the enterprise (and elsewhere) that dragged Sun and Java into the space (well, that combined with Microsoft's decision to kill Java in the browser and the weak Netscape Java implementation).
At the end of the day, Java's built in garbage collection (lacking in most competing languages at the time), reasonable object model (including no base class fragility problems), price (free download vs. > $1K per seat for Smalltalk) and exception model made it the most practical language for doing a wide range of applications.  It was not planned or intended... although in many ways, write on your Windows desktop, deploy on your Sparc server saved Sun during the 90s.

-Nadav.





--
Lift, the simply functional web framework http://liftweb.net
Beginning Scala http://www.apress.com/book/view/1430219890
Follow me: http://twitter.com/dpp
Surf the harmonics

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Re: Proposed Style Guide
The danger with having packages at the file level is it tends toward unmanageably as the project size increases (especially as the package attains more members).  As for package conventions, I would argue that these should be considered inviolable and maintained regardless of project size.  Remember the early days of Java, when package naming conventions were flying all over the place, and no-one knew how to read anyone else's name?  That's what I'm trying to avoid.  A lot of (maybe even most) Scala developers are coming from Java, and given that one of Scala's main design goals is seamless Java interop, I think we should be as strict with our package names as they are with theirs.

Daniel

On Thu, Nov 12, 2009 at 1:36 AM, Nadav Wiener <2Bscala [at] gmail [dot] com" rel="nofollow">nadav.wiener+scala@gmail.com> wrote:
Regarding "Packages" on page 4:
<----
 Scala packages should follow the Java package naming conventions:
   // right!
   package com.novell.coolness
   // wrong!
   package coolness
---->
and the final point on page 22:
<----
 All multi-unit files should be given camelCase names with a lower-case first
letter. This is a very important convention. It differentiates multi- from
single-unit files, greatly easing the process of finding declarations. These
filenames may be based upon a significant type which they contain (e.g.
option.scala for the example above) or may be descriptive of the logical
property shared by all units within (e.g. ast.scala).
---->

NOTE: This developed into a bit of a rant, so I summarized a few points at the
bottom.

I like camelCase on multi-unit files a lot, but I'm missing some recommendation
for (or against) them hosting packages.

While the guidelines are for Java's strict unit structure, which would work out
very well in large projects, not all situations warrant such a full-fledged and
meticulous solution.

Java was built for enterprise from day 1, but Scala also strives to find other
niches. One such niche is small (but not ad-hoc) libraries, developed by
individuals. Another (important!) use is sample code. The prevalence of the
"enterprise" mindset in Java makes sample code feel dirty and incomplete, and
sends homebrew developers scurrying after domain names (in other words: "package
net.sf.foobar considered excessive"). It also generally hampers prototyping, and
once habitualized makes ad-hoc programming, well, difficult...

While enterprise projects would be right to shun such practices in their own
codebase, they should be comfortable using such small projects when appropriate.
That's why I think a double standard should be applied here: In order for small
libraries not to *smell*, and a guidelines document's wording has immense
influence on this -- it should be a little more homebrew friendly.

In summary, my 4 cents:
1. Multi-unit files can better obey the principle of least surprise by giving
their very own package and naming them after it. There may be reasons against it
(such as wanting several multi-unit files in the same package) but it would be
helpful to either condone or condemn it in the guidelines.
2. Organizational package names are problematic with scala's current import
semantics. "com." "org." "net." needlessly burden the package namespace, and
should enable only minimal "." breakdown. This:
"com.novell.department.project.component", could be better served by the (I
know - ugly, unconventional) "com-novell-department.project.component". You'd
hardly ever want to "import com._" or even "com.novell._", and the potential for
importing the wrong package due to nested import will be greatly diminished.
Since I seriously doubt using "-" would ever be adopted, at least discarding top
level domains (com, net , org) and minimizing organizational structure (e.g.
".department." is nice to have in Java but often clutter in Scala) should be
considered.


-Nadav.


daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide
Yep, that's a typo.  I'll fix that asap.

Daniel

On Thu, Nov 12, 2009 at 4:57 AM, Landei <Daniel.Gronau@gmx.de> wrote:



Daniel Spiewak wrote:
>
> One of the things about Scala which has always bugged me is the *lack* of
> an
> official style guide.  There is simply no "right" way of doing things,
> syntactically speaking.  Over the years, the Scala community has attempted
> to fill the void (as it were) by defining a set of unofficial,
> word-of-mouth
> conventions.  Things like when to add parentheses to no-arg methods or
> what
> the preferred function literal definition style may be.
>
> This works fine for experienced Scala community members, but newcomers to
> the language are understandably baffled.  This also causes a great deal of
> frustration on larger Scala projects with less-experienced Scala
> developers
> as some code will be stylized in one way, while other code will use a
> different convention.
>
> A few months ago, I decided that I had run into this problem one too many
> times, and so I took the time (with the generous support of my employer)
> to
> create a full (-ish) style guide for Scala syntax, naming conventions and
> project management.  The guidelines it contains are based on what I have
> heard from the community and do not necessarily reflect my own preferences
> (e.g. function types).  When in doubt about a particular convention, I
> have
> alternately looked at Martin Odersky's code or simply relied on my own
> knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and
> criticisms are very welcome.
>
> I would like to submit this guide for adoption by the larger Scala
> community.  I know that sounds like I'm trying to foist my opinions on
> everyone else, but I'm really just hoping to get the ball rolling.
> Ideally,
> this guide should be used as a starting point from which a proper,
> officially-blessed and better-typeset guide can be fashioned.  Until that
> happens, I'm more than happy to host the guide at Code Commit,
> incorporating
> any revisions the community as a whole deems necessary.
>
> The source for the guide is in reStructuredText, which is easily
> convertible
> to distributable formats like HTML, LaTeX, TWiki markup and more.  For
> convenience, I have compiled the guide to a PDF (using rst2newlatex and
> pdflatex) and uploaded it along with the source.  The document does not
> include a license declaration, but you can pretty much consider the
> material
> to be Public Domain.
>
> Enjoy!
>
> Daniel
>
>    - http://www.codecommit.com/scala-style-guide.txt
>    - http://www.codecommit.com/scala-style-guide.pdf
>
>

Thanks, good work!

On page 5/6 of the PDF I found a minor glitch:

class Company {
private val _name: String = _
def name = _name
def name_=(name: String) {
_name = name
}
}

_name should be a var here, right?

Regards,
Daniel
--
View this message in context: http://old.nabble.com/-scala--Proposed-Style-Guide-tp26310456p26315308.html
Sent from the Scala mailing list archive at Nabble.com.


David Copeland
Joined: 2009-06-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide
So, to demonstrate what I was saying vis a vis github and not having this passed around as a PDF:

http://github.com/davetron5000/scala-style

any push (to the gh-pages branch) regenerates the entire thing, which you can view here:

http://davetron5000.github.com/scala-style/

I think each individual section could be broken up into its own file.  Issues could be created, and changes can be commented upon, like :

http://github.com/davetron5000/scala-style/commit/404e269734eb535ad4b528552cc4acc851dcc3d4

Granted, this can't as easily be turned into a PDF, but, then again, no one should be printing this sort of thing out, IMO.

Dave

---
My Blog: http://www.naildrivin5.com/blog
Scala Tour for Java Developers: http://www.naildrivin5.com/scalatour
Fork me on Github: http://davetron5000.github.com



On Thu, Nov 12, 2009 at 1:17 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:
Yep, that's a typo.  I'll fix that asap.

Daniel

On Thu, Nov 12, 2009 at 4:57 AM, Landei <Daniel.Gronau@gmx.de> wrote:



Daniel Spiewak wrote:
>
> One of the things about Scala which has always bugged me is the *lack* of
> an
> official style guide.  There is simply no "right" way of doing things,
> syntactically speaking.  Over the years, the Scala community has attempted
> to fill the void (as it were) by defining a set of unofficial,
> word-of-mouth
> conventions.  Things like when to add parentheses to no-arg methods or
> what
> the preferred function literal definition style may be.
>
> This works fine for experienced Scala community members, but newcomers to
> the language are understandably baffled.  This also causes a great deal of
> frustration on larger Scala projects with less-experienced Scala
> developers
> as some code will be stylized in one way, while other code will use a
> different convention.
>
> A few months ago, I decided that I had run into this problem one too many
> times, and so I took the time (with the generous support of my employer)
> to
> create a full (-ish) style guide for Scala syntax, naming conventions and
> project management.  The guidelines it contains are based on what I have
> heard from the community and do not necessarily reflect my own preferences
> (e.g. function types).  When in doubt about a particular convention, I
> have
> alternately looked at Martin Odersky's code or simply relied on my own
> knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and
> criticisms are very welcome.
>
> I would like to submit this guide for adoption by the larger Scala
> community.  I know that sounds like I'm trying to foist my opinions on
> everyone else, but I'm really just hoping to get the ball rolling.
> Ideally,
> this guide should be used as a starting point from which a proper,
> officially-blessed and better-typeset guide can be fashioned.  Until that
> happens, I'm more than happy to host the guide at Code Commit,
> incorporating
> any revisions the community as a whole deems necessary.
>
> The source for the guide is in reStructuredText, which is easily
> convertible
> to distributable formats like HTML, LaTeX, TWiki markup and more.  For
> convenience, I have compiled the guide to a PDF (using rst2newlatex and
> pdflatex) and uploaded it along with the source.  The document does not
> include a license declaration, but you can pretty much consider the
> material
> to be Public Domain.
>
> Enjoy!
>
> Daniel
>
>    - http://www.codecommit.com/scala-style-guide.txt
>    - http://www.codecommit.com/scala-style-guide.pdf
>
>

Thanks, good work!

On page 5/6 of the PDF I found a minor glitch:

class Company {
private val _name: String = _
def name = _name
def name_=(name: String) {
_name = name
}
}

_name should be a var here, right?

Regards,
Daniel
--
View this message in context: http://old.nabble.com/-scala--Proposed-Style-Guide-tp26310456p26315308.html
Sent from the Scala mailing list archive at Nabble.com.



Blair Zajac
Joined: 2009-01-12,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide

Daniel Spiewak wrote:
> One of the things about Scala which has always bugged me is the /lack/
> of an official style guide. There is simply no "right" way of doing
> things, syntactically speaking. Over the years, the Scala community has
> attempted to fill the void (as it were) by defining a set of unofficial,
> word-of-mouth conventions. Things like when to add parentheses to
> no-arg methods or what the preferred function literal definition style
> may be.
>
> This works fine for experienced Scala community members, but newcomers
> to the language are understandably baffled. This also causes a great
> deal of frustration on larger Scala projects with less-experienced Scala
> developers as some code will be stylized in one way, while other code
> will use a different convention.
>
> A few months ago, I decided that I had run into this problem one too
> many times, and so I took the time (with the generous support of my
> employer) to create a full (-ish) style guide for Scala syntax, naming
> conventions and project management. The guidelines it contains are
> based on what I have heard from the community and do not necessarily
> reflect my own preferences (e.g. function types). When in doubt about a
> particular convention, I have alternately looked at Martin Odersky's
> code or simply relied on my own knowledge of Java, C#, Standard ML and
> Haskell conventions. Comments and criticisms are very welcome.

Daniel,

Thanks for writing this up. It's really good.

I'll comment on several things and then below is the style guide we use at Sony
Imageworks for a 4-person Scala team.

Regarding "Type Parameters (generics)" I think we should keep to the Java style.
Using [K,V] for a map is clearer than using [A,B].

In "Inference", "Just for the sake of safety, you should annotate all public
methods in your class." This should be stronger since code is read more than it
is written. Anything longer than a single line or two must be annotated with
the return type in our code. In my mind, almost the methods in the document
should be annotated with a return type to make it clear that it is a requirement.

"Void" Methods. We don't permit them in our code, we require the ":Unit = {"
style. It's too easy to try to write a short method with no type annotation and
forget the = and now the method returns Unit. There was a debate whether to
remote this from the language, so it's use throughout the community isn't 100%.

In "Comprehensions" for the non-yield case I think you should mention when there
are many <- or = or if's, then you still want to put things onto separate lines

for {
x <- board.rows
y <- board.files
z <- foo.bar
if z > 10
} {
printf("(%d, %d)", x, y)
}

"Higher-Order Functions" we use

names.map(_.toUpperCase).filter(_.length > 5)

This is a copy/paste from a twiki page which I've tried to clean up a bit. We
use a unified Java/Scala style guide. Most of this is based off the Java and
GWT style guides:

In "Multi-Unit Files" I'm pretty sure this will cause ant to recompile the
source file every time because there is no exact match on the generates class
file and the source file. My compiles are already too long as it is, so I don't
want to compile files I don't need to.

Feel free to incorporate what we use for our style guide. Here it is.

Regards,
Blair

http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
http://code.google.com/webtoolkit/makinggwtbetter.html#codestyle

Identifier Names
================
http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html#585858

Java Naming Conventions
=======================

Underscores Vs. CamelCase
• Classes, traits, interfaces, method names, public field names, etc., always
follow the Java style.
• Parameter names, variable names and protected or private field names may use
all lowercase letters, separating words with underscores. Usage within one file
should be consistent and not mix naming styles. This is at the discretion of
the author.
• Names MUST never have underscores and mixed case.

Class Structure and Member Sort Order
=====================================

Java types should have the following member order:
• Nested Types (mixing inner and static classes is okay)
• Static Fields. These may be placed above a instance method if the field is
used only in that method.
• Static Initializers
• Static Methods
• Instance Fields
• Instance Initializers
• Constructors
• Instance Methods
Members that fall into the same category (e.g. static methods) should also be
sorted in this order based on visibility:
• public
• protected
• default
• private
All methods should be sorted alphabetically. Sorting is optional but recommended
for fields.

Indentation
===========
2-space indents for Java with line wrapping at 4-space indent.
2-space indents for Scala.
No tabs, ever.

Imports
=======
The ordering of imports is:
• Imports from the same project.
• Imports from other Imageworks packages.
• Imports from third parties (com, junit, net, org)
• Imports from java and javax
• Imports from scala
The imports should be:
• Alphabetical within each grouping. Capital letters are considered to come
before lower case letter (e.g. Z before a).
• There should be a blank line between each major grouping (com, junit, net,
org, java, javax).

Line Length and Wrapping
========================
Each line of text in your code should be at most 80 characters long. Use
linefeed characters to break lines (Unix-style). There are some exceptions:
• Java identifiers referenced from within JSNI methods can get quite long and
cannot be parsed if split across lines.
• Exception: If a comment line contains an example command or a literal URL
longer than 80 characters, that line may be longer than 80 characters for ease
of cut and paste.
• Exception: Import lines can go over the limit because humans rarely see them.
This also simplifies tool writing.

Wrapping Function Parameters
============================

Parameters are wrapped so the next line starts aligned with the first parameter
of the former line:
function_decl_or_call(param1, param2, param3, param4 |
param5, param6, param7, param8) |

Long parameter names that do not fit within 80 characters are wrapped so the
next line begins at the right-most tab stop that keeps the line within 80
characters. Subsequent lines are aligned in the same column:
long_function_name_with_long_parameter_names( |
long_parameter_name1,|
param2, param3) |
^
\ multiple of 2 or 4, depending on language.

Or, if the first parameter is not too long, but a subsequent parameter is, the
indent level is based on the long parameter. The first parameter begins on the
next line.
long_function_name_with_long_parameter_names( |
param1, |
long_parameter_name2,|
param3, param4) |
^
\ param1 is aligned with the rest of the
parameters

When a parameter is exceedingly long, the parameters may be formatted with a
block indentation style:
long_function_name_with_long_parameter_names( |
"This is a very long parameter and would look " |
+ "bad mushed up against the right margin.", |
param2, param3 |
) |
^
\ Closing parenthesis goes on its own line when using block indentation.

Wrapping Expressions

When wrapping binary expressions, the operator appears on the second line, and
the first term is indented to align with the second term:
if ( some_truth_expression |
&& some_other_expression) {|
// code |
} |

Brace Style
===========

Opening braces appear on the same line. Closing braces align with the first
column of the opening brace line. Else, catch, finally and while are placed on a
new line:
try {
. do {
. . if (expr1) {
. . }
. . else if (expr2) {
. . }
. . else {
. . }
. }
. while (expr3)
}
catch {
}
finally {
}

Scala Specific Rules
====================

Imports
Grouped imports are formatted which each subpackage on its own line, with one
level of indent:
import com.organization.package.{
subpackage1,
subpackage2
}

Colon Placement
===============

The colon hugs the left value, emulating English usage and conserving horizontal
space:
val my_value: Int = 1
def my_function(param: Int): String = param.toString

• Exception: A space is required when the left value ends in an underscore.
val my_value_ : Int = 1

Function Result Types
=====================

All functions result types are explicitly declared:
def function_name(param: Int): ResultType = {
}

• Exception: very short or trivial functions may omit the result type.

Functions returning Unit may not use the alternate form:
def function_returns_unit(param: Int) {
// ^ bad!
}

Empty Parameter Lists
=====================

An empty parameter list indicates that a function has side effects.
• Functions that take no parameters but return a value should have no parameter
list.
• Functions that take no parameters and return Unit should have an empty
parameter list.
• Callers should also follow this convention.
def get_value: Int = 1
def do_something(): Unit = ...

if (get_value) {
do_something()
}

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide
If you're going with braces on the following line, then I guess it probably is best to use = on all methods.  However, as mentioned elsewhere in the guide, this really isn't the best practice.  The parser handles it, but only by introducing some really flaky disambiguation rules.  Braces-on-the-following-line is bad for the same reason that suffix notation is bad.

Daniel

On Thu, Nov 12, 2009 at 8:05 AM, Josh Suereth <joshua.suereth@gmail.com> wrote:
On the "Void methods" section, I have the following comments:

I think methods should *always* be followed by an =, specifically to avoid the following pitfall


def foo()
{
   //O HAI, IMMA NESTED SCOPE, NOT A METHOD!
}


Techinically your "Nested Blocks" section does require { to be on the same line, but I know in my shop that was a hard argument to win (it was 4 against 1).  So, instead, we just require = after all methods. 


- Josh


On Wed, Nov 11, 2009 at 6:02 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:
One of the things about Scala which has always bugged me is the lack of an official style guide.  There is simply no "right" way of doing things, syntactically speaking.  Over the years, the Scala community has attempted to fill the void (as it were) by defining a set of unofficial, word-of-mouth conventions.  Things like when to add parentheses to no-arg methods or what the preferred function literal definition style may be.

This works fine for experienced Scala community members, but newcomers to the language are understandably baffled.  This also causes a great deal of frustration on larger Scala projects with less-experienced Scala developers as some code will be stylized in one way, while other code will use a different convention.

A few months ago, I decided that I had run into this problem one too many times, and so I took the time (with the generous support of my employer) to create a full (-ish) style guide for Scala syntax, naming conventions and project management.  The guidelines it contains are based on what I have heard from the community and do not necessarily reflect my own preferences (e.g. function types).  When in doubt about a particular convention, I have alternately looked at Martin Odersky's code or simply relied on my own knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and criticisms are very welcome.

I would like to submit this guide for adoption by the larger Scala community.  I know that sounds like I'm trying to foist my opinions on everyone else, but I'm really just hoping to get the ball rolling.  Ideally, this guide should be used as a starting point from which a proper, officially-blessed and better-typeset guide can be fashioned.  Until that happens, I'm more than happy to host the guide at Code Commit, incorporating any revisions the community as a whole deems necessary.

The source for the guide is in reStructuredText, which is easily convertible to distributable formats like HTML, LaTeX, TWiki markup and more.  For convenience, I have compiled the guide to a PDF (using rst2newlatex and pdflatex) and uploaded it along with the source.  The document does not include a license declaration, but you can pretty much consider the material to be Public Domain.

Enjoy!

Daniel


daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide

Thanks, Daniel that's really useful! By and large I agree with what's
proposed in the style guide, except for some reservations listed
below. It would be a good idea if we could evolve this to something
which we can put up on scala-lang as an official document (provided
you are happy with that).

I would be very much in favor.  In fact, that's the whole reason I posted the guide here.  :-)  I would like for there to be some officially-endorsed Scala style guide, even if it doesn't agree with my personal preferences.

1. Object naming conventions: I still hesitate between lower and upper
case. The problem is that another way to see an object is as a lazy
val with an (unnamed?) class. In that case lower case would apply.

Are you talking about the pattern where object is used as if it were a field?  (Lift does this a lot)  If so, then yes I do agree.  I should probably make mention of that in the guide; in that case, the object name should be lower-case as it is masquerading as a val.
 
2. As others have noted the discussion of nested packages does not
reflect what's in 2.8.

I'll need some help to update this one.  Would someone be willing to submit a patch?

3. Normal type parameters can occasionally also have full names, if
there's not good name
   you cann think of, A, B, C work fine.

I disagree on the full-names bit.  As others have pointed out, Doing something like class Foo[Bar] { def baz(b: Bar) } often results in a painful and fruitless search through the scaladoc for type "Bar".  I think it's just much clearer when type parameters have an obviously-distinct naming convention.

If we must use full names, we should adopt the all upper-case convention mentioned elsewhere (e.g. BAR).
 
4. Not 100% sure about Void-methods. Sometimes the : Unit = form is shorter.

When it really is a huge savings, I guess I can see advantages to the : Unit = form.  However, I have found that by preferring the non-= form, it becomes much more apparent to the eye as to which methods are Unit and which are not.  In terms of mental compilation, the non-= form only requires parsing the syntax (a very quick, visual operation), whereas the : Unit = form requires a full semantic analysis of the method body.

Even more importantly, the un-annotated : Unit = form is prone to mistakes due to the fact that type-inference will happily assign whatever type the last expression in the method may produce.  This has bitten me on many occasions, which is why I switched my personal convention from : Unit = to the non-= form.
 
5. I would not recommend spaceless syntax for type ascription. Type
ascription has relatively low priority. For instance,

 1 < 2:Boolean

parses visually as 1 < (2:Boolean), but means actually (1 < 2):
Boolean. So I would prefer either the asymmetric x: T notation, or the
symmetric notation with spaces, i.e. x : T.

I'll agree with you on this one.  It also eliminates a special-case in the conventions (longer ascription).  The main reason to use the no-space syntax is for something like foo:_*, which looks a little odd as `foo: _*`.  I think the gained uniformity is worth it though.
 
6. I think the discussion wrt curly braces at the top of page 12 is
not accurate. AFAIK the parser only mispredicts in the other sense.
That is, if you open a block with a curly brace immediately following
some construct, the parser will usually interpret this as part of the
previous line. So I would instead propose the following convention:

If you mean to write a nested block in a statement sequence, prefix it
with `locally' (defined in 2.8 Predef): I.e.

 print("hello")
 locally {
    var = 1
    ...
 }

The parser does do a pretty decent job of picking up curly braces, but it still has its wrinkles (as pointed out by Josh S in another thread).  This is yet another example of an area in which Scala's parser would be well served by a generalized algorithm allowing local ambiguity in the grammar.  Might I suggest GLL?  :-)
 
7. Declarations: I would not be 100% strict about inserting empty
lines around defs. For instance, if you declare a simple forwarding
class, you want to squeeze multiple defs together, without intervening
blank lines. Otherwise I agree with your recommendation.

Maybe in the absolutely-trivial case the spaces could be dropped, but it's a very slippery slope.  I've seen some nigh-unreadable code due to a lack of proper spacing.
 
8. Modifiers: I usually put protected in front of override, but I have
no problem reading code that does not.

The C# convention is to put override after the access modifier, while the Java syntax forces @Override to come prior to modifiers.  Since Java has "higher precedence" in my list of inspirational languages at the top of the doc, I went with the prefix form.  I'm open to either route though.
 
9. I am against putting braces around case expressions. I find

 foo match {
    case P =>
       val x = expr1
       f(x)
    case Q =>
       expr2
 }

much more readable than:

 foo match {
    case P => {
       val x = expr1
       f(x)
    }
    case Q =>
       expr2
 }

I disagree here.  It's nice to save the unnecessary braces, but it causes a lot of problems in the long run:
  • Non-semantic editor auto-indentation chokes.  I don't think that even the Emacs mode can handle this case, and I know for a fact that jEdit can't.
  • Non-uniformity with non-single-expr cases
My opinion is that uniformity is more important than saving a few curly-braces.  For most people, val a = ...; blah looks like two statements, regardless of the fact that it parses as a single expression.
 
10. Comprehensions: I hesitate to demand for { ... } syntax for all
comprehensions with multiple generators. As an example, consider a
simple matrix map:

 for (i <- 1 to N; j <- 1 to M) yield m(i)(j) + 1

Changing this to

 for {
    i <- 1 to N
    j <- 1 to M
 } yield m(i)(j) + 1

does not increase readability IMO. So, maybe accept the single line
syntax for multiple generators if they follow a simple, repetitive
pattern.

Actually, I find the latter form more readable than the former.  I will yield to the community (no pun intended) on this one if there are strong feelings.
 
12. On Arity 1: I am not sure I agree with your criterion of
side-effect freeness for operator notation (but I don't have a better
one to offer).

All I know is it's a little weird to look at something like `foo add bar`.  Infix methods are really meant to handle operators, which (as mentioned elsewhere in the guide) should be mathematical and thus, purely-functional.
 
13. Operators: The only situation where I do not put spaces around an
operator is for String-concat. I prefer either of

 "prefix "+elem+" suffix"
 "prefix "+ elem +" suffix"

to

 "prefix " + elem + " suffix"

Putting spaces around string concat makes everybody clamor for string
interpolation notation in Scala, because it is so bad.

I strongly disagree here.  Most string concatenation doesn't involve literals all over the place, so what do you do in that case?  Do you always drop the space for the String#+ method?  This again violates the principle of uniformity and has a tendency to confuse beginners about the nature of symbolic method names (and especially mixed symbolic method names).

I have read other forum posts which give your rationale for this style, and while I can see your points, I still disagree.  :-)  Here also, we should assign some weight to established conventions in the "inspirational" languages, especially Java.  In Java, it is a strong convention to put spaces around operators, even in string concatenation.  In fact, I think that's a convention in every language I listed with the possible exception of Haskell (which ironically, doesn't need the no-space convention since it uses ++).
 
14. Function literals with `_'. I quite like your recommendation to use

 { x + _ }

even though personally I have mostly used (x + _) so far.

:-)  Thanks!  The curly brace thing really helps to distinguish function literals from other values in code, making the control flow a bit more intuitive.

Daniel
daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide
I don't have any objection to using GitHub to manage the guide; it's sort of up to everyone else.  I do know that I don't have anywhere near enough time to be the sole maintainer, so it's probably good to get this into a DVCS as soon as possible.  :-)

A couple thoughts:
  • Why did you convert it to .markdown?  GitHub supports reStructuredText (just use the .rst extension).  In fact, it has better support for ReST than it does for Markdown.
  • I'm not sure that I like the split into separate chapters.  This makes it a bit easier to follow in a web setting, but much harder to distribute as a single, atomic unit.  Also, I like PDF.  :-)
Daniel

On Thu, Nov 12, 2009 at 12:30 PM, David Copeland <davec@naildrivin5.com> wrote:
So, to demonstrate what I was saying vis a vis github and not having this passed around as a PDF:

http://github.com/davetron5000/scala-style

any push (to the gh-pages branch) regenerates the entire thing, which you can view here:

http://davetron5000.github.com/scala-style/

I think each individual section could be broken up into its own file.  Issues could be created, and changes can be commented upon, like :

http://github.com/davetron5000/scala-style/commit/404e269734eb535ad4b528552cc4acc851dcc3d4

Granted, this can't as easily be turned into a PDF, but, then again, no one should be printing this sort of thing out, IMO.

Dave

---
My Blog: http://www.naildrivin5.com/blog
Scala Tour for Java Developers: http://www.naildrivin5.com/scalatour
Fork me on Github: http://davetron5000.github.com



On Thu, Nov 12, 2009 at 1:17 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:
Yep, that's a typo.  I'll fix that asap.

Daniel

On Thu, Nov 12, 2009 at 4:57 AM, Landei <Daniel.Gronau@gmx.de> wrote:



Daniel Spiewak wrote:
>
> One of the things about Scala which has always bugged me is the *lack* of
> an
> official style guide.  There is simply no "right" way of doing things,
> syntactically speaking.  Over the years, the Scala community has attempted
> to fill the void (as it were) by defining a set of unofficial,
> word-of-mouth
> conventions.  Things like when to add parentheses to no-arg methods or
> what
> the preferred function literal definition style may be.
>
> This works fine for experienced Scala community members, but newcomers to
> the language are understandably baffled.  This also causes a great deal of
> frustration on larger Scala projects with less-experienced Scala
> developers
> as some code will be stylized in one way, while other code will use a
> different convention.
>
> A few months ago, I decided that I had run into this problem one too many
> times, and so I took the time (with the generous support of my employer)
> to
> create a full (-ish) style guide for Scala syntax, naming conventions and
> project management.  The guidelines it contains are based on what I have
> heard from the community and do not necessarily reflect my own preferences
> (e.g. function types).  When in doubt about a particular convention, I
> have
> alternately looked at Martin Odersky's code or simply relied on my own
> knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and
> criticisms are very welcome.
>
> I would like to submit this guide for adoption by the larger Scala
> community.  I know that sounds like I'm trying to foist my opinions on
> everyone else, but I'm really just hoping to get the ball rolling.
> Ideally,
> this guide should be used as a starting point from which a proper,
> officially-blessed and better-typeset guide can be fashioned.  Until that
> happens, I'm more than happy to host the guide at Code Commit,
> incorporating
> any revisions the community as a whole deems necessary.
>
> The source for the guide is in reStructuredText, which is easily
> convertible
> to distributable formats like HTML, LaTeX, TWiki markup and more.  For
> convenience, I have compiled the guide to a PDF (using rst2newlatex and
> pdflatex) and uploaded it along with the source.  The document does not
> include a license declaration, but you can pretty much consider the
> material
> to be Public Domain.
>
> Enjoy!
>
> Daniel
>
>    - http://www.codecommit.com/scala-style-guide.txt
>    - http://www.codecommit.com/scala-style-guide.pdf
>
>

Thanks, good work!

On page 5/6 of the PDF I found a minor glitch:

class Company {
private val _name: String = _
def name = _name
def name_=(name: String) {
_name = name
}
}

_name should be a var here, right?

Regards,
Daniel
--
View this message in context: http://old.nabble.com/-scala--Proposed-Style-Guide-tp26310456p26315308.html
Sent from the Scala mailing list archive at Nabble.com.




odersky
Joined: 2008-07-29,
User offline. Last seen 45 weeks 6 days ago.
Re: Proposed Style Guide

On Thu, Nov 12, 2009 at 7:40 PM, Daniel Spiewak wrote:
> If you're going with braces on the following line, then I guess it probably
> is best to use = on all methods.  However, as mentioned elsewhere in the
> guide, this really isn't the best practice.  The parser handles it, but only
> by introducing some really flaky disambiguation rules.
> Braces-on-the-following-line is bad for the same reason that suffix notation
> is bad.
>
I am still not convinced that the siambiguation rules can cause a
problem here. can somebody come up with an example?

Cheers

davetron5000
Joined: 2009-06-07,
User offline. Last seen 2 years 31 weeks ago.
Re: Proposed Style Guide
I didn't realize github supported ReST, d'oh (the formats are almost identical anyway).

I just chose "chapters" as "the quickest thing I could do to demonstrate what I meant".  I do think having bits in separate units has advantages (e.g. linking/referencing specific bits of the guide).

I guess if it were in ReST, it would probably be pretty simple to cat everything together and make the dead-tree version.  I'd be willing to spend some time on this if it would be helpful.

Dave

---
My Blog: http://www.naildrivin5.com/blog
Scala Tour for Java Developers: http://www.naildrivin5.com/scalatour
Fork me on Github: http://davetron5000.github.com



On Thu, Nov 12, 2009 at 1:47 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:
I don't have any objection to using GitHub to manage the guide; it's sort of up to everyone else.  I do know that I don't have anywhere near enough time to be the sole maintainer, so it's probably good to get this into a DVCS as soon as possible.  :-)

A couple thoughts:
  • Why did you convert it to .markdown?  GitHub supports reStructuredText (just use the .rst extension).  In fact, it has better support for ReST than it does for Markdown.
  • I'm not sure that I like the split into separate chapters.  This makes it a bit easier to follow in a web setting, but much harder to distribute as a single, atomic unit.  Also, I like PDF.  :-)
Daniel

On Thu, Nov 12, 2009 at 12:30 PM, David Copeland <davec@naildrivin5.com> wrote:
So, to demonstrate what I was saying vis a vis github and not having this passed around as a PDF:

http://github.com/davetron5000/scala-style

any push (to the gh-pages branch) regenerates the entire thing, which you can view here:

http://davetron5000.github.com/scala-style/

I think each individual section could be broken up into its own file.  Issues could be created, and changes can be commented upon, like :

http://github.com/davetron5000/scala-style/commit/404e269734eb535ad4b528552cc4acc851dcc3d4

Granted, this can't as easily be turned into a PDF, but, then again, no one should be printing this sort of thing out, IMO.

Dave

---
My Blog: http://www.naildrivin5.com/blog
Scala Tour for Java Developers: http://www.naildrivin5.com/scalatour
Fork me on Github: http://davetron5000.github.com



On Thu, Nov 12, 2009 at 1:17 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:
Yep, that's a typo.  I'll fix that asap.

Daniel

On Thu, Nov 12, 2009 at 4:57 AM, Landei <Daniel.Gronau@gmx.de> wrote:



Daniel Spiewak wrote:
>
> One of the things about Scala which has always bugged me is the *lack* of
> an
> official style guide.  There is simply no "right" way of doing things,
> syntactically speaking.  Over the years, the Scala community has attempted
> to fill the void (as it were) by defining a set of unofficial,
> word-of-mouth
> conventions.  Things like when to add parentheses to no-arg methods or
> what
> the preferred function literal definition style may be.
>
> This works fine for experienced Scala community members, but newcomers to
> the language are understandably baffled.  This also causes a great deal of
> frustration on larger Scala projects with less-experienced Scala
> developers
> as some code will be stylized in one way, while other code will use a
> different convention.
>
> A few months ago, I decided that I had run into this problem one too many
> times, and so I took the time (with the generous support of my employer)
> to
> create a full (-ish) style guide for Scala syntax, naming conventions and
> project management.  The guidelines it contains are based on what I have
> heard from the community and do not necessarily reflect my own preferences
> (e.g. function types).  When in doubt about a particular convention, I
> have
> alternately looked at Martin Odersky's code or simply relied on my own
> knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and
> criticisms are very welcome.
>
> I would like to submit this guide for adoption by the larger Scala
> community.  I know that sounds like I'm trying to foist my opinions on
> everyone else, but I'm really just hoping to get the ball rolling.
> Ideally,
> this guide should be used as a starting point from which a proper,
> officially-blessed and better-typeset guide can be fashioned.  Until that
> happens, I'm more than happy to host the guide at Code Commit,
> incorporating
> any revisions the community as a whole deems necessary.
>
> The source for the guide is in reStructuredText, which is easily
> convertible
> to distributable formats like HTML, LaTeX, TWiki markup and more.  For
> convenience, I have compiled the guide to a PDF (using rst2newlatex and
> pdflatex) and uploaded it along with the source.  The document does not
> include a license declaration, but you can pretty much consider the
> material
> to be Public Domain.
>
> Enjoy!
>
> Daniel
>
>    - http://www.codecommit.com/scala-style-guide.txt
>    - http://www.codecommit.com/scala-style-guide.pdf
>
>

Thanks, good work!

On page 5/6 of the PDF I found a minor glitch:

class Company {
private val _name: String = _
def name = _name
def name_=(name: String) {
_name = name
}
}

_name should be a var here, right?

Regards,
Daniel
--
View this message in context: http://old.nabble.com/-scala--Proposed-Style-Guide-tp26310456p26315308.html
Sent from the Scala mailing list archive at Nabble.com.





daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide
You already gave one earlier:

println("foo")
{
  bar()
}

The disambiguation rules are perfectly sound, but they lead to some strange syntactic cases like the above.  There's also the example of suffix issues that I gave in the guide:

val a = xs toList
bar()

The above will actually parse, but it won't pass semantic analysis because toList doesn't take any parameters.  Maybe this is an even better example of badness caused by disambiguation.

Daniel

On Thu, Nov 12, 2009 at 12:45 PM, martin odersky <martin.odersky@epfl.ch> wrote:
On Thu, Nov 12, 2009 at 7:40 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:
> If you're going with braces on the following line, then I guess it probably
> is best to use = on all methods.  However, as mentioned elsewhere in the
> guide, this really isn't the best practice.  The parser handles it, but only
> by introducing some really flaky disambiguation rules.
> Braces-on-the-following-line is bad for the same reason that suffix notation
> is bad.
>
I am still not convinced that the siambiguation rules can cause a
problem here. can somebody come up with an example?

Cheers

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide
I would be in favor.  One thing you do need to be careful of with the cat-together approach is to keep header levels straight.  You can see an example of this here: https://activeobjects.dev.java.net/source/browse/activeobjects/trunk/ActiveObjects/doc/

Daniel

On Thu, Nov 12, 2009 at 12:58 PM, David Copeland <davetron5000@gmail.com> wrote:
I didn't realize github supported ReST, d'oh (the formats are almost identical anyway).

I just chose "chapters" as "the quickest thing I could do to demonstrate what I meant".  I do think having bits in separate units has advantages (e.g. linking/referencing specific bits of the guide).

I guess if it were in ReST, it would probably be pretty simple to cat everything together and make the dead-tree version.  I'd be willing to spend some time on this if it would be helpful.

Dave

---
My Blog: http://www.naildrivin5.com/blog
Scala Tour for Java Developers: http://www.naildrivin5.com/scalatour
Fork me on Github: http://davetron5000.github.com



On Thu, Nov 12, 2009 at 1:47 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:
I don't have any objection to using GitHub to manage the guide; it's sort of up to everyone else.  I do know that I don't have anywhere near enough time to be the sole maintainer, so it's probably good to get this into a DVCS as soon as possible.  :-)

A couple thoughts:
  • Why did you convert it to .markdown?  GitHub supports reStructuredText (just use the .rst extension).  In fact, it has better support for ReST than it does for Markdown.
  • I'm not sure that I like the split into separate chapters.  This makes it a bit easier to follow in a web setting, but much harder to distribute as a single, atomic unit.  Also, I like PDF.  :-)
Daniel

On Thu, Nov 12, 2009 at 12:30 PM, David Copeland <davec@naildrivin5.com> wrote:
So, to demonstrate what I was saying vis a vis github and not having this passed around as a PDF:

http://github.com/davetron5000/scala-style

any push (to the gh-pages branch) regenerates the entire thing, which you can view here:

http://davetron5000.github.com/scala-style/

I think each individual section could be broken up into its own file.  Issues could be created, and changes can be commented upon, like :

http://github.com/davetron5000/scala-style/commit/404e269734eb535ad4b528552cc4acc851dcc3d4

Granted, this can't as easily be turned into a PDF, but, then again, no one should be printing this sort of thing out, IMO.

Dave

---
My Blog: http://www.naildrivin5.com/blog
Scala Tour for Java Developers: http://www.naildrivin5.com/scalatour
Fork me on Github: http://davetron5000.github.com



On Thu, Nov 12, 2009 at 1:17 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:
Yep, that's a typo.  I'll fix that asap.

Daniel

On Thu, Nov 12, 2009 at 4:57 AM, Landei <Daniel.Gronau@gmx.de> wrote:



Daniel Spiewak wrote:
>
> One of the things about Scala which has always bugged me is the *lack* of
> an
> official style guide.  There is simply no "right" way of doing things,
> syntactically speaking.  Over the years, the Scala community has attempted
> to fill the void (as it were) by defining a set of unofficial,
> word-of-mouth
> conventions.  Things like when to add parentheses to no-arg methods or
> what
> the preferred function literal definition style may be.
>
> This works fine for experienced Scala community members, but newcomers to
> the language are understandably baffled.  This also causes a great deal of
> frustration on larger Scala projects with less-experienced Scala
> developers
> as some code will be stylized in one way, while other code will use a
> different convention.
>
> A few months ago, I decided that I had run into this problem one too many
> times, and so I took the time (with the generous support of my employer)
> to
> create a full (-ish) style guide for Scala syntax, naming conventions and
> project management.  The guidelines it contains are based on what I have
> heard from the community and do not necessarily reflect my own preferences
> (e.g. function types).  When in doubt about a particular convention, I
> have
> alternately looked at Martin Odersky's code or simply relied on my own
> knowledge of Java, C#, Standard ML and Haskell conventions.  Comments and
> criticisms are very welcome.
>
> I would like to submit this guide for adoption by the larger Scala
> community.  I know that sounds like I'm trying to foist my opinions on
> everyone else, but I'm really just hoping to get the ball rolling.
> Ideally,
> this guide should be used as a starting point from which a proper,
> officially-blessed and better-typeset guide can be fashioned.  Until that
> happens, I'm more than happy to host the guide at Code Commit,
> incorporating
> any revisions the community as a whole deems necessary.
>
> The source for the guide is in reStructuredText, which is easily
> convertible
> to distributable formats like HTML, LaTeX, TWiki markup and more.  For
> convenience, I have compiled the guide to a PDF (using rst2newlatex and
> pdflatex) and uploaded it along with the source.  The document does not
> include a license declaration, but you can pretty much consider the
> material
> to be Public Domain.
>
> Enjoy!
>
> Daniel
>
>    - http://www.codecommit.com/scala-style-guide.txt
>    - http://www.codecommit.com/scala-style-guide.pdf
>
>

Thanks, good work!

On page 5/6 of the PDF I found a minor glitch:

class Company {
private val _name: String = _
def name = _name
def name_=(name: String) {
_name = name
}
}

_name should be a var here, right?

Regards,
Daniel
--
View this message in context: http://old.nabble.com/-scala--Proposed-Style-Guide-tp26310456p26315308.html
Sent from the Scala mailing list archive at Nabble.com.






ichoran
Joined: 2009-08-14,
User offline. Last seen 2 years 3 weeks ago.
Re: Proposed Style Guide
On Thu, Nov 12, 2009 at 1:38 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:

3. Normal type parameters can occasionally also have full names, if
there's not good name
   you cann think of, A, B, C work fine.

I disagree on the full-names bit.  As others have pointed out, Doing something like class Foo[Bar] { def baz(b: Bar) } often results in a painful and fruitless search through the scaladoc for type "Bar".  I think it's just much clearer when type parameters have an obviously-distinct naming convention.

If we must use full names, we should adopt the all upper-case convention mentioned elsewhere (e.g. BAR).

This use of caps is particularly handy since Scala doesn't use all caps for constants and does use generics pretty heavily--so this is a great way to make things clearer.
 
7. Declarations: I would not be 100% strict about inserting empty
lines around defs. For instance, if you declare a simple forwarding
class, you want to squeeze multiple defs together, without intervening
blank lines. Otherwise I agree with your recommendation.

Maybe in the absolutely-trivial case the spaces could be dropped, but it's a very slippery slope.  I've seen some nigh-unreadable code due to a lack of proper spacing.

For particularly long classes with lots of methods that come in groups, I find it nigh-impossible to delineate the groupings clearly unless I use no blank lines, single blank lines, and two (or more) blank lines to separate things into very closely related, somewhat related, and largely different categories.

Arguably, one should split up the class at that point, but doing so prematurely simply because style guidelines make it extra-hard to figure out what's going on seems silly to me.
 
  9. I am against putting braces around case expressions. I find

 foo match {
    case P =>
       val x = expr1
       f(x)
    case Q =>
       expr2
 }

much more readable than:

 foo match {
    case P => {
       val x = expr1
       f(x)
    }
    case Q =>
       expr2
 }

I disagree here.  It's nice to save the unnecessary braces, but it causes a lot of problems in the long run:
  • Non-semantic editor auto-indentation chokes.  I don't think that even the Emacs mode can handle this case, and I know for a fact that jEdit can't.
  • Non-uniformity with non-single-expr cases
My opinion is that uniformity is more important than saving a few curly-braces.

I much prefer the no-braces version since
  (1) it's utterly clear visually where the block ends anyway, and
  (2) the second form wastes an extra line and visible-vertical-lines-of-code is correlated with increased productivity.

If editors are not clever enough to figure out the borders, then if one has adopted a specific editor, one can adopt alternate style guidelines to try to keep it happy, but I wouldn't put that in a generic style document.

(Any editor smart enough to handle Python should be able to add braceless case support in Scala.)
 
13. Operators: The only situation where I do not put spaces around an
operator is for String-concat. I prefer either of

 "prefix "+elem+" suffix"
 "prefix "+ elem +" suffix"

to

 "prefix " + elem + " suffix"

Putting spaces around string concat makes everybody clamor for string
interpolation notation in Scala, because it is so bad.

I strongly disagree here.  Most string concatenation doesn't involve literals all over the place, so what do you do in that case?  Do you always drop the space for the String#+ method?  This again violates the principle of uniformity and has a tendency to confuse beginners about the nature of symbolic method names (and especially mixed symbolic method names).

Whether concatenation involves mostly literals or not depends upon what you are using Scala for.  As a scripting language replacement, there are literals all over.  Since whitespace is important in output, it's nice to have the whitespace only appear inside the quotes so you can visually tell (more easily, anyway) where the whitespace will appear.

And, as usual, it depends on what you're doing as to whether space is helpful or not:

"My " + (if (x isBest) "best "+x.bestName else "good "+x.goodName) + " widget"

is probably the clearest way to space (and not-space) things out if one wants to stay to one line.  (One could argue that this is best placed on several lines, of course.)
   --Rex

odersky
Joined: 2008-07-29,
User offline. Last seen 45 weeks 6 days ago.
Re: Proposed Style Guide

On Thu, Nov 12, 2009 at 7:49 PM, Daniel Spiewak wrote:
> You already gave one earlier:
>
> println("foo")
> {
>   bar()
> }
>
> The disambiguation rules are perfectly sound, but they lead to some strange
> syntactic cases like the above.

Yes, but none of that is solved by the rule that forbids putting
braces on the next line. It rather makes it worse: If the convention
is forbidden, then people will be even more surprised that the
compiler will interpret it like that! I really believe the only way
out is to enforce the locally convention.

There's also the example of suffix issues
> that I gave in the guide:
>
> val a = xs toList
> bar()
>
> The above will actually parse, but it won't pass semantic analysis because
> toList doesn't take any parameters.  Maybe this is an even better example of
> badness caused by disambiguation.
>
Yes, there we agree. -- Martin

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide

I wouldn't exactly say the problem is "solved", but it is resolved. I
do agree that there isn't a better set of disambiguation rules, which
is precisely why we need to give up on making Scala's grammar
unambiguous.

Maybe this is a bit of a thread hijacking, but I would like to point
out that there are just some language features which require ambiguity
in the grammar. Haskell's mixfix operators are a fine example of
this, though in that case the problem can be "solved" by making the
parser weakly aware of the language semantics. In Scala's case, I
firmly believe that the best approach is to allow local ambiguity.
Most ambiguities in Scala resolve themselves within a few phrases.
But even if they don't, there's really no harm in generating a parse
forrest which can be disambiguated later in the analysis phase. In
the extremely rare case that the ambiguity remains unresolved going
into code gen, the compiler could simply throw up an error about being
unable to disambiguate a particular line.

My point is that adding disambiguation rules will *always* be the
wrong thing to do. While there are some rules which are less
surprising than others, they all have their corner cases.

Daniel

On Nov 12, 2009, at 3:07 PM, "martin odersky"
wrote:

> On Thu, Nov 12, 2009 at 7:49 PM, Daniel Spiewak
> wrote:
>> You already gave one earlier:
>>
>> println("foo")
>> {
>> bar()
>> }
>>
>> The disambiguation rules are perfectly sound, but they lead to some
>> strange
>> syntactic cases like the above.
>
> Yes, but none of that is solved by the rule that forbids putting
> braces on the next line. It rather makes it worse: If the convention
> is forbidden, then people will be even more surprised that the
> compiler will interpret it like that! I really believe the only way
> out is to enforce the locally convention.
>
> There's also the example of suffix issues
>> that I gave in the guide:
>>
>> val a = xs toList
>> bar()
>>
>> The above will actually parse, but it won't pass semantic analysis
>> because
>> toList doesn't take any parameters. Maybe this is an even better
>> example of
>> badness caused by disambiguation.
>>
> Yes, there we agree. -- Martin

Mats Henricson
Joined: 2009-01-14,
User offline. Last seen 2 years 28 weeks ago.
Re: Proposed Style Guide

Thanks for the effort! A colleague and I spent much of our
free time for about 3.5 years writing a programming guidelines
book for C++, so I have huge respect for these kinds of
documents. Discussions can be very heated, and in many cases
there just aren't ideal solutions - you just have to pick the
least bad solution and stick to it.

Our book is now available here:

http://www.sannabremo.se/nyquist/industrial/

Language details and length aside, there are two important
differences between your document and our book:

First, we split our guidelines into two types, Rules and
Recommendations. The difference should be clear. There are
few rules compared to recs, and the you need a very very
good reason to break a rule. The benefit from this is that
you get better respect for the rules, which if broken makes
a big mess. Beginner or expert, you don't break rules.

Secondly, our rules and recs are very very consisely worded,
and listed very explicitly at the beginning of each section
of the book. Example:

Rule 4.1 Do not change a loop variable inside a for -loop
block.

Rec 4.2 Update loop variables close to where the loop-condition
is specified.

Rec 4.3 All flow control primitives ( if, else, while, for, do,
switch and case ) should be followed by a block, even if
it is empty.

Rec 4.4 Statements following a case label should be terminated
by a statement that exits the switch statement.

Rec 4.5 All switch statements should have a default clause.

Rule 4.6 Use break and continue instead of goto .

Rec 4.7 Do not have too complex functions.

After this list, each and every rule and rec was explained.

In your document you can find similar guidelines, but they are
hidden within blocks of code and text.

I could spend time with you trying to distill the true rules and
recs in your document, if you are interested.

Mats

> One of the things about Scala which has always bugged me is the /lack/
> of an official style guide. There is simply no "right" way of doing
> things, syntactically speaking. Over the years, the Scala community has
> attempted to fill the void (as it were) by defining a set of unofficial,
> word-of-mouth conventions. Things like when to add parentheses to
> no-arg methods or what the preferred function literal definition style
> may be.
>
> This works fine for experienced Scala community members, but newcomers
> to the language are understandably baffled. This also causes a great
> deal of frustration on larger Scala projects with less-experienced Scala
> developers as some code will be stylized in one way, while other code
> will use a different convention.
>
> A few months ago, I decided that I had run into this problem one too
> many times, and so I took the time (with the generous support of my
> employer) to create a full (-ish) style guide for Scala syntax, naming
> conventions and project management. The guidelines it contains are
> based on what I have heard from the community and do not necessarily
> reflect my own preferences (e.g. function types). When in doubt about a
> particular convention, I have alternately looked at Martin Odersky's
> code or simply relied on my own knowledge of Java, C#, Standard ML and
> Haskell conventions. Comments and criticisms are very welcome.
>
> I would like to submit this guide for adoption by the larger Scala
> community. I know that sounds like I'm trying to foist my opinions on
> everyone else, but I'm really just hoping to get the ball rolling.
> Ideally, this guide should be used as a starting point from which a
> proper, officially-blessed and better-typeset guide can be fashioned.
> Until that happens, I'm more than happy to host the guide at Code
> Commit, incorporating any revisions the community as a whole deems
> necessary.
>
> The source for the guide is in reStructuredText, which is easily
> convertible to distributable formats like HTML, LaTeX, TWiki markup and
> more. For convenience, I have compiled the guide to a PDF (using
> rst2newlatex and pdflatex) and uploaded it along with the source. The
> document does not include a license declaration, but you can pretty much
> consider the material to be Public Domain.
>
> Enjoy!
>
> Daniel
>
> * http://www.codecommit.com/scala-style-guide.txt
> * http://www.codecommit.com/scala-style-guide.pdf
>

Christian Helmbold
Joined: 2009-06-08,
User offline. Last seen 1 year 40 weeks ago.
AW: Proposed Style Guide

I like the effort to create a Scala style guide and I think it is helpful for the success of the language. At the moment the style guide is discussed as a whole and I suggest to discuss it section by section. For each section we should talk about
1. bad examples,
2. good examples and
3. the rules and recommendations derived from both.
The result would be a widely accepted, well thought out part of the style guide.

I think that we'll get a more profound discussion, when we talk focused on a specific section of the style guide.

Further sources of inspiration:
* Clean Code http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132...
* Discussion about the Zen of Scala (inspired from the "Zen of Python") http://scala-forum.org/read.php?4,224

Christian

David Copeland
Joined: 2009-06-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide
Per a discussion within this discussion, I have split up the style guide into sections on github:

http://github.com/davetron5000/scala-style/tree/master

Click on Chapters and you sill see the structure.

Right now, I can recreate the original .rst file via rake, and will set up a means to turn this into LaTeX and HTML on github pages.

The setup is a bit hacky, but I wanted to get something up quickly without any yak-shaving; obviously, the string-ordering of the files is how they are all glued together.  So, to insert a new section in, say "Types", we'd have to do some renames.  not a big deal for Git, and we can get something a little less cheesy later, if this basic mechanism is found useful.

Daniel: if you want commit access to this repo, let me know, or you can fork it and become the owner.

Dave

---
My Blog: http://www.naildrivin5.com/blog
Scala Tour for Java Developers: http://www.naildrivin5.com/scalatour
Fork me on Github: http://davetron5000.github.com



On Fri, Nov 13, 2009 at 2:28 AM, Christian Helmbold <christian.helmbold@yahoo.de> wrote:
I like the effort to create a Scala style guide and I think it is helpful for the success of the language. At the moment the style guide is discussed as a whole and I suggest to discuss it section by section. For each section we should talk about
 1. bad examples,
 2. good examples and
 3. the rules and recommendations derived from both.
The result would be a widely accepted, well thought out part of the style guide.

I think that we'll get a more profound discussion, when we talk focused on a specific section of the style guide.

Further sources of inspiration:
* Clean Code http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/
* Discussion about the Zen of Scala (inspired from the "Zen of Python") http://scala-forum.org/read.php?4,224

Christian




David Copeland
Joined: 2009-06-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide
I updated the github version with the only two comments in this thread I could dig out as more-or-less universally agreed-upon:

http://github.com/davetron5000/scala-style/commits/master/

- Descriptive type parameters should be ALL CAPS - http://github.com/davetron5000/scala-style/commit/f5c998816e6d1ec79ff9100ebd5b2ec6dae02fb2
- Spaces after colons for type ascription, except for varargs _* form - http://github.com/davetron5000/scala-style/commit/ec1aaac00643d7a39d30d8794c1c443eba9a2662

I couldn't determine anything else other than some updates for 2.8

Dave

---
My Blog: http://www.naildrivin5.com/blog
Scala Tour for Java Developers: http://www.naildrivin5.com/scalatour
Fork me on Github: http://davetron5000.github.com



On Thu, Nov 12, 2009 at 1:38 PM, Daniel Spiewak <djspiewak@gmail.com> wrote:

Thanks, Daniel that's really useful! By and large I agree with what's
proposed in the style guide, except for some reservations listed
below. It would be a good idea if we could evolve this to something
which we can put up on scala-lang as an official document (provided
you are happy with that).

I would be very much in favor.  In fact, that's the whole reason I posted the guide here.  :-)  I would like for there to be some officially-endorsed Scala style guide, even if it doesn't agree with my personal preferences.

1. Object naming conventions: I still hesitate between lower and upper
case. The problem is that another way to see an object is as a lazy
val with an (unnamed?) class. In that case lower case would apply.

Are you talking about the pattern where object is used as if it were a field?  (Lift does this a lot)  If so, then yes I do agree.  I should probably make mention of that in the guide; in that case, the object name should be lower-case as it is masquerading as a val.
 
2. As others have noted the discussion of nested packages does not
reflect what's in 2.8.

I'll need some help to update this one.  Would someone be willing to submit a patch?

3. Normal type parameters can occasionally also have full names, if
there's not good name
   you cann think of, A, B, C work fine.

I disagree on the full-names bit.  As others have pointed out, Doing something like class Foo[Bar] { def baz(b: Bar) } often results in a painful and fruitless search through the scaladoc for type "Bar".  I think it's just much clearer when type parameters have an obviously-distinct naming convention.

If we must use full names, we should adopt the all upper-case convention mentioned elsewhere (e.g. BAR).
 
4. Not 100% sure about Void-methods. Sometimes the : Unit = form is shorter.

When it really is a huge savings, I guess I can see advantages to the : Unit = form.  However, I have found that by preferring the non-= form, it becomes much more apparent to the eye as to which methods are Unit and which are not.  In terms of mental compilation, the non-= form only requires parsing the syntax (a very quick, visual operation), whereas the : Unit = form requires a full semantic analysis of the method body.

Even more importantly, the un-annotated : Unit = form is prone to mistakes due to the fact that type-inference will happily assign whatever type the last expression in the method may produce.  This has bitten me on many occasions, which is why I switched my personal convention from : Unit = to the non-= form.
 
5. I would not recommend spaceless syntax for type ascription. Type
ascription has relatively low priority. For instance,

 1 < 2:Boolean

parses visually as 1 < (2:Boolean), but means actually (1 < 2):
Boolean. So I would prefer either the asymmetric x: T notation, or the
symmetric notation with spaces, i.e. x : T.

I'll agree with you on this one.  It also eliminates a special-case in the conventions (longer ascription).  The main reason to use the no-space syntax is for something like foo:_*, which looks a little odd as `foo: _*`.  I think the gained uniformity is worth it though.
 
6. I think the discussion wrt curly braces at the top of page 12 is
not accurate. AFAIK the parser only mispredicts in the other sense.
That is, if you open a block with a curly brace immediately following
some construct, the parser will usually interpret this as part of the
previous line. So I would instead propose the following convention:

If you mean to write a nested block in a statement sequence, prefix it
with `locally' (defined in 2.8 Predef): I.e.

 print("hello")
 locally {
    var = 1
    ...
 }

The parser does do a pretty decent job of picking up curly braces, but it still has its wrinkles (as pointed out by Josh S in another thread).  This is yet another example of an area in which Scala's parser would be well served by a generalized algorithm allowing local ambiguity in the grammar.  Might I suggest GLL?  :-)
 
7. Declarations: I would not be 100% strict about inserting empty
lines around defs. For instance, if you declare a simple forwarding
class, you want to squeeze multiple defs together, without intervening
blank lines. Otherwise I agree with your recommendation.

Maybe in the absolutely-trivial case the spaces could be dropped, but it's a very slippery slope.  I've seen some nigh-unreadable code due to a lack of proper spacing.
 
8. Modifiers: I usually put protected in front of override, but I have
no problem reading code that does not.

The C# convention is to put override after the access modifier, while the Java syntax forces @Override to come prior to modifiers.  Since Java has "higher precedence" in my list of inspirational languages at the top of the doc, I went with the prefix form.  I'm open to either route though.
 
9. I am against putting braces around case expressions. I find

 foo match {
    case P =>
       val x = expr1
       f(x)
    case Q =>
       expr2
 }

much more readable than:

 foo match {
    case P => {
       val x = expr1
       f(x)
    }
    case Q =>
       expr2
 }

I disagree here.  It's nice to save the unnecessary braces, but it causes a lot of problems in the long run:
  • Non-semantic editor auto-indentation chokes.  I don't think that even the Emacs mode can handle this case, and I know for a fact that jEdit can't.
  • Non-uniformity with non-single-expr cases
My opinion is that uniformity is more important than saving a few curly-braces.  For most people, val a = ...; blah looks like two statements, regardless of the fact that it parses as a single expression.
 
10. Comprehensions: I hesitate to demand for { ... } syntax for all
comprehensions with multiple generators. As an example, consider a
simple matrix map:

 for (i <- 1 to N; j <- 1 to M) yield m(i)(j) + 1

Changing this to

 for {
    i <- 1 to N
    j <- 1 to M
 } yield m(i)(j) + 1

does not increase readability IMO. So, maybe accept the single line
syntax for multiple generators if they follow a simple, repetitive
pattern.

Actually, I find the latter form more readable than the former.  I will yield to the community (no pun intended) on this one if there are strong feelings.
 
12. On Arity 1: I am not sure I agree with your criterion of
side-effect freeness for operator notation (but I don't have a better
one to offer).

All I know is it's a little weird to look at something like `foo add bar`.  Infix methods are really meant to handle operators, which (as mentioned elsewhere in the guide) should be mathematical and thus, purely-functional.
 
13. Operators: The only situation where I do not put spaces around an
operator is for String-concat. I prefer either of

 "prefix "+elem+" suffix"
 "prefix "+ elem +" suffix"

to

 "prefix " + elem + " suffix"

Putting spaces around string concat makes everybody clamor for string
interpolation notation in Scala, because it is so bad.

I strongly disagree here.  Most string concatenation doesn't involve literals all over the place, so what do you do in that case?  Do you always drop the space for the String#+ method?  This again violates the principle of uniformity and has a tendency to confuse beginners about the nature of symbolic method names (and especially mixed symbolic method names).

I have read other forum posts which give your rationale for this style, and while I can see your points, I still disagree.  :-)  Here also, we should assign some weight to established conventions in the "inspirational" languages, especially Java.  In Java, it is a strong convention to put spaces around operators, even in string concatenation.  In fact, I think that's a convention in every language I listed with the possible exception of Haskell (which ironically, doesn't need the no-space convention since it uses ++).
 
14. Function literals with `_'. I quite like your recommendation to use

 { x + _ }

even though personally I have mostly used (x + _) so far.

:-)  Thanks!  The curly brace thing really helps to distinguish function literals from other values in code, making the control flow a bit more intuitive.

Daniel

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Proposed Style Guide

On Fri, Nov 13, 2009 at 04:03:04PM -0500, David Copeland wrote:
> - Spaces after colons for type ascription, except for varargs _* form -
> http://github.com/davetron5000/scala-style/commit/ec1aaac00643d7a39d30d8...

Do not like. Did a quick grep on trunk source and ": _*" is many times
more common than ":_*" and I'm glad. Simplify rule, omit exception.

Pavol Vaskovic
Joined: 2009-11-10,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide

On 13.11.2009, at 22:21, Paul Phillips wrote:

> On Fri, Nov 13, 2009 at 04:03:04PM -0500, David Copeland wrote:
>> - Spaces after colons for type ascription, except for varargs _*
>> form -
>> http://github.com/davetron5000/scala-style/commit/ec1aaac00643d7a39d30d8...
>
> Do not like. Did a quick grep on trunk source and ": _*" is many
> times
> more common than ":_*" and I'm glad. Simplify rule, omit exception.

+1
see also http://stackoverflow.com/questions/1124099/

Wouldn't it help if there were defined standard *names* for similar
operator-esque notations commonly used in Scala? Non-trivial operators
are generally non-googlable, which is maybe OK for internal DSLs, but
not helpful in learning the standard Scala library.

I guess that x: _* would be called "repeated parameter type ascription"?

Maybe the style guide section about operators should include something
like: "Consider defining standard pronunciation for the operator in
scaladoc." Examples include cons operator (::) or bang operator (!).

Related to "[scala-user] Scaladoc that is actually useful?", it
appears that the current style guide accurately reflects the state of
scala library documentaion by ommiting any recommendations on Scaladoc
(Documentation Comments) usage ;-)
I take this means that conventions from Java are to be followed?

Regards
Pavol Vaskovic

davetron5000
Joined: 2009-06-07,
User offline. Last seen 2 years 31 weeks ago.
Re: Proposed Style Guide
Much updated, aesthetically-speaking, and also simplified the use of the repeated parameter type ascription (boy, that is a mouthful).

Very limited styles that match scala-lang, plus a TOC, which I think helps a lot with navagability.

http://davetron5000.github.com/scala-style

source is here:

http://github.com/davetron5000/scala-style/

I'm very new at ReStructured text, and I have yet to install LaTeX on my box, so PDF is coming (and should hopefully look just like the original, with the few changes that have been made).  Is there a way to do a #include in ReST?  I would love to get rid of my cheesy "cat things together in the order found" stuff and put the doc structure into the doc itself.

Agree on scaladoc; if someone wants to write up something, I can stick it in, otherwise, maybe I'll take a crack at it tomorrow.

Dave

---
My Blog: http://www.naildrivin5.com/blog
Scala Tour for Java Developers: http://www.naildrivin5.com/scalatour
Fork me on Github: http://davetron5000.github.com



On Fri, Nov 13, 2009 at 7:03 PM, Pavol Vaskovic <pali@pali.sk> wrote:

On 13.11.2009, at 22:21, Paul Phillips wrote:

On Fri, Nov 13, 2009 at 04:03:04PM -0500, David Copeland wrote:
- Spaces after colons for type ascription, except for varargs _* form -
http://github.com/davetron5000/scala-style/commit/ec1aaac00643d7a39d30d8794c1c443eba9a2662

Do not like.  Did a quick grep on trunk source and ": _*" is many times
more common than ":_*" and I'm glad.  Simplify rule, omit exception.

+1
see also http://stackoverflow.com/questions/1124099/

Wouldn't it help if there were defined standard *names* for similar operator-esque notations commonly used in Scala? Non-trivial operators are generally non-googlable, which is maybe OK for internal DSLs, but not helpful in learning the standard Scala library.

I guess that x: _* would be called "repeated parameter type ascription"?

Maybe the style guide section about operators should include something like: "Consider defining standard pronunciation for the operator in scaladoc." Examples include cons operator (::) or bang operator (!).

Related to "[scala-user] Scaladoc that is actually useful?", it appears that the current style guide accurately reflects the state of scala library documentaion by ommiting any recommendations on Scaladoc (Documentation Comments) usage ;-)
I take this means that conventions from Java are to be followed?

Regards
Pavol Vaskovic

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide

Very limited styles that match scala-lang, plus a TOC, which I think helps a lot with navagability.

Looks nice.  My one thought is to drop the font-weight: bold on the code snippets.  It makes the text quite blurry on Mac (at least to my eyes).
 
I'm very new at ReStructured text, and I have yet to install LaTeX on my box, so PDF is coming (and should hopefully look just like the original, with the few changes that have been made).  Is there a way to do a #include in ReST?  I would love to get rid of my cheesy "cat things together in the order found" stuff and put the doc structure into the doc itself.

Unfortunately, there is no way to do #include.  I mean, you could technically run it through the C pre-processor and get it that way, but I don't recommend it.  :-)  Believe it or not, catting things together is actually the recommended way to do this sort of thing with ReST.

Daniel
geoff
Joined: 2008-08-20,
User offline. Last seen 1 year 25 weeks ago.
Re: Proposed Style Guide

On Sat, Nov 14, 2009 at 05:57:49PM -0600, Daniel Spiewak said
> > I'm very new at ReStructured text, and I have yet to install LaTeX on my
> > box, so PDF is coming (and should hopefully look just like the original,
> > with the few changes that have been made). Is there a way to do a #include
> > in ReST? I would love to get rid of my cheesy "cat things together in the
> > order found" stuff and put the doc structure into the doc itself.
> >
>
> Unfortunately, there is no way to do #include. I mean, you could *
> technically* run it through the C pre-processor and get it that way, but I
> don't recommend it. :-) Believe it or not, catting things together is
> actually the recommended way to do this sort of thing with ReST.

There is an include directive actually.

http://docutils.sourceforge.net/docs/ref/rst/directives.html#including-a...

It's got some stuff so that it can process only part of the included
file. This could be useful for having a header in the parts that are
used when converting to individual HTML pages but skipped when making a
single PDF.

David Copeland
Joined: 2009-06-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide
OK, I think I have a reasonable 1.0 of this whole setup; PDF is generated, as is HTML, both with TOC's.  I still need to move to the include directive below, but for the most part, it's pretty stable.

I added a new section documenting that @annotations are lower-cased, but the content is by and large the original.  I'll cease posting every little change I make to the list at this point; I think there were a few contentious things unresolved in this thread; I'll try to comb through at some point to see if we can agree or not.

http://davetron5000.github.com/scala-style

Dave

---
My Blog: http://www.naildrivin5.com/blog
Scala Tour for Java Developers: http://www.naildrivin5.com/scalatour
Fork me on Github: http://davetron5000.github.com



On Sat, Nov 14, 2009 at 7:55 PM, Geoff Reedy <geoff@programmer-monk.net> wrote:
On Sat, Nov 14, 2009 at 05:57:49PM -0600, Daniel Spiewak said
> > I'm very new at ReStructured text, and I have yet to install LaTeX on my
> > box, so PDF is coming (and should hopefully look just like the original,
> > with the few changes that have been made).  Is there a way to do a #include
> > in ReST?  I would love to get rid of my cheesy "cat things together in the
> > order found" stuff and put the doc structure into the doc itself.
> >
>
> Unfortunately, there is no way to do #include.  I mean, you could *
> technically* run it through the C pre-processor and get it that way, but I
> don't recommend it.  :-)  Believe it or not, catting things together is
> actually the recommended way to do this sort of thing with ReST.

There is an include directive actually.

http://docutils.sourceforge.net/docs/ref/rst/directives.html#including-an-external-document-fragment

It's got some stuff so that it can process only part of the included
file. This could be useful for having a header in the parts that are
used when converting to individual HTML pages but skipped when making a
single PDF.

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Re: Proposed Style Guide

* Content

I feel there are a FEW too many "if" statements.

Agreed.  The style and format needs work.
 
** Unit/Void methods

I see no gains to

 def voidMethod() { /* do something */ }

over

 def voidMethod(): Unit = { /* do something */ }

The advantage boils down to the fact that it is not required to explicitly annotate the : Unit type.  Of course, we can always rely on type inference to get the type for us, but such a technique very seldom works with unit methods.  This is because non-trivial unit methods will most often consist of an expression which does not return Unit.  Thus, the public signature of the method could be wrong, and you would never catch it.  This ties back into the advice to explicitly annotate all public methods.  If we use the short-hand Unit syntax, we can get the explicit annotation without extra syntax.  In fact, it actually saves us two characters over the inferred form (for whatever that's worth).  
 
Rules that are "always do X" are a lot easier to understand an apply.  If
someone learning Scala NEVER sees the first form, that is a good thing.
Further, Unit methods should be rare,
so I see no need to shortcut their creation

Unfortunately, they're not as rare as one would hope, especially in real-world systems which deal with external conditions and side-effects.
 
** Paren-less vs 0-arg functions/method

I found this confusing.  I think the paren-less form should be reserved for DSLs
only and one should always use parens.  It just makes things a LOT clearer;
when you see parens, you are seeing a function/method call.

This is a very important one.  I can't emphasize this idiom enough.  The paren-less form is important because it unifies the signature of side-effect-free methods with actual fields.  Thus, it is possible to switch between def, val and lazy val without changing the public interface.  Finally, strict adherence to the syntax makes it easy to see which methods have side-effects and which ones are functional.
 
** When to use dot-invocation and when not

I *think* I agree with the convention here, but found it pretty hard to follow.
Maybe a few more examples showing the "all-dot-invocation" form as comparison?

Yeah, more examples would be good.

Daniel

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide
Commenting on a style guide would normally not be my thing, but since
martin did I'm afraid it'll end up gaining an aura of officialness,
so...  My #1 suggestion is to separate it into sections which are
uncontroversial (at least mostly) and sections where there is a
diversity of opinion.  That gives us at least a chance at a core of
consistency.  Without that separation it'll only be ignored.

I'm not sure that sacrificing organizational structure for the sake of appeasing controversy is the best decision.  However, I can certainly understand the sentiment.  Perhaps an annotation of some sort for each controversial guideline?  That way, newcomers can easily see which styles are universally accepted, and which ones are open for debate.
 
"Line Wrapping"

val result = 1 + 2 + 3 + 4 + 5 + 6 +
     7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 +
     15 + 16 + 17 + 18 + 19 + 20

This is needlessly error prone.  Do this:

val result = (
     1 + 2 + 3 + 4 + 5 + 6 +
     7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 +
     15 + 16 + 17 + 18 + 19 + 20
)

Now you can end your lines however you want.  You can't have multiple
statements in there, so if you forget a + it won't compile.

Very true.  However, this treats parentheses like braces.  I would rather keep the rules for this distinct.  I usually treat parentheses like Lisp parens (with the closing paren on the same line as the last expression) and braces like Java-style braces.  This emphasizes the grammatical differences between the two.
 
"Packages"

It's _root_, not __root__.

Yeah, typo.  I never use _root_, so it wasn't immediately on my mind.
 
"Parentheses"

I think this situation is hopeless and attempts to define when to use
empty parens vs. no parens can only have two results: 1) lots of
pointless arguing among people who have better things to do and 2) being
ignored by or unknown to 98% of scala programmers.

As mentioned earlier, this is one on which I really think is worth holding the line.  Speaking from experience, strict adherence to this guideline makes a huge difference in the readability of your code.  Maybe we need more examples in this section to help clarify things.

"Declarations"

"All class/object/trait members should be declared interleaved with
newlines."

No.  There is no reason to make an exception for var and val but not
def, they're the same thing.  It's a matter of sensible grouping, like
when to start a new paragraph in prose.

Ok, I'll buy that.  Maybe the guideline should be that trivial members (with expression bodies of less than 30 chars) can be smushed together when they represent a logical group, otherwise interleave.  The problem I'm trying to head off is when all members in a class/trait/object are unseparated.  I would rather over-separate than under, since the latter is far less readable than the former.
 
"Function Values"

"Of these styles, (1) and (4) are to be preferred at all times."

...except for all the times when one might prefer (2) or (3), which for
me is plenty often.  Especially, I avoid curly braces almost whenever
possible, with the notable exception of situationally using them in
if/then/else situations if it looks easy to misread the logic.

I can sympathize with your wish to avoid curly-braces.  I try to do the same.  However, we have to face up to the fact that this is Scala, not Lisp.  Curly braces are literally an unavoidable aspect of the grammar.  It is best to use them in a consistent and visually distinct fashion.  Thus, expression grouping should be done using parentheses, while blocks should be denoted with braces.  This relates back into function literals.  Multi-line functions always use braces (they are forced to do so by the syntax), and so consistency would dictate that even single line literals do the same.

This idiom also makes for a very nice visual cue that some sort of deferred execution is involved.  Consider the following:

foo + bar
xs.foldLeft(fooBar)(_ + _)
baz + bin

Vs the following:

foo + bar
xs.foldLeft(foobar) { _ + _ }
baz + bin

In the second form, the function literal is very clearly delineated.  It's pretty clear that the second parameter of the fold is something out of the ordinary.  When scanning code quickly, this can be a huge lifesaver.

So, in summary: braces for function literals help a lot in terms of consistency and easy visual signaling.  They are an unavoidable part of the grammar, so it's quite futile to try to suppress them without a really good reason.
 
"Omit braces if the ``case`` expression fits on a single line.
Otherwise, use curly braces for clarity (even though they are not
*required* by the parser)."

Oh god no, not having to use braces on case statements is one of their
greatest features.

This seems to be a controversial guideline.  My reasoning is mostly oriented around text editors, which (as I said) have a really hard time with this syntax.  It's not simply a matter of being able to handle Python.  Scala has a much more complicated syntax than Python.  Auto-indent for Python can be done exclusively with regular expressions, while Scala auto-indent is significantly more complex (believe me, I've tried).  As it turns out, Scala auto-indent is still regular...but only if we take a pass on the no-brace case syntax.  Auto-indent here requires some notion of context.  Emacs could do it, but not many other editors.

Once we have better IDE support, maybe this guideline could be rescinded.  I suppose that the best solution for the moment would be to lay out both alternatives and explain that one is preferred ideally, but the other is more amenable to non-supernatural editors.
 
"Comprehensions"

   // wrong!
   for (x <- board.rows; y <- board.files)
     yield (x, y)

I'm going with "right", although the yield goes on the first line.

That's two votes against "my style", this is probably worthy of some more discussion in a separate thread.
 
"Arity-1"

   // wrong!
   javaList add item

We got this one wrong in about 5000 spots in the compiler.  I'm going
with "right" again.

Then you got it wrong in about 5000 spots in the compiler.  I've looked at the compiler sources (and the whole standard library for that matter), and yeah, a lot of it is really atrocious style-wise by almost any standard.  That's fine, it's a compiler after all; the source isn't supposed to be pretty.  However, that doesn't mean we have to treat is as the canonical way to use the language.

The point to the "functional only" infix restriction is to emphasize the fact that infix notation is really designed for operators, which are (as stated elsewhere) restricted to purely-functional applications.

Daniel
Kris Nuttycombe
Joined: 2009-01-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide

Another style suggestion: calling the apply() method on an object
should not result in mutation of the object. This is something that
Lift does and it always looks funny to me when something that looks
like function application acts as a setter. (sorry David!)

Kris

On Sun, Nov 15, 2009 at 2:03 PM, Daniel Spiewak wrote:
>> Commenting on a style guide would normally not be my thing, but since
>> martin did I'm afraid it'll end up gaining an aura of officialness,
>> so...  My #1 suggestion is to separate it into sections which are
>> uncontroversial (at least mostly) and sections where there is a
>> diversity of opinion.  That gives us at least a chance at a core of
>> consistency.  Without that separation it'll only be ignored.
>
> I'm not sure that sacrificing organizational structure for the sake of
> appeasing controversy is the best decision.  However, I can certainly
> understand the sentiment.  Perhaps an annotation of some sort for each
> controversial guideline?  That way, newcomers can easily see which styles
> are universally accepted, and which ones are open for debate.
>
>>
>> "Line Wrapping"
>>
>> val result = 1 + 2 + 3 + 4 + 5 + 6 +
>>      7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 +
>>      15 + 16 + 17 + 18 + 19 + 20
>>
>> This is needlessly error prone.  Do this:
>>
>> val result = (
>>      1 + 2 + 3 + 4 + 5 + 6 +
>>      7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 +
>>      15 + 16 + 17 + 18 + 19 + 20
>> )
>>
>> Now you can end your lines however you want.  You can't have multiple
>> statements in there, so if you forget a + it won't compile.
>
> Very true.  However, this treats parentheses like braces.  I would rather
> keep the rules for this distinct.  I usually treat parentheses like Lisp
> parens (with the closing paren on the same line as the last expression) and
> braces like Java-style braces.  This emphasizes the grammatical differences
> between the two.
>
>>
>> "Packages"
>>
>> It's _root_, not __root__.
>
> Yeah, typo.  I never use _root_, so it wasn't immediately on my mind.
>
>>
>> "Parentheses"
>>
>> I think this situation is hopeless and attempts to define when to use
>> empty parens vs. no parens can only have two results: 1) lots of
>> pointless arguing among people who have better things to do and 2) being
>> ignored by or unknown to 98% of scala programmers.
>
> As mentioned earlier, this is one on which I really think is worth holding
> the line.  Speaking from experience, strict adherence to this guideline
> makes a huge difference in the readability of your code.  Maybe we need more
> examples in this section to help clarify things.
>
>> "Declarations"
>>
>> "All class/object/trait members should be declared interleaved with
>> newlines."
>>
>> No.  There is no reason to make an exception for var and val but not
>> def, they're the same thing.  It's a matter of sensible grouping, like
>> when to start a new paragraph in prose.
>
> Ok, I'll buy that.  Maybe the guideline should be that trivial members (with
> expression bodies of less than 30 chars) can be smushed together when they
> represent a logical group, otherwise interleave.  The problem I'm trying to
> head off is when all members in a class/trait/object are unseparated.  I
> would rather over-separate than under, since the latter is far less readable
> than the former.
>
>>
>> "Function Values"
>>
>> "Of these styles, (1) and (4) are to be preferred at all times."
>>
>> ...except for all the times when one might prefer (2) or (3), which for
>> me is plenty often.  Especially, I avoid curly braces almost whenever
>> possible, with the notable exception of situationally using them in
>> if/then/else situations if it looks easy to misread the logic.
>
> I can sympathize with your wish to avoid curly-braces.  I try to do the
> same.  However, we have to face up to the fact that this is Scala, not
> Lisp.  Curly braces are literally an unavoidable aspect of the grammar.  It
> is best to use them in a consistent and visually distinct fashion.  Thus,
> expression grouping should be done using parentheses, while blocks should be
> denoted with braces.  This relates back into function literals.  Multi-line
> functions always use braces (they are forced to do so by the syntax), and so
> consistency would dictate that even single line literals do the same.
>
> This idiom also makes for a very nice visual cue that some sort of deferred
> execution is involved.  Consider the following:
>
> foo + bar
> xs.foldLeft(fooBar)(_ + _)
> baz + bin
>
> Vs the following:
>
> foo + bar
> xs.foldLeft(foobar) { _ + _ }
> baz + bin
>
> In the second form, the function literal is very clearly delineated.  It's
> pretty clear that the second parameter of the fold is something out of the
> ordinary.  When scanning code quickly, this can be a huge lifesaver.
>
> So, in summary: braces for function literals help a lot in terms of
> consistency and easy visual signaling.  They are an unavoidable part of the
> grammar, so it's quite futile to try to suppress them without a really good
> reason.
>
>>
>> "Omit braces if the ``case`` expression fits on a single line.
>> Otherwise, use curly braces for clarity (even though they are not
>> *required* by the parser)."
>>
>> Oh god no, not having to use braces on case statements is one of their
>> greatest features.
>
> This seems to be a controversial guideline.  My reasoning is mostly oriented
> around text editors, which (as I said) have a really hard time with this
> syntax.  It's not simply a matter of being able to handle Python.  Scala has
> a much more complicated syntax than Python.  Auto-indent for Python can be
> done exclusively with regular expressions, while Scala auto-indent is
> significantly more complex (believe me, I've tried).  As it turns out, Scala
> auto-indent is still regular...but only if we take a pass on the no-brace
> case syntax.  Auto-indent here requires some notion of context.  Emacs could
> do it, but not many other editors.
>
> Once we have better IDE support, maybe this guideline could be rescinded.  I
> suppose that the best solution for the moment would be to lay out both
> alternatives and explain that one is preferred ideally, but the other is
> more amenable to non-supernatural editors.
>
>>
>> "Comprehensions"
>>
>>    // wrong!
>>    for (x <- board.rows; y <- board.files)
>>      yield (x, y)
>>
>> I'm going with "right", although the yield goes on the first line.
>
> That's two votes against "my style", this is probably worthy of some more
> discussion in a separate thread.
>
>>
>> "Arity-1"
>>
>>    // wrong!
>>    javaList add item
>>
>> We got this one wrong in about 5000 spots in the compiler.  I'm going
>> with "right" again.
>
> Then you got it wrong in about 5000 spots in the compiler.  I've looked at
> the compiler sources (and the whole standard library for that matter), and
> yeah, a lot of it is really atrocious style-wise by almost any standard.
> That's fine, it's a compiler after all; the source isn't supposed to be
> pretty.  However, that doesn't mean we have to treat is as the canonical way
> to use the language.
>
> The point to the "functional only" infix restriction is to emphasize the
> fact that infix notation is really designed for operators, which are (as
> stated elsewhere) restricted to purely-functional applications.
>
> Daniel
>

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide
Another style suggestion: calling the apply() method on an object
should not result in mutation of the object. This is something that
Lift does and it always looks funny to me when something that looks
like function application acts as a setter. (sorry David!)

+1  It could also be argued that anything which defines apply() should also inherit from the corresponding FunctionN.  There are exceptions to this one, but for the most part I think it's valid.  If you don't think that you should inherit from FunctionN, then you probably shouldn't be defining apply.

Daniel
odersky
Joined: 2008-07-29,
User offline. Last seen 45 weeks 6 days ago.
Re: Proposed Style Guide

Hi Daniel, Paul,

On Sun, Nov 15, 2009 at 10:03 PM, Daniel Spiewak wrote:
>> Commenting on a style guide would normally not be my thing, but since
>> martin did I'm afraid it'll end up gaining an aura of officialness,
>> so...  My #1 suggestion is to separate it into sections which are
>> uncontroversial (at least mostly) and sections where there is a
>> diversity of opinion.  That gives us at least a chance at a core of
>> consistency.  Without that separation it'll only be ignored.
>
> I'm not sure that sacrificing organizational structure for the sake of
> appeasing controversy is the best decision.  However, I can certainly
> understand the sentiment.  Perhaps an annotation of some sort for each
> controversial guideline?  That way, newcomers can easily see which styles
> are universally accepted, and which ones are open for debate.

Yes, I think that's a good idea. At least as long as we have not
reached full convergence of opinions.

>> "Parentheses"
>>
>> I think this situation is hopeless and attempts to define when to use
>> empty parens vs. no parens can only have two results: 1) lots of
>> pointless arguing among people who have better things to do and 2) being
>> ignored by or unknown to 98% of scala programmers.
>
> As mentioned earlier, this is one on which I really think is worth holding
> the line.  Speaking from experience, strict adherence to this guideline
> makes a huge difference in the readability of your code.  Maybe we need more
> examples in this section to help clarify things.
>
I am with Daniel on this one. I think he gave a well-thought out set of rules.

>> "Omit braces if the ``case`` expression fits on a single line.
>> Otherwise, use curly braces for clarity (even though they are not
>> *required* by the parser)."
>>
>> Oh god no, not having to use braces on case statements is one of their
>> greatest features.
>
> This seems to be a controversial guideline.  My reasoning is mostly oriented
> around text editors, which (as I said) have a really hard time with this
> syntax.

I think that's not sufficient reason to bend your syntax. If somebody
would just fix the emacs mode, that would be great! Or else let's all
switch to Eclipse/IntelliJ/Neabeans.

> Once we have better IDE support, maybe this guideline could be rescinded.  I
> suppose that the best solution for the moment would be to lay out both
> alternatives and explain that one is preferred ideally, but the other is
> more amenable to non-supernatural editors.
>
Yes, if you formulate it like this, that's fine.

>> "Arity-1"
>>
>>    // wrong!
>>    javaList add item
>>
>> We got this one wrong in about 5000 spots in the compiler.  I'm going
>> with "right" again.
>
> Then you got it wrong in about 5000 spots in the compiler.  I've looked at
> the compiler sources (and the whole standard library for that matter), and
> yeah, a lot of it is really atrocious style-wise by almost any standard.
> That's fine, it's a compiler after all; the source isn't supposed to be
> pretty.  However, that doesn't mean we have to treat is as the canonical way
> to use the language.
>
> The point to the "functional only" infix restriction is to emphasize the
> fact that infix notation is really designed for operators, which are (as
> stated elsewhere) restricted to purely-functional applications.
>
I think that's too narrow. The infix notation makes also a nice
sentence form. For instance, if instead of

actor ! msg

you'd write

actor send msg

I think that would work just as well. Neither is a purely functional
operator. But both are clearer than

actor.send(msg)

Cheers

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide
I think that's too narrow.  The infix notation makes also a nice
sentence form. For instance, if instead of

actor ! msg

you'd write

actor send msg

I think that would work just as well. Neither is a purely functional
operator. But both are clearer than

actor.send(msg)

I actually prefer actor.send(msg) over `actor send msg`, but I can see the logic in the infix form.  Perhaps my "purely-functional" restriction was too artificial.  Is there a better, preferably general way of deciding which form to use?  I really, really want to make sure that `xs add foo` is treated as bad practice.

Incidentally, I consider the actor library to be an internal DSL (I even mention that in the guide) so the normal rules don't really apply.

Daniel
daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide

Regarding "Type Parameters (generics)" I think we should keep to the Java style.  Using [K,V] for a map is clearer than using [A,B].

Actually, I agree!  However, [A, B] is almost universal in the Scala community, mostly because of Scala's roots in typed functional languages like Haskell and SML.  In both of these languages, type parameters are solitary English alphabetic characters, named sequentially starting from A.  I used to use [K, V], but I trained myself out of it because it runs counter to the accepted Scala style.
 
In "Inference", "Just for the sake of safety, you should annotate all public methods in your class."  This should be stronger since code is read more than it is written.  Anything longer than a single line or two must be annotated with the return type in our code.  In my mind, almost the methods in the document should be annotated with a return type to make it clear that it is a requirement.

Sometimes, yes.  However, on many occaisions, I have found that annotating methods actually reduces readability.  In general, the case should dictate the style.  However, that's kinda hard to put in a guide.  :-)  I figure that people will annotate more or less with common sense and it's really only in signature-affecting members that it becomes a serious issue.

"Void" Methods.  We don't permit them in our code, we require the ":Unit = {" style.  It's too easy to try to write a short method with no type annotation and forget the = and now the method returns Unit.  There was a debate whether to remote this from the language, so it's use throughout the community isn't 100%.

Honestly, how often do you change a void method to one which returns a real value?  I actually can't recall ever doing that (not just in Scala, but in Java or any other language).  There's no need to optimize for a case which is so incredibly rare.
 
In "Comprehensions" for the non-yield case I think you should mention when there are many <- or = or if's, then you still want to put things onto separate lines

   for {
     x <- board.rows
     y <- board.files
     z <- foo.bar
     if z > 10
   } {
     printf("(%d, %d)", x, y)
   }

Agreed.  When there are lots of chained generators, it is good to use the multi-line syntax.  Still looks weird though.
 
"Higher-Order Functions" we use

   names.map(_.toUpperCase).filter(_.length > 5)

As mentioned earlier, I disagree pretty strongly with this syntax.  I have two main reasons.  First, map, filter and friends are logically just operators, so they belong in the infix position.  Second, I really believe that function values should always be delimited with curly braces.  This makes it visually explicit that the block in question is "not like the others".  It allows the prospective code reader to skim the line very quickly and immediately see that there are two function values without having to parse their contents.  With your style, the reader must visually "drill into" the contents of each parameter, looking for an underscore.  This gets very tiring, particularly on more complex expressions.
 
In "Multi-Unit Files" I'm pretty sure this will cause ant to recompile the source file every time because there is no exact match on the generates class file and the source file.  My compiles are already too long as it is, so I don't want to compile files I don't need to.

No, not really.  Maybe re-parse, but that has to happen anyway.  As far as I know, the Scala compiler attaches no significance to the name of the .scala file.

Daniel
ijuma
Joined: 2008-08-20,
User offline. Last seen 22 weeks 2 days ago.
Re: Proposed Style Guide

On Sun, 2009-11-15 at 15:37 -0600, Daniel Spiewak wrote:
>
> Regarding "Type Parameters (generics)" I think we should keep
> to the Java style. Using [K,V] for a map is clearer than
> using [A,B].
>
> Actually, I agree! However, [A, B] is almost universal in the Scala
> community, mostly because of Scala's roots in typed functional
> languages like Haskell and SML. In both of these languages, type
> parameters are solitary English alphabetic characters, named
> sequentially starting from A. I used to use [K, V], but I trained
> myself out of it because it runs counter to the accepted Scala style.

I wonder why you think that is so. I've seen many examples of other
styles and the new collections in particular don't follow what you call
"accepted style" at all.

Best,
Ismael

David Hall 4
Joined: 2009-08-21,
User offline. Last seen 42 years 45 weeks ago.
Re: Proposed Style Guide

On Sun, Nov 15, 2009 at 1:37 PM, Daniel Spiewak wrote:
>>
>> "Higher-Order Functions" we use
>>
>>    names.map(_.toUpperCase).filter(_.length > 5)
>
> As mentioned earlier, I disagree pretty strongly with this syntax.  I have
> two main reasons.  First, map, filter and friends are logically just
> operators, so they belong in the infix position.  Second, I really believe
> that function values should always be delimited with curly braces.  This
> makes it visually explicit that the block in question is "not like the
> others".  It allows the prospective code reader to skim the line very
> quickly and immediately see that there are two function values without
> having to parse their contents.  With your style, the reader must visually
> "drill into" the contents of each parameter, looking for an underscore.
> This gets very tiring, particularly on more complex expressions.
>

The curly/paren and dot/no-dot are separate debates. I've historically
sat on the "paren" side for short HoF calls, but I'm pretty won over
by your argument there.

dot/no-dot. I find myself alternating at the moment, but I've mostly
settled on using ".", and here's why:

names map { _.toUpperCase } foldLeft("") { _ + _}

looks reasonable, but won't compile. Nor will

names map { _.toUpperCase }.foldLeft("") { _ + _}

After running into this compile error (the latter version has a really
arcane error message!) countless times, I've decided the easiest way
to avoid it (besides always using reduceLeft) is to just use ".".

daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Proposed Style Guide
I haven't done a formal survey, but I can say that the majority of Scala code does seem to use the [A, B] convention.  As you said, the new collections library does not use this convention (though the old one does).  However, as I mentioned earlier, I'm using the standard library as a general hint toward "correct" style, but I'm actually giving it even less weight than one-off libraries by prominent community members.  It's hard to keep a consistent style across a library as large as Scala's.  However, individual coders can be consistent.  Furthermore, most of the Scala standard lib was developed before the community conventions evolved.

I would be willing to go with [K, V] instead of [A, B] (as I said, I do prefer that style).  However, this doesn't work in every case.  In Java, one almost never defines a type with more than two type parameters.  In Scala, that sort of thing is commonplace.  While [K, V] may be more readable for something like Map or List, but it fails to scale beyond two or three parameters.  That was the proverbial straw that broke the camel's back, at least it was for me.  I prefer consistent style which scales across all cases.

Daniel

On Sun, Nov 15, 2009 at 3:49 PM, Ismael Juma <mlists@juma.me.uk> wrote:
On Sun, 2009-11-15 at 15:37 -0600, Daniel Spiewak wrote:
>
>         Regarding "Type Parameters (generics)" I think we should keep
>         to the Java style.  Using [K,V] for a map is clearer than
>         using [A,B].
>
> Actually, I agree!  However, [A, B] is almost universal in the Scala
> community, mostly because of Scala's roots in typed functional
> languages like Haskell and SML.  In both of these languages, type
> parameters are solitary English alphabetic characters, named
> sequentially starting from A.  I used to use [K, V], but I trained
> myself out of it because it runs counter to the accepted Scala style.

I wonder why you think that is so. I've seen many examples of other
styles and the new collections in particular don't follow what you call
"accepted style" at all.

Best,
Ismael



Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland