Quality Code

Code formatting

void Person::eat(food) {
    std::cout << "Nom nom nom!" << std::endl;
    this->weight++;
    
    if(this->likes_food(food)) {
        this->happy++;
    } else {
        this->happy--;
    }
}
void Person::eat(food) {
        std::cout << "Nom nom nom!" << std::endl;
this->weight++; if(this->likes_food(food)) {
this->happy++;
    }else {
           this->  happy--;}}

Code formatting

Naming

def max_consecutive(a):
    c = 1
    mc = 0
    for a in range(len(items) - 1):
        if a[index] == a[index+1]:
            c += 1
        elif c > mc:
            mc = c
            c = 1
    return mc

Boolean function/fields

is_dead = True
is_fat = False
is_open = True 
can_proccess = False

Class vars naming

class CoffeeMachine:
    def __init__(self):
        self.coffe_machine_water_amount = 0

hack_coffee_machine = CoffeMachine()
print(hack_coffee_machine.coffe_machine_water_amount)

print(hack_coffee_machine.water_amount)

Comments and documentation

#This sums two digits
def sum(digit_one, digit_two):
    return digit_one + digit_two

Functions do only one thing or raise error

def buy_water(store, water):
    if not store.have_water:
        raise Exception('No water in the store')
    
    self.money -= water.price
    self.items.append(water)

Functions do only one thing

  • They are easy for testing

  • They are reusable 

  • They are more abstract

Don’t use magic numbers and strings:

def is_fat(self):
    return self.weight > 100

Use static constants:

def is_fat(self):
    return self.weight > Person.NORMAL_WEIGHT

Variables should have single prpose

def get_smaller_elements(array):
    biggest_number = 0
    for element in array:
        if biggest_number > element:
            biggest_number = element

    biggest_number /= len(array)

    result = []
    for element in array:
        if element < biggest_number:
            result.append(element)

    return result

Spaghetti code

def dfs():
    graph_file = open('graph_file.txt', 'w')
    graph = graph_file.read()
    start = raw_input("Enter a start vertex")

    visited, stack = set(), [start]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

loose coupling

def dfs(graph, start):
    visited, stack = set(), [start]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

loose coupling

Quality Code

By Hack Bulgaria

Quality Code

Уводната лекция за курса по Програмиране 0

  • 1,387