Quick Reference - Style guide


User Interface Guide

A clear user interface is important in software, even if we are just writing command line based programs.

 

General rules:

Rule Example

Before getting the user's input (via keyboard, for example), ALWAYS prompt the user - display a message telling them what you want them to enter.

cout << "Enter a number between 1 and 10: ";
cin >> number;
Enter a number between 1 and 10:
cout << "Press enter to continue..." << endl;
getline( cin, str );
Press ENTER to continue...

When displaying a lot of data, make sure to indent to make the information readable.

cout << "Class 1:     " << class1name << endl;
cout << "Class 10:    " << class10name << endl;
cout << "Class 25:    " << class25name << endl;
Class 1:    CS  134
Class 10:   CS  250
Class 25:   ASL 120
cout << "$" << price1 << "\t" << food1 << endl;
cout << "$" << price2 << "\t" << food2 << endl;
cout << "$" << price3 << "\t" << food3 << endl;
$4.99    Burrito
$5.39 Taco
$2.29 Soda

When a table can be used to display information, a table should be used.

cout << left << setprecision( 2 ) << fixed;

cout << setw( 5 ) << "ID"
     << setw( 20 ) << "NAME"
     << setw( 10 ) << "PRICE"
     << setw( 10 ) << "IN STOCK" << endl;

cout << string( 40, '-' ) << endl;

for ( int i = 0; i < PROD_COUNT; i++ )
{
  cout << setw( 5 ) << i
       << setw( 20 ) << products[i].name
       << setw( 10 ) << products[i].price
       << setw( 10 ) << products[i].quantity << endl;
}
ID   NAME                PRICE     IN STOCK
----------------------------------------
0    Furby               79.99     50
1    Tamagatchi          59.95     3
2    Super Nintendo      249.99    23        

When going between different menus or areas of a program, use a "header" that stands out.

cout << string( 40, '-' ) << endl;
cout << "MAIN MENU" << endl;
cout << string( 40, '-' ) << endl;
----------------------------------------
MAIN MENU
----------------------------------------

 

 


C++ Style guide

When programming, it is important to maintain a consistent coding style to maintain readability. Each language has its own specified standard and each project will also generally have its own standard. When working alone, you can develop your own sense of style, but you should remain consistent.

More information:



Naming conventions

Rule Example

Variables

For this course, we will use camelCasing for variable names, with the first letter of the variable name written as lower-case. For all subsequent words in a variable name, the first letter of that word should be capitalized.

float price = 2.99;
int totalKittens = 4;
string currentLocation = "Overland Park";

Named constants

It is standard to write named constants' names as all upper-case and words separated by underscores.

int TOTAL_STUDENTS = 30;
string STATE_ABBR = "KS";

Functions

Function names should be styled using CamelCasing with the first letter of each word capitalized.

int AddAllCats(int a, int b, int c);
void DisplayMainMenu();
int GetChoice( int min, int max );

Classes

Name Structs and Classes in C++ using CamelCasing with the first letter of each word capitalized.

class PetCat
{
  private:
  string m_name;
  int m_birthYear;
};

struct Product
{
  string name;
  float price;
};

Indentation style and spacing

In C++, we denote the start and end of code blocks with curly braces { }. For example:

if ( catCount == 0 )
{
    AdoptACat();
}
Each time a new code block opens, the code within should be indented forward by 1 tab (or equivalent spaces).

Rule Example

Horizontal space (indentation)

Each time a code block is opened (after {), the next line should be indented forward by 1 TAB. When the code block is closed (after }), the next line of code should be unindented by 1 TAB.

If code is left unindented, or indented inconsistently:

int main()
{
int a = 0;
if ( a == 0 )
{
cout << "it's zero." << endl;
}
return 0;
}

then it will receive points off.

int main()
{
    // CODE IS NOW TABBED FORWARD

    int a = 0;
    if ( a == 0 )
    {
        // CODE IS INDENTED FORWARD ONE MORE TIME
        cout << "it's zero." << endl;
    }

    return 0;
}

