That being said, there are a few safe ways to reuse portions of code that is essentially guaranteed not to cause unintended glitches down the road (as opposed to those intended glitches that developers like to put in their code for fun!)
Here are some suggestions to effectively copy code:
1. Copy smaller portions. Instead of copying large blocks of code with many variables logical structures and the like, copy the methods that you will reuse a lot, and paste those whenever needed.
2. Write in example basic types and classes that will cause errors unless given relevant names. This is probably the most effective suggestion. The most common problem that I have found in copying code is when I copy a variable from one portion of the code elsewhere, and then forget to change its name to fit the context.
For example,
Let's say you have a class that parses the html of a web page, called parser.
Parser parser = new Parser(html);
you grab some data
parser.MoveToEndOf("");
");
string tableData = parser.Selected;
Then you go to another page and want to scrap the same data there;
Parser parser2 = new Parser(newHtml);
Then you paste your code
parser.MoveToEndOf("");
");
Forgetting that your parser for the new page is called parser2, not parser. Well, you may have saved yourself 2 minutes of time by pasting that code. But, in the end you will spend 20 minutes to a half hour hunting down where your code is going wrong.
Instead if you were to create some code like
exampleParser.MoveToEndOf("");
");
and then paste that around, the code would not compile until you changed the name. It's the same reason why some people put
while (1 ==2)
in their code to make sure there is never an infinite loop until they have tested their logic.
3. Copy the logic portions of code that have no variables in them . Sometimes copying your logical structure will save you the care of having to rethink how to logically go about doing something, and focus on the details.
Conclusion
This article is designed to make the programmer rethink the way they code, and to take the long path at first so that code is built without bugs. Copying code from one portion to another is a sure way to introduce bugs into your code that will be hard to catch at a glance, since the variables you copy are existing ones. Change the names or don't copy at all. In the end you will be a more efficient coder.
No comments:
Post a Comment