Skip to content

Project Style Guide

Luiz Guilherme Silva edited this page Mar 31, 2017 · 18 revisions

Version History

Version Policy

Version Date Description Responsable
0.1 22/03/2017 Document creation and adaptation Luiz Guilherme
0.2 22/03/2017 Add React Topics Gustavo Braz
0.3 23/03/2017 Add Some HTML/CSS topics Luiz Guilherme
1.0 23/03/2017 First stable version of document Luiz Guilherme
1.1 31/03/2017 Remove 'always use .jsx' rule for React Components Luiz Guilherme
  • This is an adapted guide based on the coding standard used by Airbnb and Google Style Guide. It's utilization was adapted for utilization in the project found here and here. This guide can be used openly, even if is this version, an adaptation of the project cited above.

  • The reading and consult of this guide can be somewhat confusing for users that are not acquainted with Java, Javascript, ReactJS, JSX and HTML/CSS. It is recommended that you study them before utilizing this guide.

  • It's also recommended the utilization of the Eclipse IDE for Java development during the process of development and for ReactJS development it's recommended a text editor like Atom, Sublime or Webstorm because it is more intuitive, easy to use and well documented. As a web browser, we recommend Google Chrome.

  • If you have any doubts in relation of a code pattern, utilize the search function from your browser(CTRL+F on Google Chrome) before start coding!

  • Alterations can be made without previous warning.

Index

  1. Basic Rules
    1. Naming
    2. Formatting
    3. Comments
    4. Programming Practices
  2. Java Style Guide
    1. Java Annotations
    2. Javadoc
    3. Instructions
    4. Declarations
  3. JavaScript Style Guide
    1. Instructions
    2. Declarations
    3. Policies
  4. ReactJS Style Guide
    1. Declarations
    2. Ordering
    3. Props
    4. References
  5. HTML and CSS Style Guide
    1. HTML Style Rules
    2. CSS Style Rules

Basic Rules

Naming

React/JSX

  • Only include one React component per file.

  • However, multiple Stateless, or Pure, Components are allowed per file.

  • Always use JSX syntax.

  • Do not use React.createElement unless you're initializing the app from a file that is not JSX.

  • Extensions: Use preferentially .jsx extension for React components, but .js will be accepted too.

  • Filename: Use PascalCase for filenames. E.g., ReservationCard.jsx.

  • Reference Naming: Use PascalCase for React components and camelCase for their instances. eslint: react/jsx-pascal-case

    // bad
    import reservationCard from './ReservationCard';
    
    // good
    import ReservationCard from './ReservationCard';
    
    // bad
    const ReservationItem = <ReservationCard />;
    
    // good
    const reservationItem = <ReservationCard />;
  • Component Naming: Use the filename as the component name. For example, ReservationCard.jsx should have a reference name of ReservationCard. However, for root components of a directory, use index.jsx as the filename and use the directory name as the component name:

    // bad
    import Footer from './Footer/Footer';
    
    // bad
    import Footer from './Footer/index';
    
    // good
    import Footer from './Footer';
  • Higher-order Component Naming: Use a composite of the higher-order component's name and the passed-in component's name as the displayName on the generated component. For example, the higher-order component withFoo(), when passed a component Bar should produce a component with a displayName of withFoo(Bar). Why? A component's displayName may be used by developer tools or in error messages, and having a value that clearly expresses this relationship helps people understand what is happening.

    // bad
    export default function withFoo(WrappedComponent) {
      return function WithFoo(props) {
        return <WrappedComponent {...props} foo />;
      }
    }
    
    // good
    export default function withFoo(WrappedComponent) {
      function WithFoo(props) {
        return <WrappedComponent {...props} foo />;
      }
    
      const wrappedComponentName = WrappedComponent.displayName
        || WrappedComponent.name
        || 'Component';
    
      WithFoo.displayName = `withFoo(${wrappedComponentName})`;
      return WithFoo;
    }
  • Props Naming: Avoid using DOM component prop names for different purposes. Why? People expect props like style and className to mean one specific thing. Varying this API for a subset of your app makes the code less readable and less maintainable, and may cause bugs.

    // bad
    <MyComponent style="fancy" />
    
    // good
    <MyComponent variant="fancy" />

