code 작성 rules!

markyang92·2021년 8월 14일
0

clean code

목록 보기
4/4

전역 변수는 함수로 활성화


함수 설명

C

/**
 * @brief        Features of the function
 * @param hist   color distribution histogram
 * @param median average color distribution histogram
 * @return       sum of squared errors
 */

static double frame_sum_square_err(const int *hist, const double *median)
{
    int i;
    double err, sum_sq_err = 0;

    for (i = 0; i < HIST_SIZE; i++) {
        err = median[i] - (double)hist[i];
        sum_sq_err += err*err;
    }
    return sum_sq_err;
}

console의 예

console.h

  • console.h
/** @file console.h
 *  @brief Function prototypes for the console driver.
 *
 *  This contains the prototypes for the console
 *  driver and eventually any macros, constants,
 *  or global variables you will need.
 *
 *  @author Harry Q. Bovik (hqbovik)
 *  @author Fred Hacker (fhacker)
 *  @bug No known bugs.
 */

#ifndef _MY_CONSOLE_H
#define _MY_CONSOLE_H

#include <video_defines.h>

/** @brief Prints character ch at the current location
 *         of the cursor.
 *
 *  If the character is a newline ('\n'), the cursor should
 *  be moved to the next line (scrolling if necessary).  If
 *  the character is a carriage return ('\r'), the cursor
 *  should be immediately reset to the beginning of the current
 *  line, causing any future output to overwrite any existing
 *  output on the line.  If backsapce ('\b') is encountered,
 *  the previous character should be erased (write a space
 *  over it and move the cursor back one column).  It is up
 *  to you how you want to handle a backspace occurring at the
 *  beginning of a line.
 *
 *  @param ch the character to print
 *  @return The input character
 */
int putbyte( char ch );

/** @brief Prints the string s, starting at the current
 *         location of the cursor.
 *
 *  If the string is longer than the current line, the
 *  string should fill up the current line and then
 *  continue on the next line. If the string exceeds
 *  available space on the entire console, the screen
 *  should scroll up one line, and then the string should
 *  continue on the new line.  If '\n', '\r', and '\b' are
 *  encountered within the string, they should be handled
 *  as per putbyte. If len is not a positive integer or s
 *  is null, the function has no effect.
 *
 *  @param s The string to be printed.
 *  @param len The length of the string s.
 *  @return Void.
 */
void putbytes(const char* s, int len);

/** @brief Changes the foreground and background color
 *         of future characters printed on the console.
 *
 *  If the color code is invalid, the function has no effect.
 *
 *  @param color The new color code.
 *  @return Void.
 */
void set_term_color(int color);

/** @brief Writes the current foreground and background
 *         color of characters printed on the console
 *         into the argument color.
 *  @param color The address to which the current color
 *         information will be written.
 *  @return Void.
 */
void get_term_color(int* color);

/** @brief Sets the position of the cursor to the
 *         position (row, col).
 *
 *  Subsequent calls to putbytes should cause the console
 *  output to begin at the new position. If the cursor is
 *  currently hidden, a call to set_cursor() must not show
 *  the cursor.
 *
 *  @param row The new row for the cursor.
 *  @param col The new column for the cursor.
 *  @return Void.
 */
void set_cursor(int row, int col);

/** @brief Writes the current position of the cursor
 *         into the arguments row and col.
 *  @param row The address to which the current cursor
 *         row will be written.
 *  @param col The address to which the current cursor
 *         column will be written.
 *  @return Void.
 */
void get_cursor(int* row, int* col);

/** @brief Hides the cursor.
 *
 *  Subsequent calls to putbytes must not cause the
 *  cursor to show again.
 *
 *  @return Void.
 */
void hide_cursor();

/** @brief Shows the cursor.
 *
 *  If the cursor is already shown, the function has no effect.
 *
 *  @return Void.
 */
void show_cursor();

/** @brief Clears the entire console.
 *  @return Void.
 */
void clear_console();

/** @brief Prints character ch with the specified color
 *         at position (row, col).
 *
 *  If any argument is invalid, the function has no effect.
 *
 *  @param row The row in which to display the character.
 *  @param col The column in which to display the character.
 *  @param ch The character to display.
 *  @param color The color to use to display the character.
 *  @return Void.
 */
void draw_char(int row, int col, int ch, int color);

/** @brief Returns the character displayed at position (row, col).
 *  @param row Row of the character.
 *  @param col Column of the character.
 *  @return The character at (row, col).
 */
char get_char(int row, int col);

#endif /* _MY_CONSOLE_H */

console.c

  • console.c
/** @file console.c
 *  @brief A console driver.
 *
 *  These empty function definitions are provided
 *  so that stdio will build without complaining.
 *  You will need to fill these functions in. This
 *  is the implementation of the console driver.
 *  Important details about its implementation
 *  should go in these comments.
 *
 *  @author Harry Q. Bovik (hqbovik)
 *  @author Fred Hacker (fhacker)
 *  @bug No know bugs.
 */

