<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">\documentclass[onecolumn,letterpaper,11pt]{article}

%===================================================================
% Include common packages, environments, counters etc
\input{common_latex/common_latex_packages}
\input{common_latex/common_latex_lab_format}
\input{common_latex/common_latex_definitions}
%===================================================================

\begin{document}
\wikidoc{file=Lab.CPPStructure}
\wikidoc{auth=mikerb@mit.edu}


%===================================================================
% Build the Cover Page in an environment style easy for wiki parsing
\begin{labcover}
\labtitle{Lab 09 - C++ Coding Guidelines}
\vspace{0.1in}
\labcourse{2.680 Unmanned Marine Vehicle Autonomy, Sensing and Communications}
\vspace{0.2in}
\labpng{0.55}{figures/coding_standards.png}
\vspace{0.3in}
\labdate{Spring 2020}
\vspace{0.1in}
\labauth{Michael Benjamin, mikerb@mit.edu}
\labauth{Department of Mechanical Engineering}
\labauth{MIT, Cambridge MA 02139}
\vspace{0.2in}
\labtoc{small}
\end{labcover}

%===================================================================
% Add a blank page so first body page is on the right when doubleside
\blankpage

%===================================================================
% Begin the body of the text
%======================================================================
\section{Overview and Objectives}
%======================================================================

This document describes a set of C++ coding structure suggestions
based on practices commonly found in the body of code comprising the
MOOS-IvP Open Source autonomy project. Some of the topics are by
nature subjective, while some represent coding practices we advocate
for more vigorously especially if you are a student of 2.680 and even
more so if you are writing code to be included in the MOOS-IvP
distribution. 

\pskip
\noindent
This document covers {\em structure} conventions or guidelines as
opposed to its sister document which covers {\em style}
conventions. Both are part of the same discussion, but the former is
perhaps less contentious, and represents longer standing practices
concerning the assurance of code correctness. The latter is a bit
more subjective and addresses code {\em readability}.

\begin{labinfo}
%\labinfoheader{Topics:}
\begin{packed_itemize}[2]
\item Put Your Name On Your Code
\item Each C++ Class Has a Dedicated .cpp and .h file
\item Initialize Your Variables
\item Use Distinct Notation for Class Member Variables
\item Create Class Member Variables Only When Needed
\item Use const Functions Where Appropriate
\item Use unsigned int vs. int Where Appropriate
\item Return Bool in Parameter Handling Functions
\item Avoid Overloading Variables
\end{packed_itemize}
\end{labinfo}

%======================================================================
\subsection*{More C++ Structure/Style Resources}

For some of the topics covered here, related discussions can be found on 
the web. Links to some of these are given in the related section and a 
few general references are further provided below.

\noindent
Books:

\begin{packed_itemize}
\item {\em C++ Coding Standards: 101 Rules, Guidelines, and Best Practices}, 
  Herb Sutter, Andrei Alexandrescu, 2004.
\item {\em Safe C++: How to avoid common mistakes}, Vladimir Kushnir, 2012.
\end{packed_itemize}

\noindent
Web sites:

