<h1>Code style guide<aclass="headerlink"href="#code-style-guide"title="Permalink to this headline">¶</a></h1>
<p>This document explains the coding style used in the R3 prototyping repository. You will be expected to follow these
recommendations when submitting patches for review. Please take the time to read them and internalise them, to save
time during code review.</p>
<p>What follows are <em>recommendations</em> and not <em>rules</em>. They are in places intentionally vague, so use your good judgement
when interpreting them.</p>
<divclass="admonition note">
<pclass="first admonition-title">Note</p>
<pclass="last">Parts of the codebase may not follow this style guide yet. If you see a place that doesn’t, please fix it!</p>
</div>
<divclass="section"id="general-style">
<h2>1. General style<aclass="headerlink"href="#general-style"title="Permalink to this headline">¶</a></h2>
<p>We use the standard Java coding style from Sun, adapted for Kotlin in ways that should be fairly intuitive.</p>
<p>Files no longer have copyright notices at the top, and license is now specified in the global README.md file.
We do not mark classes with @author Javadoc annotations.</p>
<p>In Kotlin code, KDoc is used rather than JavaDoc. It’s very similar except it uses Markdown for formatting instead
of HTML tags.</p>
<p>We target Java 8 and use the latest Java APIs whenever convenient. We use <codeclass="docutils literal"><spanclass="pre">java.time.Instant</span></code> to represent timestamps
and <codeclass="docutils literal"><spanclass="pre">java.nio.file.Path</span></code> to represent file paths.</p>
<p>Never apply any design pattern religiously. There are no silver bullets in programming and if something is fashionable,
that doesn’t mean it’s always better. In particular:</p>
<ulclass="simple">
<li>Use functional programming patterns like map, filter, fold only where it’s genuinely more convenient. Never be afraid
to use a simple imperative construct like a for loop or a mutable counter if that results in more direct, English-like
code.</li>
<li>Use immutability when you don’t anticipate very rapid or complex changes to the content. Immutability can help avoid
bugs, but over-used it can make code that has to adjust fields of an immutable object (in a clone) hard to read and
stress the garbage collector. When such code becomes a widespread pattern it can lead to code that is just generically
slow but without hotspots.</li>
<li>The tradeoffs between various thread safety techniques are complex, subtle, and no technique is always superior to
the others. Our code uses a mix of locks, worker threads and messaging depending on the situation.</li>
</ul>
<divclass="section"id="line-length-and-spacing">
<h3>1.1 Line Length and Spacing<aclass="headerlink"href="#line-length-and-spacing"title="Permalink to this headline">¶</a></h3>
<p>We aim for line widths of no more than 120 characters. That is wide enough to avoid lots of pointless wrapping but
narrow enough that with a widescreen monitor and a 12 point fixed width font (like Menlo) you can fit two files
next to each other. This is not a rigidly enforced rule and if wrapping a line would be excessively awkward, let it
overflow. Overflow of a few characters here and there isn’t a big deal: the goal is general convenience.</p>
<p>Where the number of parameters in a function, class, etc. causes an overflow past the end of the first line, they should
be structured one parameter per line.</p>
<p>Code is vertically dense, blank lines in methods are used sparingly. This is so more code can fit on screen at once.</p>
<p>We use spaces and not tabs.</p>
</div>
<divclass="section"id="naming">
<h3>1.2 Naming<aclass="headerlink"href="#naming"title="Permalink to this headline">¶</a></h3>
<p>Naming generally follows Java standard style (pascal case for class names, camel case for methods, properties and
variables). Where a class name describes a tuple, “And” should be included in order to clearly indicate the elements are
individual parts, for example <codeclass="docutils literal"><spanclass="pre">PartyAndReference</span></code>, not <codeclass="docutils literal"><spanclass="pre">PartyReference</span></code> (which sounds like a reference to a
<p>We use C-style (<codeclass="docutils literal"><spanclass="pre">/**</span><spanclass="pre">*/</span></code>) comments for API docs and we use C++ style comments (<codeclass="docutils literal"><spanclass="pre">//</span></code>) for explanations that are
only intended to be viewed by people who read the code.
When writing multi-line TODO comments, indent the body text past the TODO line, for example:</p>
<h2>3. Threading<aclass="headerlink"href="#threading"title="Permalink to this headline">¶</a></h2>
<p>Classes that are thread safe should be annotated with the <codeclass="docutils literal"><spanclass="pre">@ThreadSafe</span></code> annotation. The class or method comments
should describe how threads are expected to interact with your code, unless it’s obvious because the class is
(for example) a simple immutable data holder.</p>
<p>Code that supports callbacks or event listeners should always accept an <codeclass="docutils literal"><spanclass="pre">Executor</span></code> argument that defaults to
<codeclass="docutils literal"><spanclass="pre">MoreExecutors.directThreadExecutor()</span></code> (i.e. the calling thread) when registering the callback. This makes it easy
to integrate the callbacks with whatever threading environment the calling code expects, e.g. serialised onto a single
worker thread if necessary, or run directly on the background threads used by the class if the callback is thread safe
and doesn’t care in what context it’s invoked.</p>
<p>In the prototyping code it’s OK to use synchronised methods i.e. with an exposed lock when the use of locking is quite
trivial. If the synchronisation in your code is getting more complex, consider the following:</p>
<olclass="arabic simple">
<li>Is the complexity necessary? At this early stage, don’t worry too much about performance or scalability, as we’re
exploring the design space rather than making an optimal implementation of a design that’s already nailed down.</li>
<li>Could you simplify it by making the data be owned by a dedicated, encapsulated worker thread? If so, remember to
think about flow control and what happens if a work queue fills up: the actor model can often be useful but be aware
of the downsides and try to avoid explicitly defining messages, prefer to send closures onto the worker thread
instead.</li>
<li>If you use an explicit lock and the locking gets complex, and <em>always</em> if the class supports callbacks, use the
cycle detecting locks from the Guava library.</li>
<li>Can you simplify some things by using thread-safe collections like <codeclass="docutils literal"><spanclass="pre">CopyOnWriteArrayList</span></code> or <codeclass="docutils literal"><spanclass="pre">ConcurrentHashMap</span></code>?
These data structures are more expensive than their non-thread-safe equivalents but can be worth it if it lets us
simplify the code.</li>
</ol>
<p>Immutable data structures can be very useful for making it easier to reason about multi-threaded code. Kotlin makes it
easy to define these via the “data” attribute, which auto-generates a copy() method. That lets you create clones of
an immutable object with arbitrary fields adjusted in the clone. But if you can’t use the data attribute for some
reason, for instance, you are working in Java or because you need an inheritance heirarchy, then consider that making
a class fully immutable may result in very awkward code if there’s ever a need to make complex changes to it. If in
doubt, ask. Remember, never apply any design pattern religiously.</p>
<p>We have an extension to the <codeclass="docutils literal"><spanclass="pre">Executor</span></code> interface called <codeclass="docutils literal"><spanclass="pre">AffinityExecutor</span></code>. It is useful when the thread safety
of a piece of code is based on expecting to be called from a single thread only (or potentially, a single thread pool).
<codeclass="docutils literal"><spanclass="pre">AffinityExecutor</span></code> has additional methods that allow for thread assertions. These can be useful to ensure code is not
accidentally being used in a multi-threaded way when it didn’t expect that.</p>
</div>
<divclass="section"id="assertions-and-errors">
<h2>4. Assertions and errors<aclass="headerlink"href="#assertions-and-errors"title="Permalink to this headline">¶</a></h2>
<p>We use them liberally and we use them at runtime, in production. That means we avoid the “assert” keyword in Java,
and instead prefer to use the <codeclass="docutils literal"><spanclass="pre">check()</span></code> or <codeclass="docutils literal"><spanclass="pre">require()</span></code> functions in Kotlin (for an <codeclass="docutils literal"><spanclass="pre">IllegalStateException</span></code> or
<codeclass="docutils literal"><spanclass="pre">IllegalArgumentException</span></code> respectively), or the Guava <codeclass="docutils literal"><spanclass="pre">Preconditions.check</span></code> method from Java.</p>
<p>We define new exception types liberally. We prefer not to provide English language error messages in exceptions at
the throw site, instead we define new types with any useful information as fields, with a toString() method if
really necessary. In other words, don’t do this:</p>
Built with <ahref="http://sphinx-doc.org/">Sphinx</a> using a <ahref="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <ahref="https://readthedocs.org">Read the Docs</a>.