Curly braces

Curly braces should go on the next line after the class name, function name, or condition/loop header, and should NOT be indented forward. However, the code within the code block { } should be indented forward by 1 tab.

I think it makes it easier to detect missing curly braces if braces for the same block are on the same level.

Additionally, I put in curly braces even for one line statements because if you need to go back and update it to add more lines later, it is faster to add stuff in if the curly braces are already there.

struct Cable
{
    int x;
    // ...
};

double Example( int x, int y )
{
    if ( x == y )
    {
        // Multiple lines of code
    }

    if      ( x < 0 )   
    {
        negative_case();
    }
    else if ( x > 0 )   
    {
        positive_case();
    }
    else                
    {
        zero_case();
    }

    return some_value;
}

Vertical whitespace

Parts of a program should be separated by empty newlines to help "chunk" together related parts of code.

DON'T mush all the code together:

int main()
{
  const int PROD_COUNT = 3;
  Product products[PROD_COUNT];
  products[0].name = "Furby";
  products[0].quantity = 50;
  products[0].price = 79.99;
  products[1].name = "Tamagatchi";
  products[1].quantity = 3;
  products[1].price = 59.95;
  products[2].name = "Super Nintendo";
  products[2].quantity = 23;
  products[2].price = 249.99;
  cout << left << setprecision( 2 ) << fixed;
  cout << setw( 5 ) << "ID"
       << setw( 20 ) << "NAME"
       << setw( 10 ) << "PRICE"
       << setw( 10 ) << "IN STOCK" << endl;
  cout << string( 40, '-' ) << endl;
  for ( int i = 0; i < PROD_COUNT; i++ )
  {
    cout << setw( 5 ) << i
         << setw( 20 ) << products[i].name
         << setw( 10 ) << products[i].price
         << setw( 10 ) << products[i].quantity << endl;
  }
  return 0;
}
int main()
{
  const int PROD_COUNT = 3;
  Product products[PROD_COUNT];

  products[0].name = "Furby";
  products[0].quantity = 50;
  products[0].price = 79.99;

  products[1].name = "Tamagatchi";
  products[1].quantity = 3;
  products[1].price = 59.95;

  products[2].name = "Super Nintendo";
  products[2].quantity = 23;
  products[2].price = 249.99;

  cout << left << setprecision( 2 ) << fixed;

  cout << setw( 5 ) << "ID"
       << setw( 20 ) << "NAME"
       << setw( 10 ) << "PRICE"
       << setw( 10 ) << "IN STOCK" << endl;

  cout << string( 40, '-' ) << endl;

  for ( int i = 0; i < PROD_COUNT; i++ )
  {
    cout << setw( 5 ) << i
         << setw( 20 ) << products[i].name
         << setw( 10 ) << products[i].price
         << setw( 10 ) << products[i].quantity << endl;
  }

  return 0;
}
                                

Tabs vs. Spaces

I don't care what you use, just be consistent. I prefer spaces.

Your indentation length usually defaults to 4, and that's fine. You can also set it to 2. I would avoid choosing anything besides 2 or 4.



Comments

I generally don't write comments in my code very much from my industry experience because when working on a project over time, it is very easy for code to be updated but the comments to be forgotten. When the comments become stale, they can also become misleading. Instead, it is better to write clear code that is "self-documenting" as much as possible.

I mostly just write documentation-style comments for functions when writing something that will be used in multiple projects, such as a data structure.

Generally with our projects in the classes, your intent is usually clear enough that I do not need you to add comments to clarify what you're doing. Comments should be to clarify something like a formula or something else that is non-obvious from just looking at it.



Formatting tips for C++

Tip Example

To format currency, make sure to have
#include <iomanip>, and put this cout statement at the beginning of your program in order to specify formatting.

// Setup:
cout << fixed << setprecision( 2 );
// Later:
float price = 2.90;
cout << price << endl;
price = 1.00;
cout << "$" << price << endl;
2.90
$1.00

To make a horizontal rule, you can use
string( LENGTH, CHAR ) with a cout statement.