\begin{packed_itemize}
\item The googlecode.com web site has a styleguide that's worth checking out 
  for comparison.
  \urlx{http://google-styleguide.googlecode.com/svn/trunk/cppguide.html}

\item Stroustrup also provides a short discussion on coding standards and a 
  few pointers of their own to other resources here:
  \urlx{http://www.stroustrup.com/bs_faq2.html\#coding-standard}
\end{packed_itemize}


%==================================================================
\section{Put Your Name On Your Code}
%==================================================================

Even if you think a piece of code is just a temporary hack that no one
but you will ever use, put your name on it - {\em day one!} It is far
too common to open a piece of software in a group project repository,
and no one has any idea who wrote it.

\pskip

Put your name at the top of every source code file.  This includes all
\var{.cpp} and header, \var{.h}, files, including \var{main.cpp} and
the \var{CMakeLists.txt} file.  A header block like the one below is
strongly recommended, including name, organization, file name, and
date created.

\vspace{0.1in}

\begin{fileverb}
/*****************************************************************/
/*    NAME: Harry Chapin                                         */
/*    ORGN: Dept of Mechanical Eng / MIT Cambridge MA            */
/*    FILE: Widget.cpp                                           */
/*    DATE: Oct 12th 2004                                        */
/*****************************************************************/
\end{fileverb}

\vspace{0.1in}

\noindent
If a major revision is implemented that either significantly changes
the code function or was done by someone other than the original
author, something like the below is appropriate:

\begin{fileverb}
/*****************************************************************/
/*    NAME: Ella Sudbury (originally by Harry Chapin)            */
/*    ORGN: Dept of Mechanical Eng / MIT Cambridge MA            */
/*    FILE: Widget.cpp                                           */
/*    DATE: Oct 12th 2004                                        */
/*    DATE: Jun 18th 2012 Multithreading added by E. Sudbury     */
/*****************************************************************/
\end{fileverb}

%==================================================================
\section{Each C++ Class Has a Dedicated .cpp and .h File}
%==================================================================

When creating a C++ class, a simple rule of thumb is to implement the class
definition/interface in a dedicated \var{.h} file and the class implementation
in a dedicated \var{.cpp} file. Developers sometimes bend this rule when a 
class is regarded as a simple/small utility class only used by another more
complex class. In this case the smaller class definition and implementation
is embedded in the larger classes definition (\var{.h}) file. Even in these
cases I strongly recommend using a dedicated \var{.h} and \var{.cpp} file
even for small classes. By sticking to this convention, it makes it far
easier for someone to track down a class when they see it being used
in the code somewhere. 

\pskip

If a class is used in more than one place, e.g., in more than one other
class implementation, then the first class certainly ought to be defined
and implemented in its own \var{.h} and \var{.cpp} files. 

%==================================================================
\section{Initialize Your Variables}
%==================================================================

The worst kinds of bugs are those that happen intermittently. Even
worse if code is bug-free on your computer but someone informs you that
it crashes on their computer. If you find yourself in this situation,
avoid the temptation to say "but it works on my machine". 

\pskip

\noindent
Intermittent bugs are often due to uninitialized variables.  When the
following line of code is executed:

\vspace{0.1in}
\begin{fileverb}
 double a;
\end{fileverb}
\vspace{0.1in}

\noindent
Sometimes (maybe most of the time?) the initial value will be 0. But often
it will not, and this is where the intermittent nature of the problem is
introduced. 

\pskip

When implementing a C++ class, always look through your list of member
variables in your class definition, and make sure you are initializing
those same variables in your class constructor. When I say
"especially" class member variables, I don't mean they are somehow
more important. I say "especially" because it should be an item on
your mental checklist to match up your class member variable
declarations, and ensure you have the required initializations in your
constructor. Another tip: initialize your member variables in the same
order they are declared if possible. This makes it easer to
double-check that all member variables have been initialized.

\pskip

\noindent
You can safely omit initializations of certain classes that have their
own initializations, as with many of the STL classes such as
\var{string}, \var{vector} and so on. For example, in a class with
the following three member variables:

\vspace{0.1in}
\begin{fileverb}
  ...
  double       m_speed;
  unsigned int m_amount;
  std::string  m_status;
  ...
\end{fileverb}
\vspace{0.1in}

\noindent
the following may be found in the corresponding constructor:

\begin{fileverb}
  ...
  m_speed  = 0;    // necessary
  m_amount = 0;    // necessary
  m_status = "";   // NOT necessary
  ...
\end{fileverb}
\vspace{0.1in}

\noindent
Even if you are sure that \var{m\_speed} will otherwise be set somehow
before it is referenced, always initialize it. 



%==================================================================
\section{Use Distinct Notation for Class Member Variables}
%==================================================================

Class member variables variable are essentially global within any
function implemented for the C++ class. We prefix these variables with
\var{m\_}. This makes code much easier to read since we immediately
know if a variable was declared locally or defined at the class
level. Some examples:

\vspace{0.1in}
\begin{packed_itemize}
\item \var{m\_verbose}
\item \var{m\_line\_length}
\item \var{m\_dynamic\_scale}
\end{packed_itemize}
\vspace{0.1in}

%==================================================================
\section{Create Class Member Variables Only When Needed}
%==================================================================

Code that is simpler is easier to understand and maintain. One way to
simplify code is to not introduce class member variables unless
needed. Class member variables act like global variables in that they
are accessible across all class functions. They provide a form 
of persistence because they don't go out of scope (they hold they 
value) even after a function call has completed. Consider the below
code snippet for a fictional class \var{MyClass}. The class has two
member variables and a function:

\vspace{0.1in}
\begin{fileverb}
class MyClass
{
  ...
  void calcSquarRoot();
  ...

  double m_sqrt; 
  double m_current_value;
  ...
}
\end{fileverb}
\vspace{0.1in}

\noindent
And the below function:

\begin{fileverb}
void MyClass::calcSquareRoot() 
{
  m_sqrt = sqrt(m_current_value);
  cout &lt;&lt; "The square root is: " &lt;&lt; m_sqrt &lt;&lt; endl;
}
\end{fileverb}
\vspace{0.1in}

\noindent
The above function implies two things to me. First it implies that the
\var{m\_current\_value} variable was set elsewhere in some other
function, and second, that the \var{m\_sqrt} variable is used elsewhere
in some other function. In readable, simple code, the implications should
match reality. If the variable \var{m\_sqrt} is not actually used elsewhere, 
it is still legal compilable code, but it is overly complex and misleading.
A better implementation would be:

\vspace{0.1in}
\begin{fileverb}
class MyClass
{
  ...
  void calcSquarRoot();
  ...
  double m_current_value;
  ...
}

void MyClass::calcSquareRoot() 
{
  double sqrt = sqrt(m_current_value);
  cout &lt;&lt; "The square root is: " &lt;&lt; sqrt &lt;&lt; endl;
}
\end{fileverb}
\vspace{0.1in}

%==================================================================
\section{Use const Functions Where Appropriate}
%==================================================================

If a class member function doesn't result in a change in value or
state of any class member variables, it really should be implemented
as \var{const} function. For example:

\vspace{0.1in}
\begin{fileverb}
 bool tempIsPositive() const     // &lt;-- Note the use of const
 {
   if(m_temperature &gt; 0)
     return(true);
   return(false);
 }
\end{fileverb}
\vspace{0.1in}

\noindent
is preferable to the below since the member variable, \var{m\_temperature}
is only examined and not modified. This may be obvious in this short example, 
but in longer functions it may be hard to discern from a glance whether the
function results in a state change.

\vspace{0.1in}
\begin{fileverb}
 bool tempIsPositive()
 {
   if(m_temperature &gt; 0)
     return(true);
   return(false);
 }
\end{fileverb}
\vspace{0.1in}

\noindent
Use of const functions, where possible, ultimately makes the code much
more readable by conveying to readers a key property of the function,
i.e., whether or not the local state of the class instance will be
changed by invoking this function.


%==================================================================
\section{Use unsigned int vs. int Where Appropriate}
%==================================================================

Unsigned integers are similar to integers, usually taking up the same 
amount of bits. But unsigned ints don't interpret the higher order bit
as the sign, but instead assume the number is non-negative and use that
one extra bit to represent the value, thus effectively doubling the 
range of values that can be represented with the same number of bits. 

\pskip
\noindent
The biggest advantage is that they convey to the compiler, and to
later readers or maintainers of the code, the intended use of the
variable. It will help the compiler help you find mistakes. You should
use unsigned ints when representing (a) a {\em count} of some kind of
event and (b) the {\em size} of a container. For example, the
following should not occur in your code, even though the compiler may
let you get away with it:

\vspace{0.1in}
\begin{consoleverb}
  int total_days = holidays.size();
\end{consoleverb}
\vspace{0.1in}

\noindent
If \var{holidays} is your own data structure, and a non-zero number is
just not possible, the \var{size()} function should be implemented to
return an unsigned int. If \var{holidays} is an instance of the STL
class \var{vector}, or \var{set} for example, these classes {\em do}
implement the \var{size()} function to return an unsigned int, and the
above line of code is even more egregious. By using:

\vspace{0.1in}
\begin{fileverb}
  unsigned int total_days = holidays.size();
\end{fileverb}
\vspace{0.1in}

\noindent
this tells the reader a lot about how \var{holidays} is implemented,
without even knowing the class type of \var{holidays}.  So it's a win
even if only for pure code readability. But even better it will allow
the compiler to work on your behalf if you try to later treat it in a
way that is inconsistent with the assumption that it is non-negative.

\pskip
\noindent
Use of unsigned int allows you to safely assume the number will never
be less than zero which can be convenient in certain cases. For
example, if a function takes as an argument an index into an array,
typically the function will include a check that the index is valid:

\vspace{0.1in}
\begin{fileverb}
  double MyClass::getTemperature(unsigned int index)
  {
    if(index &gt;= m_series_temp.size())
      return(0);
    return(m_series_temp[index])
  }
\end{fileverb}
\vspace{0.1in}

\noindent
In the above there is no need to check that the index negative. 
If instead, the argument is an int, then we would need:

\vspace{0.1in}
\begin{fileverb}
  double MyClass::getTemperature(int index)
  {
    if((index &lt; 0) || (index &gt;= m_series_temp.size()))
      return(0);
    return(m_series_temp[index])
  }
\end{fileverb}
\vspace{0.1in}

%==================================================================
\section{Return Bool in Parameter Handling Functions}
%==================================================================

If you have a function that is handling input or configuration parameters, 
implement some sensible correctness checking, and return true or false. 

\vspace{0.1in}
\noindent
For example:

\vspace{0.1in}
\begin{fileverb}
bool SomeClass::setHeading(double value)
{
  if((value &lt; 0) || (value &gt;= 360))
    return(false);
  m_heading = value;
  return(true);
}
\end{fileverb}

\vspace{0.1in}
\noindent
is better for a function taking a value in the range $[0, 360)$, compared to
the following:

\vspace{0.1in}
\begin{consoleverb}
void SomeClass::setHeading(double value)
{
  m_heading = value;
}
\end{consoleverb}


\end{document}



</pre></body></html>