“Style” in programming refers to the choices one makes about formatting, naming, organization, and other aspects of the code that don’t affect its meaning or correctness but that play an important role for any person reading the code.
There are many stylistic choices one can make, and none are necessarily right or wrong. However, making consistent choices throughout one’s code that are also consistent with other people’s code will make your code much easier for you and for others to read. A style guide gives guidance on those choices that one can follow to achieve that consistency. In our class, we will follow Google’s C++ Style Guide.
It is quite long and detailed. Much of it only applies to aspects of C++ that we will not be using in our class. For us, the most important sections are:
- Scoping, especially Local Variables
-
Naming, especially:
- Local and global variables will be named in
lower_case_with_underscores
. - Class member variables (attributes) will be named
with_a_trailing_underscore_
. - Class names will be named in capitalized
CamelCase
(wikipedia). - Functions, including class methods, will be named in capitalized
CamelCase
. -
All names should be descriptive, other than loop counter variables like
i
.
- Local and global variables will be named in
-
Comments, especially:
- Variable, class, and function comments come before the commented component.
- No specific format is required for comments, but they should be descriptive and clearly explain how to use the function/class being commented.
- Prefer
//
over/*
and*/
.
-
Formatting
-
Horizontal whitespace: Use 1 space around (most) operators. E.g.,
x = y + z
as opposed tox=y+z
. Exceptions:.
,->
,++
, and--
. Put 1 space before every opening{
curly brace. Do not put a space between a function name and its argument or parameter list. E.g., writeFunction(arg1, arg2)
, notFunction (arg1, arg2)
. - Vertical whitespace: Use 1 (or a few) blank lines between functions/classes etc., as well as between related sections of code within a function (sort of like paragraph breaks in writing).
- Indentation: Indent each nested block 2 spaces at a time. Do not use tabs in your code. You should set your editor to emit spaces when you hit the tab key. (Replit should do this automatically.)
-
Horizontal whitespace: Use 1 space around (most) operators. E.g.,
Additionally, here are some style guidelines and conventions for writing classes:
- Classes should be declared and implemented in their own files, which are named
ClassName.h
(declaration) andClassName.cpp
(implementation). - Class data members (attributes) should be private, unless they’re constants meant to be used outside the class.
- All classes should have explicit constructors and destructors, even if they do nothing, for clarity.
- Use
this->
to access an object’s attributes and methods from within its methods — this immediately differentiates them from normal variables and functions.