# Coding Style
:::danger
第三週開始
只要被抓到**任何一個地方**沒有遵守Coding Style
該項分數**全扣**,沒有部分給分
不論你的程式碼有多清楚明瞭,都**必須撰寫註解**,請使用**英文**撰寫,中文可能有編碼問題。
header註解 != function註解 != 一般註解
三者是各自獨立的扣分項,不能互相cover
:::
:::success
:::spoiler click to open TOC
[TOC]
:::success
:::
## Perfect Example
```cpp!
/***********************************************************************
* File: Main.cpp
* Author: Alex
* Create Date: 2023/03/17
* Editor: Brendon
* Update Date: 2023/03/17
* Description: This program is to compute and ouput the volume of a sphere with radius r.
***********************************************************************/
#define PI 3.1415926
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// reusable variable ,place this variable outside of the loop
std::string input;
// infinite loop until cin meets EOF
while (true)
{
// read input as a string
std::cin >> input;
// break the loop if input stream meets EOF
if(std::cin.eof())
{
break;
}
// output the input string ,
// but with the indentation if string length is less than 10
std::cout << std::setw(10) << input << "\n";
}
}
// Intent: To calculate the sum of two numbers
// Pre: Two integer number
// Post: The function returns the sum of two numbers
int sum(int a, int b){
return a + b;
}
```
```cpp!
/************************************************************************
* File: main.cpp
* Author: BO-EN HUANG & YUEH-HSUN WU
* Create Date: 2023-3-19
* Editor: BO-EN HUANG & YUEH-HSUN WU
* Update Date: 2023-3-19
* Description: Draw and print out the canvas.
************************************************************************/
#include <iostream>
#include <stdio.h>
using namespace std;
void drawBoard(); // Function to draw boards
void makeBoard(); // Function to make board
void modifyBoard(); // Function to modify board
const int DUNGEN_ROW = 10, DUNGEN_COL = 20;
char dungenMap[DUNGEN_ROW][DUNGEN_COL];
char wall, blank, position; // the symbol of wall, blank, position respectively
int posX = 0, posY = 0; // X and Y modifying position respectively
int main(int argc, char **argv)
{
makeBoard();
drawBoard();
modifyBoard();
drawBoard();
}
// Intent: Draw out the whole board
// Pre: nothing showed
// Post: show the dungen map on screen
void drawBoard()
//==================================================================
{
// Draw out the whole board
/************************************************************************/
for (int row = 0; row < DUNGEN_ROW; row++)
{
for (int col = 0; col < DUNGEN_COL; col++)
{
cout << dungenMap[row][col];
}
cout << endl;
}
cout << endl;
/************************************************************************/
}
// Intent: Enter symbol for wall and blank then create array
// Pre: symbols of wall and blank are unknown and the dungen map is empty
// Post: dungen map is filled with symbols of wall and blank
void makeBoard()
//==================================================================
{
// Enter symbol for wall and blank then create array
/************************************************************************/
cout << "Enter symbol for wall: ";
cin >> wall; // get the symbol of wall from user
cout << "Enter symbol for blank: ";
cin >> blank; // get the symbol of blank from user
// create the map
for (int row = 0; row < DUNGEN_ROW; row++)
{
for (int col = 0; col < DUNGEN_COL; col++)
{
if (row == 0 || row == DUNGEN_ROW - 1 || col == 0 || col == DUNGEN_COL - 1)
{
// set the board of map to be symbols of wall
dungenMap[row][col] = wall;
}
else
{
// set the inner of map to be filled with symbols of blank
dungenMap[row][col] = blank;
}
}
}
/************************************************************************/
}
// Intent: Modify board given position and char to change
// Pre: original map is not changed
// Post: if position of X and Y is valid, substitute symbol of position for given position in map
void modifyBoard()
//==================================================================
{
// Function for modifying board given position and char to change
/************************************************************************/
cout << "Enter symbol for modifying position: ";
cin >> position; // get the symbol of position from user
cout << "Enter X of modifying position: ";
cin >> posX; // get position of X from user
cout << "Enter Y of modifying position: ";
cin >> posY; // get position of Y from user
/* if the position of X or Y is beyond the board, show message "Invalid input",
otherwise, set the X,Y position in map to be symbol of position*/
if (posX < 0 || posY > DUNGEN_ROW - 1 || posY < 0 || posX > DUNGEN_COL - 1)
{
cout << "Invalid input" << endl;
}
else
{
dungenMap[posY][posX] = position;
}
/************************************************************************/
}
```
## 1. Every program must have a header. **10分**
```cpp!
/***********************************************************************
* File: Main.cpp
* Author: Alex
* Create Date: 2023/03/17
* Editor: Brendon
* Update Date: 2023/03/17
* Description: This program is to compute and ouput the volume of a sphere with radius r.
***********************************************************************/
```
* File
* Author
* Create
* Editor
* Last edit
* Description
:::danger
See Tip1
:::
:::warning
header要放在檔案開頭,不可放於其他位置
並且每個程式碼檔案(.h .cpp .cc)都要有!
:::
## 2. Use blank lines to separate logical sections. **5分**
### Correct Examples
```cpp!
#define PI 3.1415926535
#include<iostream>
#include<cmath>
using namespace std;
int main(){
// Define a variable that is used to save input value.
float input;
while(1){
//...
}
}
```
### Wrong Examples
```cpp!
// Wrong 1, No space between two logical sections.
if(...){
}
if(...){
}
// Wrong 2, Having a space between one logical section.
if(...){
}
else if(...){
}
// Wrong 3, Redundant spaces in your code.
int main(){
std::cout<<"Hello World!"<<std::endl;
}
// Wrong 4, No space between loop and variable define sections.
int main(){
float input;
while(...){
///....
}
}
// Wrong 5, No space between loop and output sections.
int main(){
while(...){
///....
}
cout<<"Hello World!"<<endl;
}
// Wrong 6, Having a meaningless space between two for loops.
for (int i = 0; i < DUNGEN_ROW; ++i)
{
for (int o = 0; o < DUNGEN_COL; ++o)
{
putchar(dungenMap[i][o]);
}
putchar('\n');
}
```
## 3. Use spaces around '=' and around operators and after commas and semicolons. **5分**
### Wrong Examples
```cpp!
// Wrong 1
double input=0,ouput=0;
// Wrong 2
if(input==1&&ouput==0){
}
```
### Correct Examples
```cpp!
double input = 0, ouput = 0;
if(input == 1 && ouput == 0){
}
```
See Tip2
## 4. Use comments to describe major sections of program or where something needs to be clarified. **10分**
### Correct Examples
```cpp!
// Name: XXX
// Date: March 8, 2023
// Last Update: March 8, 2023
// Problem statement: This C++ program read an input , and output the input // with indentation if string length of input is less than 10.
#include <iostream>
#include <iomanip>
int main()
{
// reusable variable ,place this variable outside of the loop
std::string input;
// infinite loop until cin meets EOF
while (true)
{
// read input as a string
std::cin >> input;
// break the loop if input stream meets EOF
if(std::cin.eof())
{
break;
}
// output the input string ,
// but with the indentation if string length is less than 10
std::cout << std::setw(10) << input << "\n";
}
}
```
### Wrong Examples
```cpp!
// Wrong 1, comment is not clear
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int numOfEmploy;
while (cin >> numOfEmploy)
{
string names;
long long salary;
long long award;
int maxLengthName, maxLengthSalary, maxLengthAward;
vector <string> name;
vector <long long> money;
vector <long long> reward;
for (int a = 0; a < numOfEmploy; a++)
{
cin >> names; // Alexandrescu
name.push_back(names);
cin >> salary; // 200000000
money.push_back(salary);
cin >> award; // 99999
reward.push_back(award);
}
// int zero = 0;
maxLengthName = name[0].length();
for (int b = 1; b < numOfEmploy; b++)
{
if (maxLengthName < name[b].length())
{
maxLengthName = name[b].length();
}
}
maxLengthSalary = *max_element(money.begin(), money.end());
maxLengthSalary = to_string(maxLengthSalary).length();
maxLengthAward = *max_element(reward.begin(), reward.end());
maxLengthAward = to_string(maxLengthAward).length();
for (int c = 0; c < numOfEmploy; c++)
{
cout << setw(maxLengthName) << name[c];
cout << "|" << " " << setw(maxLengthSalary) << money[c];
cout << "|" << " " << setw(maxLengthAward) << reward[c] << endl;
}
}
}
```
## 5. For names of objects (variables) you will use lower case letters and capitalize the first letter of the second and succeeding words. **10分**
There are a lot of coding style in programing language, such as below.
* Camel Case
* Snack Case
* Pascal Case
However, you are asked to use [lower camel case](https://zh.wikipedia.org/zh-tw/%E9%A7%9D%E5%B3%B0%E5%BC%8F%E5%A4%A7%E5%B0%8F%E5%AF%AB) in this class.
### Correct Examples
```cpp
int input = 1;
int inputNumber = 0;
int inputCarNumber = 3;
```
### Wrong Examples
```cpp
// Variable name is meaningless
int i;
int a;
int b;
// Different coding styles
int Input = 1;
int input_number = 0;
int InputCarNumber = 3;
```
## 6. For constants (including enumeration values), the identifier should be all capital letters (uppercase) using underscore to separate words. **10分**
### Wrong Examples
```cpp
const double pi = 3.1415926535;
enum key{
up,
down,
left,
right
};
enum common_color{
red,
green,
blue
};
```
### Correct Examples
```cpp
const double PI = 3.1415926535;
enum KEY{
UP,
DOWN,
LEFT,
RIGHT
};
enum COMMON_COLOR{
RED,
GREEN,
BLUE
};
```
## 7. The names of classes should start with an upper case letter **10分**
### Wrong Examples
```cpp
class dog
{
};
class national_taiwan_university
{
};
```
### Correct Examples
```cpp
class Dog
{
};
class NationalTaiwanUniversity
{
};
```
## 8. Use descriptive object and class names which relate the program to the problem. **10分**
### Wrong Examples
```cpp
// print a 99 multiplication
int a = 9; // What is a?
int b[9][9]; // How does b do?
for (int i = 0; i < a; i++)
{
for (int j = 0; j < a; j++)
{
b[i][j] = i * j;
cin >> i >> " X " >> j >> " = " >> b[i][j] >> endl;
}
}
```
### Correct Examples
```cpp
// print a 99 multiplication
int num = 9;
int table[9][9];
for (int i = 0; i < num; i++) // only allow use i, j, k in for loop
{
for (int j = 0; j < num; j++)
{
table[i][j] = i * j;
cin >> i >> " X " >> j >> " = " >> table[i][j] >> endl;
}
}
```
## 9. A class should be declared in a header file and defined in a source file where the name of the files match the name of the class. **5分**
```cpp
class Cat
{
};
```
### Wrong Examples
mew.h, mew.cpp
### Correct Examples
Cat.h, Cat.cpp
## 10. Indent if, for and do-while as shown **10分**
### Correct Examples
```cpp!
if()
{
if()
{
....
}
}
if(){
if(){
....
}
}
for()
{
for()
{
....
}
}
for(){
for(){
....
}
}
do{
if(){
....
}
}while();
do
{
if()
{
....
}
}while();
```
## 11. All functions must have a series of comments which state the intent and the pre and post conditions. A pre-condition is a sentence or two which states what must be true before the function is called. The post-condition states what is true after the function is called. **10分**
### Wrong Examples
```cpp!
// Wrong 1, put function description in wrong place
double getVolume(double radius)
{
// Intent: To calculate the volume of a sphere with a given radius
// Pre: The variable radius must have a value and radius > 0.
// Post: The function returns tthe volume of a sphere.
//declare variables which are needed
const double PI = 3.14159265358979323846;
double volume;
//derived value of sphere volume
//formula: 4/3 * pi * r^3
volume = (4.0 / 3.0) * PI * radius * radius * radius;
return volume;
}
```
### Correct Examples
```cpp
// Intent: To calculate the volume of a sphere with a given radius
// Pre: The variable radius must have a value and radius > 0.
// Post: The function returns tthe volume of a sphere.
double getVolume(double radius)
{
//declare variables which are needed
const double PI = 3.14159265358979323846;
double volume;
//derived value of sphere volume
//formula: 4/3 * pi * r^3
volume = (4.0 / 3.0) * PI * radius * radius * radius;
return volume;
}
```
See Tip1
## 12. Header files must contain an include guard **5分**
### Wrong Examples
Cat.h :
```cpp
class Cat
{
};
```
### Correct Examples
Cat.h :
```cpp
#ifndef _CAT_H_
#define _CAT_H_
class Cat
{
};
#endif // _CAT_H_
```
```cpp
#pragma once
class Cat
{
};
```
---
## Tip 1 : Doxygen Comments
:::info
You can use the following tool to quickly generate code documentation, such as header or function comments.
*https://marketplace.visualstudio.com/items?itemName=FinnGegenmantel.doxygenComments*
Generate header :

Generate function comment :

Setting Interface (工具->選項->Doxygen):

:::
## Tip 2 : Format on Save
:::info
You can use the following tool to automatic format on save file.
*https://marketplace.visualstudio.com/items?itemName=WinstonFeng.FormatonSave*
Format on save file

:::
## Tip 3 : Dungeon 正確繳交格式
:::info
* /Group#_ver#/Readme.txt
* /Group#_ver#/工作分配表.txt
* /Group#_ver#/submit/... All your source code and .exe should be included.
* Make sure your .exe can be execute correctly in other PCs.

:::