Java

  • Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example, com.example.deepspace, not com.example.deepSpace or com.example.deep_space.
  • Class names are written in UpperCamelCase.
  • Class names are typically nouns or noun phrases. For example, Character or ImmutableList. Interface names may also be nouns or noun phrases (for example, List), but may sometimes be adjectives or adjective phrases instead (for example, Readable).
  • There are no specific rules or even well-established conventions for naming annotation types.
  • Test classes are named starting with the name of the class they are testing, and ending with Test. For example, HashTest or HashIntegrationTest.
  • Method names are written in lowerCamelCase.
  • Method names are typically verbs or verb phrases. For example, sendMessage or stop.
  • Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores. But what is a constant, exactly?

HTML

  • Use a new line for every block, list, or table element, and indent every such child element.

  • Independent of the styling of an element (as CSS allows elements to assume a different role per display property), put every block, list, or table element on a new line.

  • Also, indent them if they are child elements of a block, list, or table element.

    <blockquote>
      <p><em>Space</em>, the final frontier.</p>
    </blockquote>
    <ul>
      <li>Moe
      <li>Larry
      <li>Curly
    </ul>
    <table>
      <thead>
        <tr>
          <th scope="col">Income
          <th scope="col">Taxes
      <tbody>
        <tr>
          <td>$ 5.00
          <td>$ 4.50
    </table>
  • When quoting attributes values, use double quotation marks.

  • Use double ("") rather than single quotation marks ('') around attribute values.

    <!-- bad -->
    <a class='maia-button maia-button-secondary'>Sign in</a>
    <!-- good -->
    <a class="maia-button maia-button-secondary">Sign in</a>

CSS

  • Prefer dashes over camelCasing in CSS class names
  • Do not use ID selectors at CSS classes
  • When using multiple selectors in a rule declaration, give each selector its own line at CSS classes
  • In CSS classes properties:
    • Put a space after, but not before, the : character.
    • Put a space before the opening brace { in rule declarations
    • Put closing braces } of rule declarations on a new line
    • Put blank lines between rule declarations

Formatting

  • Use soft-tabs with a two space indent. Spaces are the only way to guarantee code renders the same in any person’s environment.
  • Avoid lines with more than 80 characters, provided they are not treated well handled by a lot of terminals and tools.
  • When the expression does not fit in a single line, break her accordingly to this general principles;
    • Break after a comma.
    • Break after an operator.
    • Prefer lines of higher level than the ones with lower level.
    • Align the new line with the start of the expression in the same level as the previous line.

Comments

  • Prefer line comments to block comments.

  • Prefer comments on their own line. Avoid end-of-line comments.

  • Write detailed comments for code that isn't self-documenting:

    • Uses of z-index on CSS Classes
    • Compatibility or browser-specific hacks
  • The utilization of comments in Java is a complex subject to deal with. IT IS RECOMMENDED, read again, IT IS RECOMMENDED, the utilization of a implementation comment in each line break and the same must be preceded of a blank space. However, as we know the difficulty of such implementation it's utilization is not obligatory. Just utilize the patterns below, remember to use a comma at the end of a comment.

    /*
    * This is            // this             /* Or it can be
    * cool.           // also is.          * like this. */
    */

Programming Practices

  • Not using any programming practice until now

Java Style Guide

Java Annotations

  • Use alphabetical order to list two or more annotation.
  • Annotations don't fit on one line in some cases.
  • What happens in that annotations keep adding up in our project, responsibility after responsibility. Having annotations for really different concerns on the same line becomes messy.
  • Also, some annotation can become really big, and be multi-liners on their own.

Javadoc

  • Until we apply some Programming Practice, we are not using Javadoc system.

Instructions

Simple

  • Each line must contain just one declaration.
    argv++;         /*ideal*/
    argc--;         /*ideal*/
    argv++; argc--; /*bad*/

Composed

  • Composed instructions are instructions that contain a list of instructions inside keys {instructions}. Look the following sections for examples.

  • The Closed declarations must contain one more indentation level than the composed instruction. The opening key must be at the end of the line where the composed instruction starts. The closing key must start in a line and must be indented at the start of a composed instruction. The keys are utilized around of all the instructions, even the simple instructions, when they are a part of the control structure, as a if-else or for instructions. This make it easier to add more instructions without, accidentally, introducing error when you forget to add the keys.

