Should You Copy and Paste Code?

Photo by freestocks on Unsplash

Whether you’ve been programming for 5 years or 5 months, there is no way you haven’t copied a line of code or two… or two hundred. However, those brand new to programming might adopt the misconception that using someone else’s code is categorically bad. Let me get this out of the way first: there is nothing wrong with using code found online…if you do it right. Well I shouldn’t say right, there are good practices to copying code that yield much better results than others. I’m here to help shed some light on some good practices that I’ve learned.

So why do we use the code of others? If you’ve noticed after coding for at least five seconds, programming is really hard. There are thousands of packages, libraries, and modules that are required to get even the simplest application to run. If any one of these drops the ball, we get errors. But since millions of people around the world also have these same packages and such, chances are that they’ve had the same errors before. Some of them may have even solved their problem. If the problem has been solved already, we want to know how! Therefore we can save time and effort we can put back into the project. One of the cardinal sins of programming is re-inventing the wheel. As it turns out, using code written by other people is one way of avoiding that.

Now, I know that it seems like I just sang the praises of copying code. But there is one key word you’ll notice I’ve left out. Pasting. Let me draw up a scenario.

Imagine you just learned a bit of JavaScript. You have a great idea for an app about pizza delivery service. You want to make an algorithm that finds the nearest pizza restaurant to the user but you’re not sure how to do it. So you head over to Google University to find the answer. You find a snippet of code that looks like this and you paste it into your project:

var p1 = new google.maps.LatLng(6.71532762, 80.06215197);var p2 = new google.maps.LatLng(6.93234287, 79.84870747);function getShortestDistance(p1, p2) {return new Promise(function(resolve, reject) {   var request = {      origin: p1,      destination: p2,      travelMode: google.maps.TravelMode.DRIVING,      provideRouteAlternatives: true   };new google.maps.DirectionsService().route(request, function(response, status) {   var minRoute = null;for (var i = 0; i < response.routes.length; i++) {      if (minRoute === null || response.routes[i].legs[0].distance.value < minRoute.legs[0].distance.value) {      minRoute = response.routes[i];      }   }  resolve(minRoute);});});}getShortestDistance(p1, p2).then(function(result) {   document.getElementById('distance').innerHTML = 'Distance : ' +   result.legs[0].distance.text;});

After pressing the run button, this guy pops up:

Failed to compilesrc/App.js   Line 73:16:  'google' is not defined  no-undef   Line 74:14:  'google' is not defined  no-undef   Line 81:19:  'google' is not defined  no-undef   Line 84:9:   'google' is not defined  no-undef Search for the keywords to learn more about each error.

Uh oh. I don’t think anyone’s getting that pizza in 30 minutes or less.

If we weren’t working at all with Google Maps before copying this, your code likely has no idea what is. The solution found online was made for a highly specific problem. We need to first understand how much of that highly specific problem overlaps with your own. This leads to our first good practice: analyze and abstract.

What do I mean by analyze and abstraction? If we return to our pizza app, the problem we had was finding pizza restaurants near the user. Putting this exact wording into Google might won’t show us what we want. It likely won’t even give us JavaScript code. First we have to break the problem up into smaller chunks. For example we can break “Find nearest Pizza place” into:

· Get the user’s location

· Get a list of pizza places

· Find shortest distance between user and pizza places

Next, we need to abstract. By abstract, I mean we must generalize our problem so that it’s easier to search. For example, if you’re baking a cake for the first time, you wouldn’t need to specify your oven make and model for cooking instructions. Take enough of the specifics out to increase your chances of finding someone with the solution. To that end, we can abstract out “pizza places” into just “restaurants” since there might be a solution where pizza restaurants were not the target.

· Get the user’s location

· Get a list of restaurants

· Find shortest distance between user and restaurants

Nice! These are much more searchable terms that will likely yield something we can work with.

The next step is one of the most important disciplines a programmer should know. Once you find a solution, you must understand what you’ve found before you use it. Let’s see an example. This is the code you found the get the user’s location:

var x = document.getElementById("demo");function getLocation() {   if (navigator.geolocation) {      navigator.geolocation.getCurrentPosition(showPosition);   } else {      x.innerHTML = "Geolocation is not supported by this browser.";   }}function showPosition(position) {    x.innerHTML = "Latitude: " + position.coords.latitude +"<br>Longitude: " + position.coords.longitude;}

For the most part the code is readable. The function getLocation() should be what you want out of this right? Well, how do we know that this is what we want? I mean, what data does this even output? If you’re familiar with only vanilla JavaScript, you might recognize everything in the code snippet except for this “navigator”. If you have no idea what this is, you can make one of two options:

· Don’t use this code

· Find out what it does!

Just searching for “JavaScript navigator” leads you to this page.

Here you can read up on what the Navigator object does. We can find out what is. Continuing this process recursively leads you to the Geolocation object, then to the Coordinates property:

Here we see that we call .latitude to get some string with the latitude of the coordinates in degrees. Whew! Now that all that is over, we finally know exactly what our code does. So we can use it in our project!

As you’ll notice, this process took some time. However, over that time we learned a ton about how JavaScript works and how to use geolocation that’s built-in! And this was just one of the broken-down chunks of our bigger problem. I know you’re not going to believe me but prior to writing this, I had no idea how to solve this problem. I didn’t know the Navigator object even existed. But by following the process, I was able to find out completely on the fly! This is the same power you can use in your own projects.

So to recap:

1. Identify the problem

2. Analyze (break it down)

3. Abstract (generalize)

4. Search

5. Understand the solution

And don’t build a pizza app. Just use Google Maps.