Coding Practice: Cut and Paste Code

Coding Practice: When is it okay to cut and paste code?
The presence of code that is cut and pasted is a good indication that functionality can be extracted to a common library, class, or method.  It is also a common source of hard to   read code and bugs.

Here is an example of cut and paste resulting in repetition that you want to avoid:

…
for (int Index = 1;   Index <= numberOfPages; Index++)
{
   docs.SetPageSize(reader.GetPageSizeWithRotation(Index));
   //…
   content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
}

if (!string.IsNullOrEmpty(CopiesPath))
{
   PdfReader imageReader = new PdfReader(CopiesPath);
   numberOfPages = imageReader.NumberOfPages;
   for (int Index = 1; Index <= numberOfPages; Index++)
   {
      docs.SetPageSize(imageReader.GetPageSizeWithRotation(Index));
      //…
      content.AddTemplate(importedPage, 1f, 0,   0, 1f, 0, 0);
   }
}

Quote:
“Duplication may be the root of all evil in software.  Many software practices have been   created for the purpose of controlling or eliminating it.”
–            Robert Martin

Application:
In practice, when working within your own code, you will cut and paste frequently to reduce the amount of typing you are doing.  Just keep in mind that every time you do this, it   should trigger a thought on whether or not you are violating the DRY (Don’t   Repeat Yourself) principle, and perhaps you should be creating a shared class or method for what you are doing.

Sometimes you will want to use a block of code as a template.  When you do this, be very careful to make sure you understand what each line of code is doing that you are copying and make sure you rename any variables and methods to fit into the context you   are in.  This is a common root cause behind some of our more confusing and buggy code.

References:
Clean   Code: A Handbook of Agile Software Craftsmanship

About Chris VanHoose

Principal Software Architect at CT Lien Solutions
This entry was posted in Software Architecture and tagged , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.