Return

  • A instruction with a return value must not utilize parenthesis,unless they, somehow, have the most obvious return value. Example:

     return;
     
     return myDisk.size();
     
     /* About ternary operators see the following section. */
     return (size ? size : defaultSize);

If, If-Else, If Else-If Else

  • The instructions class if-else must possess the following form:

    if (condition) {
        statements;
    } else {
        statements;
    }
    
    if (condition) {
        statements;
    } else if (condition) {
        statements;
    } else {
        statements;
    }
  • Note: the declaration if always utilize keys, {}. Avoid the following form:

 /* You must not do this. It's easier to comprehend if you utilize the keys */
  if (condition)
      statement;
  • Also do not utilize ternary operators. Prefer utilizing a simple operator, therefore if - else.
    /*bad*/
    return (size ? size : defaultSize);
    
    /*ideal*/
    if (size) {
      return size;
    } else {
      return defaultSize;
    }

For

  • A "for" declaration must follow this form:

    for (initialization; condition ; update) {
         instructions;
    }
  • An empty instruction (one that every work is made in the initialization, condition, and update of the clauses) must possess the following form:

    for (initialization; condition; update);
  • When utilizing a comma in the initialization clause or in the update of a instruction,avoid the complexity of the use of more than three variables. If necessary, use separated instructions before the loop (for the initialization clause) or at the end of the loop (for the update clause).

  • Use a space when booting or making comparisons and etc.

  • Utilize a space when you are going to initialize or make comparisons. Example:

    for (int i = 0; i < 10; i += 2) {
      /*instructions*/
    }

While

  • A "while" instruction must possess the following form:
    while (condition) {
        instructions;
    }  
  • An empty while must possess the following form:
    while (condition);

Do-While

  • A "do-while" must possess the following form:
    do {
        instructions;
    } while (condition);        

Switch

  • A "switch" declaration must possess the following form:

    switch (condition) {
        case ABC:
            statements;
            /* Enters the case */
        
        case DEF:
            statements;
            break;
        
        case XYZ:
            statements;
            break;
        
        default:
            statements;
            break;
    }
    
  • Each time a case fails (do not include a break type instruction),add a comment where the break would follow normally. This is evident in the previous code example with the Falls through in the comments.

  • Each instruction of the switch type must include a "default" case. The pause in the pattern case is redundant, however this prevents the Fall through error if another case is add after.

Arithmetic expressions

  • It's followed and example of break in a arithmetic expression. Example:
```java
float longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6;
```

Declarations

  • When a long fall-back of methods happens, change the lines utilizing two levels of indentation. Example:

    /* Indent two levels to avoid the deep fall-backs. */
    private static String synchronized horkingLongMethodName(int anArg,
    Object anotherArg, String yetAnotherArg,
    Object andStillAnother) {
        /* The code goes on */
    }

Javascript Style Guide

Instructions

Strings

  • Use single quotes '' for strings instead of double quotes ""

    // bad
    var name = "Techa Ivete";
    
    var fullName = "Techa " + this.lastName;
    
    // good
    var name = 'Techa Ivete';
    
    var fullName = 'Techa ' + this.lastName;

Variables

  • Declarations for var as follows:

    // bad
    var a = 1;
    var b = 2;
    var c = 'string';
    
    // good
    var a = 1,
     b = 2,
     c = 'string';

Semicolons

  • Use semicolons ;

    // bad
    function() {
      return 'TechVet'
    }
    
    // good
    function() {
      return 'Techvet';
    }

Commas

  • Don't use leading commas.

    // bad
    var TechVet
      , premium
      , business;
    
    // good
    var TechVet,
        premium,
        business;
    
    // bad
    var product = {
        name: 'TechVet'
      , type: 'App'
      , category: 'Productivity'
    };
    
    // good
    var product = {
      name: 'TechVet',
      type: 'App',
      category: 'Productivity'
    };
    
    // good
    function() {
      return 'TechVet';
    }

Naming conventions

  • Use descriptive naming. Avoid single letter names.

    // bad
    function t() {
      // do something...
    }
    
    // good
    function test() {
      // do something...
    }
  • Use camelCase when naming objects, functions, and instances.

    // bad
    var OBject = {};
    var heres_an_object = {};
    function c() {}
    var u = new user({
      name: 'TechVet';
    });
    
    // good
    var thisIsMyObject = {};
    function thisIsMyFunction() {}
    var user = new User({
      name: 'TechVet';
    });

