Home

Coding Conventions for the JavaFX Language

Introduction

This wiki page provides a set of recommendations for how to format your JavaFX code - a coding
style or style guide for JavaFX.

Note that this is not an official document from Sun or the JavaFX team; I do work at Sun and
on JavaFX but there are many people more qualified than me to write with authority on this. I plan
to incorporate their feedback as soon as I get it!

This document is my attempt to

  1. Capture the de-facto conventions I am observing in the JavaFX platform libraries, and
  2. Provide own opinions in cases where there is enough variation that there isn't an obvious
    recommended style yet.

I googled looking for existing JavaFX coding conventions and the only thing I came across
was a blog entry with a number of recommendations that don't match the Sun coding style
(for example, it placed left braces on lines by themselves), so I thought it would be worthwhile
to start my own.

I chose to put this in a wiki page rather than in a blog, not just because I can imagine that it will
grow over time, but because I'm also certain that I will be convinced to change this content
over time as we discuss these topics and as the language evolves. Finally, a wiki will allow
collaboration.

This first revision attempts to be brief rather than pedantic.

Default: Stay Consistent with Java

This document only records issues that are specific to JavaFX. For everything else, follow
the general Java code convention. This means:

  • Use a 4-space indent
  • Use CamelCase for class names, camelCase for function, method, property and variable names, and
    UNDERLINED_CAPS for constants (this does not include local def's)
  • No spaces directly inside parentheses, or before semicolons
  • Spaces around operators
  • Left brace, {, should never be on its own line. For multiline blocks, } should always
    be on its own line and line up with the beginning of the block.
  • Always use { } around if clauses - don't write code like "if (foo) bar()".
  • Wildcard imports are okay.

File organization

Place private, static constants used by a class at the top of the file. Place everything else
(private utility methods) after the class.

Place public (public, public-init, public-read) properties at the top of the class, followed
by protected, package and finally private properties.

Rather than organizing constructor code into a single big init {} block, use multiple init blocks
if necessary to distribute the code near their logical place. For example, if you are initializing
a map, place the init block next to the declaration of the map.

Type Definitions

There should be no space before a type declaration and one space after it. This is true both
for variable declarations and for parameters. In other words:

var yes: Number;
var no:Number;
var no : Number;
function foo(yes: Boolean, no : Boolean, no:Boolean) { ... }

All non-overriding functions should explicitly state their return type rather
than rely on JavaFX' ability to infer them automatically.

public function foo(): Number { 1 }   // Yes
public function foo(): Integer { 1 }  // Yes
public function foo(): { 1 }          // No

public function foo(): Void { bar() } // Yes

Object Literals

Just as for type definitions, the property name and the property value should
have a single space after the colon.

There should not be any semicolons at the end of a line, including the final closing }.

// Yes
Insets {
    left: 0
    right: 0
    top: 0
    right: 0
}

// No
Insets {
    left:0     // Missing space after :
    right : 0  // Extra space before :
    top: 0;    // Extra semicolon
};             // Extra semicolon

For single-line definition of objects

  • Multiple properties should be separated by a comma to enhance readability.
    Semicolons are okay too but I think commas are preferable.
  • There should not be a semicolon before (or after) the closing }
  • There should be a single space inside the left and right braces
Point2D { x: 100, y: 100 }

// No:
Point2D {x: 100, y: 100}    // Missing spaces inside {}
Point2D { x: 100 y: 100 }   // Missing comma separator
Point2D { x:100, y:100 }    // Missing space after :
Point2D { x: 100, y: 100; } // Extra semicolon before }
Point2D { x: 100, y: 100 }; // Extra semicolon after {

When an object literal is defined in indented code, the whole object literal should
be indented such that the final closing } lines up directly with the beginning of
the object literal.

When an object is specified on the right hand side of an assignment, or as a
parameter to a function, or in an insert into expression, or any other context where
the object literal is not the first non-whitespace character on a line, there are
acceptable ways to indent the code block:

// Alternative 1: Indent whole literal to rhs indentation
def shapeInsets = Insets {
                      left: 0
                      right: 0
                      top: 0
                      bottom: 0
                  }

// Alternative 2: Indent to the lhs indentation                 
def shapeInsets2 = Insets {
    left: 0
    right: 0
    top: 0
    bottom: 0
}