cout << string( 40, '-' ) << endl;
----------------------------------------

To get input from the user that allows spaces in the string, you need to use
getline( cin, variable );

cout << "Enter city: ";
getline( cin, cityName );
cout << "City is: " << cityName << endl;
Enter city: Overland Park
City is: Overland Park

When switching between cin >> var; and getline( cin, var );, you need to use cin.ignore();!

If you misuse the cin.ignore(), you will probably notice your program either SKIPPING an input (no cin.ignore()), or skipping the first letter of an input (too many cin.ignore()s).

cout << "Enter price: ";
cin >> price;
cin.ignore();   // ONLY between cin >> and getline!!

cout << "Enter name: ";
getline( cin, name );

cout << "Enter city: ";
getline( cin, city );
Enter price: 3.99
Enter name: Bean Burrito
Enter city: Burrito City

To convert a float or integer to a string, you can use the following FUNCTIONS:

Int/float to String:

// THIS MUST GO IN A .h FILE!
template <typename T>
string Helper::ToString( const T& value )
{
    stringstream ss;
    ss << value;
    return ss.str();
}

String to int (can make a float version just by changing int to float):

int StringToInt( const string& str )
{
    int value = 0;
    try
    {
        value = stoi( str );
    }
    catch( const std::invalid_argument& ex )
    {
        std::cout << "Cannot convert \"" << str << "\" to int!" << std::endl;
        return -1;
    }

    return value;
}

Python Style guide

There is an Official Style Guide for Python. Here is a run down of the rules.

Naming conventions

There are a lot of different naming styles. It helps to be able to recognize what naming style is being used, independently from what they are used for.

The following naming styles are commonly distinguished:

  • b (single lowercase letter)
  • B (single uppercase letter)
  • lowercase
  • lower_case_with_underscores
  • UPPERCASE
  • UPPER_CASE_WITH_UNDERSCORES
  • CapitalizedWords (or CapWords, or CamelCase – so named because of the bumpy look of its letters [4]). This is also sometimes known as StudlyCaps.

    Note: When using acronyms in CapWords, capitalize all the letters of the acronym. Thus HTTPServerError is better than HttpServerError.

  • mixedCase (differs from CapitalizedWords by initial lowercase character!)
  • Capitalized_Words_With_Underscores (ugly!)

Rules:

  • Variables: Variable names follow the same convention as function names.
  • Constants: Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.
  • Functions: Function names should be lowercase, with words separated by underscores as necessary to improve readability.
  • Classes: Class names should normally use the CapWords convention.
  • Methods (class functions): Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
  • Instance variables (in a class): Use one leading underscore only for non-public methods and instance variables.

Indentation

Use 4 spaces per indentation level.

Continuation lines should align wrapped elements either vertically using Python’s implicit line joining inside parentheses, brackets and braces, or using a hanging indent [1]. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line:

# Correct:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# Add 4 spaces (an extra level of indentation) to distinguish arguments from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)
# Wrong:

# Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# Further indentation required as indentation is not distinguishable.
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

Tabs vs. Spaces

Spaces are preferred over tabs.

Comments

Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!

Comments should be complete sentences. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).

Block comments generally consist of one or more paragraphs built out of complete sentences, with each sentence ending in a period.

You should use two spaces after a sentence-ending period in multi- sentence comments, except after the final sentence.

Ensure that your comments are clear and easily understandable to other speakers of the language you are writing in.

An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.

Inline comments are unnecessary and in fact distracting if they state the obvious. Don’t do this:

x = x + 1                 # Increment x

But sometimes, this is useful:

x = x + 1                 # Compensate for border




Turning in code in CS 200

Take a screenshot of each program running.

You can use the Print Screen button on the keyboard and then paste the image into the Windows Paint program and save the image as a .png file.

Highlight the URL of your Replit project and copy it (CTRL+C or right-click and select Copy)

Paste the assignment URL into Canvas

Under the File Upload tab, upload the screenshots of the program.

Click on Submit Assignment when done.