#include <console.h>

int
putbyte( char ch )
{
  return ch;
}

void
putbytes( const char *s, int len )
{
}

void
set_term_color( int color )
{
}

void
get_term_color( int *color )
{
}

void
set_cursor( int row, int col )
{
}

void
get_cursor( int *row, int *col )
{
}

void
hide_cursor()
{
}

void
show_cursor()
{
}

void
clear_console()
{
}

void
draw_char( int row, int col, int ch, int color )
{
}

kernel.c

  • kernel.c
/** @file kernel.c
 *  @brief An initial kernel.c
 *
 *  This file contains the kernel's
 *  main() function.
 *
 *  You should add your own comments to
 *  replace this one.
 *
 *  This is where you will eventually setup
 *  your game board and have it run.
 *
 *  @author Harry Q. Bovik (hqbovik)
 *  @author Fred Hacker (fhacker)
 *  @bug No known bugs.
 */

/* -- Includes -- */

/* libc includes. */
#include <stdio.h>        /* for lprintf_kern() */

/* multiboot header file */
#include <multiboot.h>    /* for boot_info */

/* memory includes. */
#include <lmm.public.h>  /* for lmm_remove_free() */

/* x86 specific includes */
#include <x86/seg.h>     /* for install_user_segs() */
#include <x86/pic.h>     /* for pic_init() */
#include <x86/base_irq.h> /* for base_irq_master/slave */

/*
 * state for kernel memory allocation.
 */
extern lmm_t malloc_lmm;

/*
 * Info about system gathered by the boot loader
 */
extern struct multiboot_info boot_info;


/** @brief Kernel entrypoint.
 *
 *  This is the entrypoint for your kernel.
 *  You will use this to test and debug your
 *  drivers and it will eventually hold the
 *  code for your game.  Right now, it is
 *  A tight while loop.
 *
 * @return Should not return
 */
int main()
{
    /*
     * Tell the kernel memory allocator which memory it can't use.
     * It already knows not to touch kernel image.
     */
    lmm_remove_free( &malloc_lmm, (void*)USER_MEM_START, USER_MEM_SIZE );
    lmm_remove_free( &malloc_lmm, (void*)0, 0x100000 );

    /*
     * Install interrupt handlers here.
     */

    /*
     * initialize the PIC so that IRQs and
     * exception handlers don't overlap in the IDT.
     */
    pic_init( BASE_IRQ_MASTER_BASE, BASE_IRQ_SLAVE_BASE );

    lprintf_kern( "Hello from a brand new kernel!" );

    while(1);

    return 0;
}

Java

Class

/** 
 * Javadoc 테스트용 클래스 * 
 * @see Sample08_01 
 */ 
public class Sample08_02 { 
    /** 
     * 폭 반환 
     * 
     * @return 폭 
     * @see Sample08_01#setSize(int, int) 
     * @see #getHeight() */ 
    public int getWidth() { 
        return 0; 
    } 
    /** 
     * 높이 반환 
     * 
     * @return 높이 
     * @see Sample08_01#setSize(int, int) 
     * @see #getWidth() 
     */ 
    public int getHeight() { 
        return 0; 
    }
}

하나의 함수에는 하나의 기능만!

  1. 함수 하나에도 여러개로 나눠야한다.
def create_user(email, password):
    isValid()
    
    getFromInfoDB()
    
    ...

하나의 클래스는 하나의 책임을 가지자!

SRP

  • 안좋은 예: 하나의 클래스가 너무 많은 역할을 수행한다
class Store:
    def communicate_user():
        ...
    def manage_product():
        ...
    def manage_money():
        ...
  • 책임을 나눠 Manager 클래스에 책임을 전가한다.
class CounterManager:
    def communicate_user():
        ....


class ProductManager:
    def manage_products():
        ....
        
class Owner:
    def manage_money():
        ....


class Store:
    def __init__(counter_manager: CounterManager, product_manager: ProductManager, owner: Owner):
        self.counter_manager = counter_manager
        self.product_manager = product_manager
        self.owner = owner
    
    def sell_product():
        # 파는건 카운터 매니저 한테 전가
        self.counter_manager.communicate_user()
        self.product_manager.manage_products()

추상화

  • 안좋은 예:
class Developer:
    def coding(self):
        print("코딩 하기")

class Designer:
    def design(self):
        print("디자인 하기")

class Analyst:
    def analyze(self):
        print("분석 하기")


class Company:
    def __init__(self, employees): # 구체 클레스에 의존적임
         self.employees = employees
    
    # employee가 다양해질수록 코드를 계속 변경해야한다.
    def make_work(self):
        for employee in self.employees:
            if type(employee) == Developer:
                employee.coding()
            elif type(employee) == Designer:
                employee.design()
            elif type(employee) == Analyst:
                employee.analyze()

profile
pllpokko@alumni.kaist.ac.kr

0개의 댓글