// Alternative 3: Indent one level on the next line.
def shapeInsets3 = 
    Insets {
        left: 0
        right: 0
        top: 0
        bottom: 0
    }

I have recently started using form #3 which I think works best in most scenarios.
The problem with #1 is that it doesn't work well in more deeply nested code,
and it doesn't work well when block starts at a character other than a multiple of
the indentation size. The problem with #2 is that it's harder to spot visually
what is created since the class being instantiated doesn't line up with the final }.

For sequences, add a whole indentation level for the sequence begin/end markers ( [ ] ).
Note also that like {, the [ should not appear on its own line:

Group {
    content: [
        Button {},
        Button {}
    ]
}

// No
Group 
{                    // Should not be on its own line
    content: 
    [                // Should not be on its own line
        Button {},
        Button {}
    ]
}

Nested data structures should be declared in place. You may find that you need
to reference one part of the nested data structure from another. But rather than
pulling those parts out and defining them first, you can define variables for
these and assign them as part of the object hierarchy:

var scene: Scene;
Stage {
    width: 1000
    height: 1000
    scene: scene = Scene { // We assign to variable as part of declaration
        content : [
            ListView {
                items: items
                width: bind scene.width
                height: bind scene.height
            }
        ]
    }
}

For large data structures you don't even need to define the variables up front;
you can do it within the declaration:

Group {
    var button: Button; // Button reference defined inside Group literal
    content: [
        button = Button { text: "Hello" }
    ]
    onMouseEntered: function(e) {
        button.effect = DropShadow{};
    }
}

Function Returns

The last statement of the function should evaluate to the return of the function.
Do not use the "return" keyword. And add a blank line before the last statement
(unless it's the only statement of the function).

// Yes - just specify an object literal
function create(args): Foo {
    Foo {
        foo: args.foo
        bar: args.bar
    }
}

function indexOf(str: String): Number {
    ...code...

    -1
}

public override function toString() {
    "{allowed}, but usually in {common}"
}

public bound function getIconPaint():Paint {
    def brightness = UtilsFX.calculateBrightness(BASE_COLOR);

    if(brightness>=0.5 and brightness<0.7) then {
        ICON_COLOR_DARK
    } else if (brightness>=0.5) then {
        ICON_COLOR
    }  else {
        ICON_COLOR_LIGHT
    }
}

Note also that there is no semicolon here – the last statement is "-1" or "null" etc, not "null;".

Properties

All public properties should be documented.

Try to minimize access privileges; just because other classes need to see the value
of a property doesn't mean the property has to be public. Use "public-read" on these
variables. Even if they need to be written outside the class, note that you can
tack a second access modifier on it for writes, so you can for example have "public-read protected"
which means everybody can read and subclasses can write this property.

Similarly, use public-init as much as possible on all properties that are only settable at
construction time.

Variables

Prefer "def" over "var" as much as possible. Unlike Java's "final" which was extra typing, def lets
you create a final variable.

def newFile = new File(file, "NewFolder");
newFile.mkdir();

Constants created as a def inside a method can be formatted like other variables - in other words,
like newFile above instead of NEW_FILE.

Null Checks

JavaFX performs null checks for you in a form of short-circuit evaluation, so there is no need to
sprinkle them all over your code.

// Bad
if (foo != null && foo.bar != null) {
    x = foo.bar.baz;
}
// Good
x = foo.bar.baz;

Note in particular that nulls are ignored when it creates sequences.

Thus, rather than something like this:

if (header != null) {
    content = [ background, footer, header ]
} else {
    content = [ background, footer ]
}

you should simply write this:

content = [ background, footer, header ]

These two code snippets are equivalent but the second style is clearly preferable.

Ternary Expressions

JavaFX doesn't have the ?: operator from Java, but it lets you use if-else as expressions.
Therefore, you can do this:

var foo = if (bar) 3 else 4

Code should be using the above construct, preferably without extra { }'s and "then", to keep things
simple, instead of more convoluted logic to handle conditional initialization of variables,
objects, or function arguments.

Similarly, you should use generator expressions instead of for loops with sequence inserts.

// BAD
var seq: String[] = [];
for (name in names) {
    insert name into seq;
}

// GOOD
seq = for (name in names) name

The "override" modifier

The "override" keyword should appear after the access modifier, it should not be before it as the @Override annotation often is in Java:

public override function yes() { } // YES
override public function no() { } // NO

Discussion and Justification:

(This is where I provide more justification or discussion around recommendations listed above.)

Type Declarations

There is a lot of variation in how type declarations, and object literal key value pairs, are formatted:

var foo: Integer;  // 1
var bar : Integer; // 2
var baz:Integer;   // 3

In this style guide I have recommended the first approach. This is a bit arbitrary, but my reasoning is as follows:

  • This seems to be the convention in Scala, which also defines types after variables, and Scala's formatting seems to
    continue the general style of Java so mixing and matching conventions seems like a good idea.
  • Using no spaces (as in #3 above) is in my opinion less readable since the whole item appears as a single unit

Specify Return Types

At first I relied on the language support for automatically figuring out return types. It's really nice when you're
just writing functions that you're using locally. But I ran into problems once I started writing more code,
and started overriding functions in my class hierarchy. For example, in many cases I have a function which in
my mind is a "void" function - because I don't care about the return value and I didn't explicitly return anything.
However, if the last expression evaluates to a number, your function signature now returns a number, and if you in
a subclass try to override this method with another "void" function, you get an error if you don't also happen
to have a last expression in your function that evaluates to the same type! This also doesn't just happen with void;
in other cases the type inference may conclude that the return type should be "Integer", whereas in your mind you
intended for the function to return a "Number", and if your subclass now tries to return a Number you get either
a compilation or a truncation error.

Override Modifier

The recommendation to put override after public is based on current usage. A quick search of the JavaFX SDK codebase
showed that 80% of all combinations of public and override are of the public override form.


Version 1, November 8th 2009.
Tor Norbye, tor.norbye@sun.com
http://blogs.sun.com/tor

Labels

javafx javafx Delete
codeconventions codeconventions Delete
styleguide styleguide Delete
formatting formatting Delete
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. Nov 09

    dnarmitage says:

    Excellent piece of work, much needed, thanks very much Tor. My feedback - first...

    Excellent piece of work, much needed, thanks very much Tor.

    My feedback - first the non-contentious one:

    Ternary Expressions

    JavaFX doesn't have the ?: operator from Java, but it lets you use if-else as expressions.
    Therefore, you can do this:

    {{var foo = if (bar) 3 else 4}}

    I believe is considerably better as:

    {{var foo = if (bar) then 3 else 4}}

    with the 'then' clearly defining what is going on.

    Braces generally

    I would very much like someone to explain why the brace standard of Java is a clear way of presenting code, as I personally believe it is extremely unhelpful and possibly simply a legacy habit that should be broken:

    • Left brace, {, should never be on its own line. For multiline blocks, } should always be on its own line and line up with the beginning of the block.

    This should, IMHO, be:

    • Left brace, {, should never be on its own line. For multiline blocks, } should always be on its own line and line up with the beginning of the block statements.

    e.g.:

    var scene: Scene;
        Stage {
            width: 1000
            height: 1000
            scene: scene = Scene { // We assign to variable as part of declaration
                content : [
                    ListView {
                        items: items
                        width: bind scene.width
                        height: bind scene.height
                        },
                    ListView {
                        items: items2
                        width: bind scene.width
                        height: bind scene.height
                        }
                    ]
                }
            }

    (notice I include ] in this as well) and:

    Group {
        var button: Button; // Button reference defined inside Group literal
        content: [
            button = Button { text: "Hello" }
            ]
        onMouseEntered: function(e) { button.effect = DropShadow{}; }
        }

    I believe that placing the end Brace (or ] ) in line with the statements it encloses makes a far more effective visual block than the current Java norm, especially with larger and more complex blocks of code.

    The initial indent clearly shows the start of a block and the brace followed by code now de-indented (?) clearly picks out the end.  

    I am happy to be convinced otherwise when someone can demonstrably show me how the existing Java style is more readable, or even as readable (other than 'thats how we always do it')!

    Thanks again, I think this is a much needed discussion. (and this wiki editor is ... peculiarly difficult to use for some reason)

    David

    1. Nov 09

      dnarmitage says:

      Well, I'm not normally known for my inability to use systems, but your Wiki edit...

      Well, I'm not normally known for my inability to use systems, but your Wiki editor for replying is currently beating me hands down, no matter what I try!

      Edit - Forced it into submission - what a pain - and wasn't an IE issue as tried Firefox as well - obviously easier when you know it's peculiarities

    2. Nov 09

      tnorbye says:

      Hi David, Thanks for your feedback! Regarding the ternary operator, yeah, I don...

      Hi David,
      Thanks for your feedback!

      Regarding the ternary operator, yeah, I don't mind including the then. The main thing I wanted to get at is to keep these expressions simple (in the same spirit as the ternary operator) so that they don't take up a lot of space and push towards the right hand margin. In particular, don't include the { and } delimiters, since that just adds clutter - whereas in all other cases they should be included in if statements. And even for a single-line if they should be included if you do anything other than return simple values (but this is luckily what you usually do with the if-elses used as expressions). I didn't think then added much in the way of readability (e.g. in the ?: operator there is no then and I can read it just fine) but if you think it adds something by all means include it!

      Regarding braces:
      The strongest reason I can give, which isn't very satisfying, is that coding conventions is not just about the best theoretical argument for one style over another, it's also about ensuring consistency. One could fairly easily argue for the ruby_naming_convention instead of the javaNamingConvention, or vice versa, but at this point, with one style in widespread use, the alternative would have to be provably much MUCH better for the whole world to switch. Some of these things are arbitrary but just feels right because we've been exposed to them for so long. So JavaFX' bracing style is just following territory established by Java, which in turned picked a style used by a segment of the C++ population.

      Having said all that, I don't think the Java style is something I like purely because I've lived with it for so long. For me it helps with visual scanning – when I look at a for statement the closing } is clearly associated with the for keyword 3 lines further up. With your proposed style it looks more like Python code to me with the } being a bit superfluous, probably only needed by the parser and not really used for visual scanning. It also seems like it would be difficult to apply that style to an if/else statement - would the } else { also be lined up with the indented block instead of the statement marker?

      In any case, I think the bracing policy is so thoroughly ingrained in our coding culture that it would be impossible to change at this point... Not only the right-brace policy consistent in Java (there is some variation in whether people put the left brace on its own line or not, but the right brace is pretty universally lined up with the left one of the statement open) - but it's also done that way in Scala and Groovy, etc.

      Regarding the wiki editor – sorry about that, but there's not much I can do about it - this is as far as I know a standard Confluence installation and (luckily) I don't do any administration of it... One thing that helped me when using it is clicking on the Preview tab - it lets you see how Confluence formats your wiki entry.

      1. Nov 09

        dnarmitage says:

        Tor, Thanks for response. In respect of the 'then', like lots of words in Engl...

        Tor,

        Thanks for response.

        In respect of the 'then', like lots of words in English, not required to read it. but I think it sure as hell helps (all IMHO of course )

        Being a practical guy I never believed there was a snowflakes chance in hell of getting a braces change, but I would love to see what an ergonomics academic (or whatever they are) would say about them. Once someone kindly provides formatting for javafx in netbeans I will have to set up 2 formatters, one for me, and one for when I make anything public!

        On the else statements, I generally use a half indent which works realy well. The style also helps a lot with try catch blocks (again, IMHO).

        With respect to else, I do feel there should be some cleaner way of presenting else if chains, even if it means more lines, TBH I dont really like 'else' on same line as followinhg 'if' and tend to block them up.

        An additional item is nested data structures - I really do find it a lot cleaner (for me again) to create the individual building blocks as variables and incrementally build them into the final scene. It isn't so bad when there is a small number of data structures, but when building a reasonably complex one, the nesting gets way out of all sensibility.

        As ever, all IMHO

        David

  2. Nov 10

    SEMorris says:

    As far as type declarations go, I think for Actionscript Adobe favour var baz:In...

    As far as type declarations go, I think for Actionscript Adobe favour var baz:Integer (no space) as their convention. Given the intended audience for JavaFX, perhaps it might be better to look towards JavaScript and Actionscript first for conventions, rather than Scala etc (..?)

Sign up or Log in to add a comment or watch this page.


The individuals who post here are part of the extended Sun Microsystems community and they might not be employed or in any way formally affiliated with Sun Microsystems. The opinions expressed here are their own, are not necessarily reviewed in advance by anyone but the individual authors, and neither Sun nor any other party necessarily agrees with them.

© 2010, Oracle Corporation and/or its affiliates
Powered by Atlassian Confluence
Oracle Social Media Participation Policy Privacy Policy Terms of Use Trademarks Site Map Employment Investor Relations Contact