Declaring Strict Mode

  • Declare 'use strict' in all your JavaScript files.

Conditional Expressions

  • Use === and !==
      // bad
      var name = 'Techa Ivete';
      if(name == 'Techa Ivete'){}
    
      if(name != 'Techa Ivete'){}
    
      // good
      var name = 'Techa Ivete';
      if(name === 'Techa Ivete'){}
    
      if(name !== 'Techa Ivete'){}

Blocks

  • Use braces when there are multi-line blocks.
      // bad
      if (name)
      return false;
    
      // good
      if (name) return false;
    
      // bad
      if (name){return false};
    
      // good
      if (name){
        return false;
      }
      ```

Declarations

Types

  • Primitives: When you access a primitive type you work directly on its value

    • string
    • number
    • boolean
    • null
    • undefined
    var foo = 1,
        bar = foo;
    
    bar = 9;
    
    console.log(foo, bar); // => 1, 9
  • Complex: When you access a complex type you work on a reference to its value

    • object
    • array
    • function
    var foo = [1, 2],
        bar = foo;
    
    bar[0] = 9;
    
    console.log(foo[0], bar[0]); // => 9, 9

Objects

  • Use the literal syntax for object creation.

    // bad
    var item = new Object();
    
    // good
    var item = {};
  • Don't use reserved words as keys. It won't work in IE8.

    // bad
    var superman = {
      default: { clark: 'kent' },
      private: true
    };
    
    // good
    var superman = {
      defaults: { clark: 'kent' },
      hidden: true
    };
  • Use readable synonyms in place of reserved words.

    // bad
    var superman = {
      class: 'alien'
    };
    
    // bad
    var superman = {
      klass: 'alien'
    };
    
    // good
    var superman = {
      type: 'alien'
    };

Arrays

  • Use the literal syntax for array creation

    // bad
    var items = new Array();
    
    // good
    var items = [];
  • If you don't know array length use Array#push.

    var someStack = [];
    
    
    // bad
    someStack[someStack.length] = 'abracadabra';
    
    // good
    someStack.push('abracadabra');
  • When you need to copy an array use Array#slice.

    var len = items.length,
        itemsCopy = [],
        i;
    
    // bad
    for (i = 0; i < len; i++) {
      itemsCopy[i] = items[i];
    }
    
    // good
    itemsCopy = items.slice();
  • To convert an array-like object to an array, use Array#slice.

    function trigger() {
      var args = Array.prototype.slice.call(arguments);
      ...
    }

Properties

  • Use dot notation when accessing properties.

    var TechVet = {
      elephant: true,
      remember: true
    };
    
    // bad
    var isElephant = TechVet['elephant'];
    
    // good
    var isElephant = TechVet.elephant;
  • Use subscript notation [] when accessing properties with a variable.

    var TechVet = {
      elephant: true,
      remember: true
    };
    
    function getProp(prop) {
      return TechVet[prop];
    }
    
    var isElephant = getProp('elephant');

Accessors

  • Accessor functions for properties are not required

  • If you do make accessor functions use getVal() and setVal('hello')

    // bad
    elephant.age();
    
    // good
    elephant.getAge();
    
    // bad
    elephant.age(25);
    
    // good
    elephant.setAge(25);
  • If the property is a boolean, use isVal() or hasVal()

    // bad
    if (!elephant.age()) {
      return false;
    }
    
    // good
    if (!elephant.hasAge()) {
      return false;
    }

Policies

  • Until we apply some programming practices, none policy will be determined.

ReactJS Style Guide

Declarations

  • Do not use displayName for naming components. Instead, name the component by reference.
    // bad
    export default React.createClass({
      displayName: 'ReservationCard',
      // stuff goes here
    });
    
    // good
    export default class ReservationCard extends React.Component {
    }

Ordering

  • Ordering for class extends React.Component:
  1. optional static methods
  2. constructor
  3. getChildContext
  4. componentWillMount
  5. componentDidMount
  6. componentWillReceiveProps
  7. shouldComponentUpdate
  8. componentWillUpdate
  9. componentDidUpdate
  10. componentWillUnmount
  11. clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()
  12. getter methods for render like getSelectReason() or getFooterContent()
  13. optional render methods like renderNavigation() or renderProfilePicture()
  14. render
  • How to define propTypes, defaultProps, contextTypes, etc...
    import React, { PropTypes } from 'react';
    
    const propTypes = {
      id: PropTypes.number.isRequired,
      url: PropTypes.string.isRequired,
      text: PropTypes.string,
    };
    
    const defaultProps = {
      text: 'Hello World',
    };
    
    class Link extends React.Component {
      static methodsAreOk() {
        return true;
      }
    
      render() {
        return <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a>
      }
    }
    
    Link.propTypes = propTypes;
    Link.defaultProps = defaultProps;
    
    export default Link;
  1. displayName
  2. propTypes
  3. contextTypes
  4. childContextTypes
  5. mixins
  6. statics
  7. defaultProps
  8. getDefaultProps
  9. getInitialState
  10. getChildContext
  11. componentWillMount
  12. componentDidMount
  13. componentWillReceiveProps
  14. shouldComponentUpdate
  15. componentWillUpdate
  16. componentDidUpdate
  17. componentWillUnmount
  18. clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()
  19. getter methods for render like getSelectReason() or getFooterContent()
  20. optional render methods like renderNavigation() or renderProfilePicture()
  21. render

Props

  • Always use camelCase for prop names.

    // bad
    <Foo
      UserName="hello"
      phone_number={12345678}
    />
    
    // good
    <Foo
      userName="hello"
      phoneNumber={12345678}
    />
  • Omit the value of the prop when it is explicitly true.

    // bad
    <Foo
      hidden={true}
    />
    
    // good
    <Foo
      hidden
    />
  • Always include an alt prop on tags. If the image is presentational, alt can be an empty string or the must have role="presentation". eslint: jsx-a11y/img-has-alt

    // bad
    <img src="hello.jpg" />
    
    // good
    <img src="hello.jpg" alt="Me waving hello" />
    
    // good
    <img src="hello.jpg" alt="" />
    
    // good
    <img src="hello.jpg" role="presentation" />
  • Do not use words like "image", "photo", or "picture" in alt props. Why? Screenreaders already announce img elements as images, so there is no need to include this information in the alt text.

    // bad
    <img src="hello.jpg" alt="Picture of me waving hello" />
    
    // good
    <img src="hello.jpg" alt="Me waving hello" />
  • Do not use accessKey on elements. Why? Inconsistencies between keyboard shortcuts and keyboard commands used by people using screenreaders and keyboards complicate accessibility.

    // bad
    <div accessKey="h" />
    
    // good
    <div />
  • Avoid using an array index as key prop, prefer a unique ID.

    // bad
    {todos.map((todo, index) =>
      <Todo
        {...todo}
        key={index}
      />
    )}
    
    // good
    {todos.map(todo => (
      <Todo
        {...todo}
        key={todo.id}
      />
    ))}

References

  • Always use ref callbacks.
// bad
<Foo
  ref="myRef"
/>

// good
<Foo
  ref={(ref) => { this.myRef = ref; }}
/>

HTML and CSS Style Guide

HTML Style Rules

  • Paragraphs of text should always be placed in a <p> tag. Never use multiple <br> tags.

  • Items in list form should always be in <ul>, <ol>, or <dl>. Never use a set of <div> or <p>.

  • Every form input that has text attached should utilize a <label> tag. Especially radio or checkbox elements.

  • Even though quotes around attributes is optional, always put quotes around attributes for readability.

  • Avoid writing closing tag comments, like <!-- /.element -->. This just adds to page load time. Plus, most editors have indentation guides and open-close tag highlighting.

  • Avoid trailing slashes in self-closing elements. For example, <br>, <hr>, <img>, and <input>.

  • Don’t set tabindex manually on the browser to set the order.

    <p class="line-note" data-attribute="106">
    This is my paragraph of special text.
    </p>

CSS Style Rules

  • Put spaces after : in property declarations.
  • Put spaces before { in rule declarations.
  • Put line breaks between rulesets.
  • When grouping selectors, keep individual selectors to a single line.
  • Place closing braces of declaration blocks on a new line.
  • Each declaration should appear on its own line for more accurate error reporting.
Clone this wiki locally