Introduction
This is a collection of my passive-aggressive notes on software development. It
primarily concerns C++, Linux, and robotic applications, in other words,
embedded / headless systems consisting of a large number of heterogeneous
software components, running with minimal human intervention.
Sections of the document are ordered by decreasing level of abstraction, feel
free to skip those that seem to be non-substantial.
The markdown source of this document is available at
https://github.com/asherikov/codeincomplete, an HTML version – at
http://www.sherikov.net/codeincomplete/.
First principles
Human friendliness: minimize everyone’s mental work.
- The less you need to think the more you can do.
Consistency: make your choices and stick to them.
Automation: any action that is performed more than once must be automated.
Organization
Process vs progress
In my experience the trade-off between the two is always biased to the latter,
i.e., everything else is sacrificed to delivering quick results. In the end,
the codebase is unmanageable, results are unstable, and further progress
becomes more and more challenging. The more ambitious your goals are the more
effort you have to spend on organizing your processes, possibly delaying your
progress.
This trade-off is also important in refactoring legacy code base: if you have
no proper processes to ensure that there are no regressions and new
requirements are met, you are just adding to a pile of garbage without a hope
to improve anything.
Let it go
The field is quite dynamic and, although the changes are not always for the
best, you have to adapt and be ready to abandon your past achievements if
necessary and move on.
Reuse vs reinvent
Professional curiosity and ambitions, as well as laziness, often push developers
to reinventing existing tools and methodologies, rather than studying
alternatives and making an informed and pragmatic choice. Maintaining your own
code is often more expensive than working around the quirks of 3rd party
software.
What and why before how
When a new development is being discussed it is common to lose focus and drift
toward discussion of implementation rather than the purpose. Even experienced
developers tend to be carried away. For this reason, it is advisable to
explicitly separate discussions of what must be done, and how it must be done.
The first must result in a requirements document that would help to ensure that
development is moving in the right direction and to track progress.
Adequate processes
It feels that many teams fail at adequately matching the complexity of the
processes with the team size and project scale. 5-people teams spend a third of
their time writing KPIs and doing sprint reviews, while 50-people teams do not
bother to track their tasks in Jira. Both extremes negatively impact
performance, so it is crucial to find a reasonable balance and evolve processes
to reflect changes in the team and the projects.
Communication
Work related communication should happen through channels that facilitate
tracing and sharing of information and decisions: wiki, email, issue tracker,
source code management systems, etc. It is a crime to ignore your notifications
and expect everyone to reach you in-person to resolve issues.
Design
Architectural patterns
Transformation API symmetry
If you transform data to a different representation, e.g., by writing it from
memory to a file, you or somebody else almost always is going to need to perform
the reverse transformation. Take this into account when designing new API and
don’t neglect implementation of reverse operations: that helps to find bugs,
facilitates testing, makes your code and data more coherent. Also, assuming that
users must manually compose input files for your code is a dick move.
Examples:
URDF format is commonly used for robot model description in ROS. There is a
standard parser for it, but no emitter. Unfortunately you may need to modify
and store models automatically, e.g., when performing parameter
identification, in which case you’ll have to implement some ugly workarounds.
The second example comes from STL library where you can find std::to_string
(since C++11) but no std::from_string. For this reason,
boost::lexical_cast should be preferred since it works both ways.
Configuration-driven development
Start implementing services (ROS nodes) with a configuration file, this way
you can avoid hardcoded constants and save time during development and
testing.
Configuration files are better than command line arguments: they are more
general and scalable.
Choose YAML or JSON by default. XML is unnecessarily verbose, lacks
array type, has ambiguous choice between attributes and child nodes. Custom
formats should also be avoided since they are generally inferior to
YAML/JSON.
Use serialization / reflection libraries to abstract from a particular file
format, e.g., https://github.com/asherikov/ariles.
Don’t forget to respect transformation API symmetry – sooner or later you are
going to need to modify configuration during execution and export it for
future use.
When you come to the point where you need to export configurations make sure
that you are not mixing configuration with saved state of the system. State is
something that is less persistent and valuable, e.g., the last time the
software checked for updates.
Global configuration of the system, e.g., via ROS1 parameter server, is quite
convenient, but should always be used as read-only from services. Use messages
or services to pass parameters between services instead.
Environment variables should not be used for controlling your services, but
might be necessary to alter behavior of 3rd-party applications and scripts.
Process isolation
Isolation between processes is way better than between threads. Use this to your
advantage by isolating 3rd-party, potentially unreliable, or non-critical
components of you software system in standalone processes. For the same reason,
I recommend using ROS nodelets only when absolutely necessary, they are just a
workaround for poor IPC.
Let it crash
“Let it crash” approach to failure handling comes from Erlang – a language
designed for telecommunication applications https://en.wikipedia.org/wiki/Erlang\_(programming_language)#%22Let_it_crash%22_coding_style
You have to accept that your programs are going to crash, which means that:
you have to have a restarting mechanism in place, e.g., a service manager;
in some cases it is better to crash than try to recover on the fly, e.g.,
segmentation faults mentioned below;
you should exploit process isolation as described above to localize failures.
Let it vanish
This is also an old and ubiquitous design pattern, but I don’t recall a specific
term for it so I named it to relate to “let it crash”. The main idea is that you
have to design your software to lose data when appropriate:
If you are working with large amounts of data you may simply run out of memory
if you don’t limit size of you buffers.
Even if your data buffers are limited you may run into situations when they
are filled to a degree when data gets too old by the time the processing code
receives it. This is relevant for many data-rich sensors such as cameras,
lidars, etc.
I/O isolation
I/O is expensive, especially when it is performed via interactive terminals. It
is a common practice to localize I/O in separate threads to avoid interference
with time critical operations. For a similar reason, you should generally delay
transferring of debug and logging information until the end of time critical
methods, such as control loops.
State machines
State machines are often employed for representing robot behaviors, but in my
opinion they should be used more for implementation of individual services. Any
time you work on a service that changes its behavior in response to some command
messages, for example using http://wiki.ros.org/actionlib, it is necessary to
consider a finite state machine.
Fail early
Early failures usually have lower cost, for example, if you can detect a failure
during source code compilation you are saving time on deployment and tests, if
you can validate drone state before takeoff you can potentially avoid a crash,
and so on.
Single source shared parameters
Parameters shared by different components of the stack should come from the same
source. If they are stored in multiple independent locations, they are
inevitably going to get out of sync, which, in turn, would lead to failures or
poor performance. Extraction and distribution of shared parameters should not
necessarily happen at runtime, on the contrary, it may be preferable to perform
this during startup or build phases in order to comply with “fail early”
principle.
For example, an URDF / SDF model of a robot can be the source of its total mass
and geometric dimensions.
Separate logic from interfaces
Separate software logic from interfaces, both human and API:
- Interfaces involve potentially heavy I/O.
- They introduce dependencies on third party components, making it difficult to
test, migrate, and evolve the core functionality.
- Sometimes, interfaces are not necessary for normal operation, e.g., debugging
helpers, but may still introduce critical bugs.
For example, if your node receives a path, do not generate visual debugging
data, such as ROS markers for rviz, in the same node; but rather create an
independent node that would also subscribe for the path and generate necessary
visualization info.
Separate representation and handling
Separate data containers from logic that uses or modifies the data, e.g., use
separate classes for a message from a message publisher.
Project bootstrapping
There are a few things that should be done first when starting a new project.
Infrastructure first
Prepare templates for new packages, source code files, copyright notice, etc.
Bring up build and development infrastructure: CI, version control system.
Integrate static / dynamic analysis tools before starting coding:
Simulation
Simulation is a crucial component for testing your system. All code should
always be validated in simulation before deployment to save time and reduce
risks. For this reason simulation must be implemented as soon as possible.
Integration tests
Integration tests are more important on early stages of development: a simple
test that starts your system with a simulator and terminates immediately has
more value than a single thoroughly unit-tested component. Integration tests
focus your attention on the whole system rather than its parts. However, complex
integration tests are difficult to maintain and are prone to become fragile on
later stages of development, at which point you should support them with
component specific tests.
Development