Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do programmers practice code reuse

Tags:

code-reuse

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 edit, copy the code that sets the datagridview and edit. I am aware of the phrase code reuse, but I have not actually used it. How can i utilize code reuse so that I don't have to copy and paste the database code and the datagridview code.,

like image 670
user26087 Avatar asked Oct 26 '08 08:10

user26087


2 Answers

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.

like image 134
Colin Barrett Avatar answered Nov 02 '22 06:11

Colin Barrett


Put the code into a routine and call the routine whenever you want that code to be executed.

like image 4
Paige Ruten Avatar answered Nov 02 '22 06:11

Paige Ruten