solidity/docs/style-guide.rst

772 lines
16 KiB
ReStructuredText
Raw Normal View History

2015-12-07 20:16:25 +00:00
.. index:: style, coding style
#############
Style Guide
#############
************
Introduction
************
This guide is intended to provide coding conventions for writing solidity code.
This guide should be thought of as an evolving document that will change over
time as useful conventions are found and old conventions are rendered obsolete.
Many projects will implement their own style guides. In the event of
conflicts, project specific style guides take precedence.
The structure and many of the recommendations within this style guide were
taken from python's
`pep8 style guide <https://www.python.org/dev/peps/pep-0008/>`_.
The goal of this guide is *not* to be the right way or the best way to write
solidity code. The goal of this guide is *consistency*. A quote from python's
`pep8 <https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds>`_
captures this concept well.
A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important.
2017-10-28 11:48:57 +00:00
But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgement. Look at other examples and decide what looks best. And don't hesitate to ask!
2015-12-07 20:16:25 +00:00
***********
Code Layout
***********
Indentation
===========
Use 4 spaces per indentation level.
Tabs or Spaces
==============
Spaces are the preferred indentation method.
Mixing tabs and spaces should be avoided.
Blank Lines
===========
Surround top level declarations in solidity source with two blank lines.
Yes::
contract A {
...
}
contract B {
...
}
contract C {
...
}
No::
contract A {
...
}
contract B {
...
}
contract C {
...
}
Within a contract surround function declarations with a single blank line.
Blank lines may be omitted between groups of related one-liners (such as stub functions for an abstract contract)
Yes::
contract A {
2017-12-12 18:47:30 +00:00
function spam() public;
function ham() public;
2015-12-07 20:16:25 +00:00
}
contract B is A {
2017-12-12 18:47:30 +00:00
function spam() public {
2015-12-07 20:16:25 +00:00
...
}
2017-12-12 18:47:30 +00:00
function ham() public {
2015-12-07 20:16:25 +00:00
...
}
}
No::
contract A {
2017-12-12 18:47:30 +00:00
function spam() public {
2015-12-07 20:16:25 +00:00
...
}
2017-12-12 18:47:30 +00:00
function ham() public {
2015-12-07 20:16:25 +00:00
...
}
}
Source File Encoding
====================
UTF-8 or ASCII encoding is preferred.
Imports
2016-08-10 15:48:23 +00:00
=======
2015-12-07 20:16:25 +00:00
Import statements should always be placed at the top of the file.
Yes::
import "owned";
contract A {
...
}
contract B is owned {
...
}
No::
contract A {
...
}
import "owned";
contract B is owned {
...
}
Order of Functions
==================
2016-11-22 08:47:58 +00:00
Ordering helps readers identify which functions they can call and to find the constructor and fallback definitions easier.
Functions should be grouped according to their visibility and ordered:
- constructor
- fallback function (if exists)
- external
- public
- internal
- private
Within a grouping, place the ``constant`` functions last.
Yes::
contract A {
2017-12-12 18:47:30 +00:00
function A() public {
...
}
2017-12-12 18:47:30 +00:00
function() public {
...
}
2017-12-12 18:47:30 +00:00
// External functions
// ...
2017-12-12 18:47:30 +00:00
// External functions that are constant
// ...
2017-12-12 18:47:30 +00:00
// Public functions
// ...
2017-12-12 18:47:30 +00:00
// Internal functions
// ...
2017-12-12 18:47:30 +00:00
// Private functions
// ...
}
No::
contract A {
2017-12-12 18:47:30 +00:00
// External functions
// ...
// Private functions
// ...
// Public functions
// ...
2017-12-12 18:47:30 +00:00
function A() public {
...
}
2017-12-12 18:47:30 +00:00
function() public {
...
}
// Internal functions
2017-12-12 18:47:30 +00:00
// ...
}
2015-12-07 20:16:25 +00:00
Whitespace in Expressions
=========================
Avoid extraneous whitespace in the following situations:
2017-10-28 11:48:57 +00:00
Immediately inside parenthesis, brackets or braces, with the exception of single line function declarations.
2015-12-07 20:16:25 +00:00
2016-05-05 18:40:35 +00:00
Yes::
spam(ham[1], Coin({name: "ham"}));
No::
2015-12-07 20:16:25 +00:00
spam( ham[ 1 ], Coin( { name: "ham" } ) );
2015-12-07 20:16:25 +00:00
Exception::
2017-12-12 18:47:30 +00:00
function singleLine() public { spam(); }
2016-05-06 13:42:05 +00:00
Immediately before a comma, semicolon:
2015-12-07 20:16:25 +00:00
2016-05-05 18:40:35 +00:00
Yes::
2017-12-12 18:47:30 +00:00
function spam(uint i, Coin coin) public;
2016-05-05 18:40:35 +00:00
No::
2015-12-07 20:16:25 +00:00
2017-12-12 18:47:30 +00:00
function spam(uint i , Coin coin) public ;
2015-12-07 20:16:25 +00:00
2016-05-06 13:42:05 +00:00
More than one space around an assignment or other operator to align with
2015-12-07 20:16:25 +00:00
another:
Yes::
x = 1;
y = 2;
long_variable = 3;
No::
x = 1;
y = 2;
long_variable = 3;
Don't include a whitespace in the fallback function:
Yes::
2017-12-12 18:47:30 +00:00
function() public {
...
}
No::
2017-12-12 18:47:30 +00:00
function () public {
...
}
2015-12-07 20:16:25 +00:00
Control Structures
==================
The braces denoting the body of a contract, library, functions and structs
should:
* open on the same line as the declaration
* close on their own line at the same indentation level as the beginning of the
declaration.
* The opening brace should be proceeded by a single space.
Yes::
contract Coin {
struct Bank {
address owner;
uint balance;
}
}
No::
contract Coin
{
struct Bank {
address owner;
uint balance;
}
}
The same recommendations apply to the control structures ``if``, ``else``, ``while``,
and ``for``.
2015-12-07 20:16:25 +00:00
Additionally there should be a single space between the control structures
``if``, ``while``, and ``for`` and the parenthetic block representing the
2015-12-07 20:16:25 +00:00
conditional, as well as a single space between the conditional parenthetic
block and the opening brace.
Yes::
if (...) {
...
}
for (...) {
...
}
No::
if (...)
{
...
}
while(...){
}
for (...) {
...;}
2016-05-06 15:11:00 +00:00
For control structures whose body contains a single statement, omitting the
2015-12-07 20:16:25 +00:00
braces is ok *if* the statement is contained on a single line.
Yes::
if (x < 10)
x += 1;
No::
if (x < 10)
someArray.push(Coin({
name: 'spam',
value: 42
}));
For ``if`` blocks which have an ``else`` or ``else if`` clause, the ``else`` should be
2016-08-24 19:27:46 +00:00
placed on the same line as the ``if``'s closing brace. This is an exception compared
to the rules of other block-like structures.
2015-12-07 20:16:25 +00:00
Yes::
if (x < 3) {
x += 1;
2016-08-24 19:27:46 +00:00
} else if (x > 7) {
2015-12-07 20:16:25 +00:00
x -= 1;
2016-08-24 19:27:46 +00:00
} else {
x = 5;
2015-12-07 20:16:25 +00:00
}
if (x < 3)
x += 1;
else
x -= 1;
No::
if (x < 3) {
x += 1;
2016-08-24 19:27:46 +00:00
}
else {
2015-12-07 20:16:25 +00:00
x -= 1;
}
Function Declaration
====================
For short function declarations, it is recommended for the opening brace of the
function body to be kept on the same line as the function declaration.
The closing brace should be at the same indentation level as the function
declaration.
The opening brace should be preceeded by a single space.
Yes::
2017-12-12 18:47:30 +00:00
function increment(uint x) public pure returns (uint) {
2015-12-07 20:16:25 +00:00
return x + 1;
}
2017-12-12 18:47:30 +00:00
function increment(uint x) public pure onlyowner returns (uint) {
2015-12-07 20:16:25 +00:00
return x + 1;
}
No::
2017-12-12 18:47:30 +00:00
function increment(uint x) public pure returns (uint)
2015-12-07 20:16:25 +00:00
{
return x + 1;
}
2017-12-12 18:47:30 +00:00
function increment(uint x) public pure returns (uint){
2015-12-07 20:16:25 +00:00
return x + 1;
}
2017-12-12 18:47:30 +00:00
function increment(uint x) public pure returns (uint) {
2015-12-07 20:16:25 +00:00
return x + 1;
}
2017-12-12 18:47:30 +00:00
function increment(uint x) public pure returns (uint) {
2015-12-07 20:16:25 +00:00
return x + 1;}
The visibility modifiers for a function should come before any custom
modifiers.
Yes::
function kill() public onlyowner {
selfdestruct(owner);
}
No::
function kill() onlyowner public {
selfdestruct(owner);
}
2016-09-06 09:24:06 +00:00
For long function declarations, it is recommended to drop each argument onto
2015-12-07 20:16:25 +00:00
it's own line at the same indentation level as the function body. The closing
parenthesis and opening bracket should be placed on their own line as well at
the same indentation level as the function declaration.
Yes::
function thisFunctionHasLotsOfArguments(
address a,
address b,
address c,
address d,
address e,
address f
2017-12-12 18:47:30 +00:00
)
public
{
doSomething();
2015-12-07 20:16:25 +00:00
}
No::
function thisFunctionHasLotsOfArguments(address a, address b, address c,
2017-12-12 18:47:30 +00:00
address d, address e, address f) public {
doSomething();
2015-12-07 20:16:25 +00:00
}
function thisFunctionHasLotsOfArguments(address a,
address b,
address c,
address d,
address e,
2017-12-12 18:47:30 +00:00
address f) public {
doSomething();
2015-12-07 20:16:25 +00:00
}
function thisFunctionHasLotsOfArguments(
address a,
address b,
address c,
address d,
address e,
2017-12-12 18:47:30 +00:00
address f) public {
doSomething();
2015-12-07 20:16:25 +00:00
}
If a long function declaration has modifiers, then each modifier should be
2017-12-12 18:47:30 +00:00
dropped to its own line.
2015-12-07 20:16:25 +00:00
Yes::
function thisFunctionNameIsReallyLong(address x, address y, address z)
public
onlyowner
priced
returns (address)
{
doSomething();
2015-12-07 20:16:25 +00:00
}
function thisFunctionNameIsReallyLong(
address x,
address y,
address z,
)
public
onlyowner
priced
returns (address)
{
doSomething();
2015-12-07 20:16:25 +00:00
}
No::
function thisFunctionNameIsReallyLong(address x, address y, address z)
public
onlyowner
priced
returns (address) {
doSomething();
2015-12-07 20:16:25 +00:00
}
function thisFunctionNameIsReallyLong(address x, address y, address z)
public onlyowner priced returns (address)
{
doSomething();
2015-12-07 20:16:25 +00:00
}
function thisFunctionNameIsReallyLong(address x, address y, address z)
public
onlyowner
priced
returns (address) {
doSomething();
2015-12-07 20:16:25 +00:00
}
2016-05-06 15:11:00 +00:00
For constructor functions on inherited contracts whose bases require arguments,
2015-12-07 20:16:25 +00:00
it is recommended to drop the base constructors onto new lines in the same
manner as modifiers if the function declaration is long or hard to read.
Yes::
contract A is B, C, D {
function A(uint param1, uint param2, uint param3, uint param4, uint param5)
B(param1)
C(param2, param3)
D(param4)
2017-12-12 18:47:30 +00:00
public
2015-12-07 20:16:25 +00:00
{
// do something with param5
}
}
No::
contract A is B, C, D {
function A(uint param1, uint param2, uint param3, uint param4, uint param5)
B(param1)
C(param2, param3)
D(param4)
2017-12-12 18:47:30 +00:00
public
2015-12-07 20:16:25 +00:00
{
// do something with param5
}
}
contract A is B, C, D {
function A(uint param1, uint param2, uint param3, uint param4, uint param5)
B(param1)
C(param2, param3)
2017-12-12 18:47:30 +00:00
D(param4)
public {
2015-12-07 20:16:25 +00:00
// do something with param5
}
}
2016-05-06 14:19:28 +00:00
When declaring short functions with a single statement, it is permissible to do it on a single line.
Permissible::
2017-12-12 18:47:30 +00:00
function shortFunction() public { doSomething(); }
2015-12-07 20:16:25 +00:00
These guidelines for function declarations are intended to improve readability.
Authors should use their best judgement as this guide does not try to cover all
possible permutations for function declarations.
Mappings
========
TODO
Variable Declarations
=====================
Declarations of array variables should not have a space between the type and
the brackets.
Yes::
uint[] x;
No::
uint [] x;
2015-12-07 20:16:25 +00:00
Other Recommendations
=====================
2016-08-10 15:48:23 +00:00
* Strings should be quoted with double-quotes instead of single-quotes.
Yes::
str = "foo";
str = "Hamlet says, 'To be or not to be...'";
No::
str = 'bar';
str = '"Be yourself; everyone else is already taken." -Oscar Wilde';
2015-12-07 20:16:25 +00:00
* Surround operators with a single space on either side.
Yes::
x = 3;
x = 100 / 10;
x += 3 + 4;
x |= y && z;
No::
x=3;
x = 100/10;
x += 3+4;
x |= y&&z;
* Operators with a higher priority than others can exclude surrounding
2015-12-07 22:31:58 +00:00
whitespace in order to denote precedence. This is meant to allow for
2015-12-07 20:16:25 +00:00
improved readability for complex statement. You should always use the same
amount of whitespace on either side of an operator:
Yes::
x = 2**3 + 5;
x = 2*y + 3*z;
x = (a+b) * (a-b);
No::
x = 2** 3 + 5;
x = y+z;
x +=1;
******************
2015-12-07 20:16:25 +00:00
Naming Conventions
******************
Naming conventions are powerful when adopted and used broadly. The use of
different conventions can convey significant *meta* information that would
otherwise not be immediately available.
2016-01-06 23:26:08 +00:00
The naming recommendations given here are intended to improve the readability,
and thus they are not rules, but rather guidelines to try and help convey the
most information through the names of things.
Lastly, consistency within a codebase should always supercede any conventions
outlined in this document.
Naming Styles
=============
To avoid confusion, the following names will be used to refer to different
naming styles.
* ``b`` (single lowercase letter)
* ``B`` (single uppercase letter)
* ``lowercase``
* ``lower_case_with_underscores``
* ``UPPERCASE``
* ``UPPER_CASE_WITH_UNDERSCORES``
* ``CapitalizedWords`` (or CapWords)
* ``mixedCase`` (differs from CapitalizedWords by initial lowercase character!)
* ``Capitalized_Words_With_Underscores``
2015-12-17 15:57:02 +00:00
.. note:: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus HTTPServerError is better than HttpServerError.
Names to Avoid
==============
* ``l`` - Lowercase letter el
* ``O`` - Uppercase letter oh
* ``I`` - Uppercase letter eye
Never use any of these for single letter variable names. They are often
indistinguishable from the numerals one and zero.
Contract and Library Names
==========================
Contracts and libraries should be named using the CapWords style. Examples: ``SimpleToken``, ``SmartBank``, ``CertificateHashRepository``, ``Player``.
2018-01-14 18:53:45 +00:00
Struct Names
==========================
Structs should be named using the CapWords style. Examples: ``MyCoin``, ``Position``, ``PositionXY``.
Event Names
===========
Events should be named using the CapWords style. Examples: ``Deposit``, ``Transfer``, ``Approval``, ``BeforeTransfer``, ``AfterTransfer``.
Function Names
==============
Functions other than constructors should use mixedCase. Examples: ``getBalance``, ``transfer``, ``verifyOwner``, ``addMember``, ``changeOwner``.
2017-10-25 19:58:18 +00:00
Function Argument Names
=======================
Function arguments should use mixedCase. Examples: ``initialSupply``, ``account``, ``recipientAddress``, ``senderAddress``, ``newOwner``.
2015-12-07 20:16:25 +00:00
When writing library functions that operate on a custom struct, the struct
should be the first argument and should always be named ``self``.
2017-10-25 19:58:18 +00:00
Local and State Variable Names
==============================
Use mixedCase. Examples: ``totalSupply``, ``remainingSupply``, ``balancesOf``, ``creatorAddress``, ``isPreSale``, ``tokenExchangeRate``.
Constants
=========
Constants should be named with all capital letters with underscores separating
words. Examples: ``MAX_BLOCKS``, `TOKEN_NAME`, ``TOKEN_TICKER``, ``CONTRACT_VERSION``.
Modifier Names
==============
Use mixedCase. Examples: ``onlyBy``, ``onlyAfter``, ``onlyDuringThePreSale``.
Enums
=====
Enums, in the style of simple type declarations, should be named using the CapWords style. Examples: ``TokenGroup``, ``Frame``, ``HashStyle``, ``CharacterLocation``.
Avoiding Naming Collisions
==========================
* ``single_trailing_underscore_``
This convention is suggested when the desired name collides with that of a
built-in or otherwise reserved name.
2015-12-07 20:16:25 +00:00
General Recommendations
=======================
TODO