How do programmers practice code reuse

前端 未结 14 1274
天涯浪人
天涯浪人 2021-02-13 14:14

I\'ve been a bad programmer because I am doing a copy and paste. An example is that everytime i connect to a database and retrieve a recordset, I will copy the previous code and

14条回答
  •  情话喂你
    2021-02-13 14:35

    The essence of code reuse is to take a common operation and parameterize it so it can accept a variety of inputs.

    Take humble printf, for example. Imagine if you did not have printf, and only had write, or something similar:

    //convert theInt to a string and write it out.
    char c[24];
    itoa(theInt, c, 10);
    puts(c);
    

    Now this sucks to have to write every time, and is actually kind of buggy. So some smart programmer decided he was tired of this and wrote a better function, that in one fell swoop print stuff to stdout.

    printf("%d", theInt);
    

    You don't need to get as fancy as printf with it's variadic arguments and format string. Even just a simple routine such as:

    void print_int(int theInt)
    {
        char c[24];
        itoa(theInt, c, 10);
        puts(c);
    }
    

    would do the trick nickely. This way, if you want to change print_int to always print to stderr you could update it to be:

    void print_int(int theInt)
    {
        fprintf(stderr, "%d", theInt);
    }
    

    and all your integers would now magically be printed to standard error.

    You could even then bundle that function and others you write up into a library, which is just a collection of code you can load in to your program.

    Following the practice of code reuse is why you even have a database to connect to: someone created some code to store records on disk, reworked it until it was usable by others, and decided to call it a database.

    Libraries do not magically appear. They are created by programmers to make their lives easier and to allow them to work faster.

提交回复
热议问题