Abstraction: Making Code Readable
Abstraction, we use it in everyday life. It helps us quickly understand what other people are talking about. So why not use it for code and make it that much more readable.
Any language is based around abstraction. We can take one word like “Apple” and know exactly what the person is talking about. If someone were to say “A red spherical fruit with a stem sticking out the top” sure you could probably guess what it is, but wouldn’t it be easier just to say “Apple”? This happens all to often, you might see something like this:
1 2 3 4 5 6 7 8 9 10 | var energyReserves = 1; var food = 2; var steps = 1; var loc = 0; if (energyReserves < 2.5){ energyReserves += food; }else{ loc += steps; } |
Okay who knows what the heck this program is trying to do. You can see programically what it does, but why is it doing it, in what context is it being used. Just unclear the purpose of the code. How do we make it better?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | var energyReserves = 1; var food = 2; var steps = 1; var loc = 0; if (feelingHungry(energyReserves)){ eat(food); }else{ walkForward(steps); } function feelingHungry(energy){ if (energy < 2.5){ return true; }else{ return false; } } function eat(food){ energyReserves += food; } function walkForward(numOfSteps){ loc += numOfSteps; } |
Now you can see it reads almost in plain English. If it’s feeling hungry than eat otherwise start the walkin’. The great thing is you can change anything in the functions and it won’t affect the logic. Say you want to change the eat function so there is a 30 line mathematical equation to figure out how many calories you’re actually getting out of it. Go right ahead. Sure the function gets bigger, but it’s encapsulated so you know it shouldn’t be affecting any of your other code. You’ll also be able to reuse the code in other projects saving you some serious development time.













