A Beginners Guide to Abstraction in Object-Oriented Programming

When you eat a burrito, every one of your taste receptors sings with joy. Each bite brings in a combination of different flavor types, like salty, sweet, spicy, and umami. Every bite after that tastes slightly different as a new collection of ingredients join their flavors together.

You may have read the ingredients from the menu, but you don’t know exactly how the salsa gets made. The seasoning they use on their veggies could be a secret blend. You don’t need to know every exact ingredient, though. It’s enough to know that it’s delicious.

The ingredients you know, like plain white rice, are concrete. The other elements are abstract. You know it’s salsa, but what kind? Or, if someone just hands you a burrito out of nowhere, then the whole burrito is abstract.

Abstraction in the Abstract

Along with inheritance, abstraction is an important concept in object-oriented programming. The theory is that every object should deliver simple and predictable results. Objects should also only share what needs to be shared.

Abstraction Keeps Code and Data Hidden When Appropriate

You can think of a burrito as an object. Inside the burrito, you have several other objects, like beans, rice, cheese, and hot sauce. The beans may have been seasoned. The cheese could be a blend. And the hot sauce might be a combination of peppers aged in vinegar.

You don’t need to know how all the ingredients in a burrito were made. And in the case of hot dogs, you probably don’t want to know. All that matters is that it doesn’t fall apart when you eat it and that it’s super tasty.

Abstraction Is Closely Tied To Encapsulation

It’s the same thing with programming objects. When you instantiate an object (create it from a class), it’s like ordering a burrito from the food truck counter. You have access to some data, but not all. You don’t need to know how the object works, as long as the functions return the correct data. Here is a burrito in JavaScript/Typescript:

class CheeseBlend {
private _ingredients = ["Colby Jack", "Cheddar", "Manchego"];
get ingredients() {
return "melted cheese";
}
}
class SecretSalsa {
private _ingredients = ["onions", "tomatoes", "cilantro", "Guatemalan Insanity Peppers"];
get ingredients() {
return "it's a secret";
}
}
class Burrito {
private _beans = "beans";
private _rice = "rice";
private _cheese: CheeseBlend = new CheeseBlend();
private _salsa: SecretSalsa = new SecretSalsa();
get cheese() {
return this._cheese.ingredients;
}
get salsa() {
return this._salsa.ingredients;
}
}
let burro = new Burrito();
console.log(burro.cheese);
console.log(burro.salsa);

You can play with this code at the TypeScript sandbox.

In the above example, the salsa and cheese ingredients are abstracted away. First, they’re encapsulated, to hide the special ingredients. Then getters are added to access the ingredients. But the ingredients only return an abstract representation of what they really are.

Abstraction in the Concrete

Abstraction is more than a concept, though. Classes can also be abstract. That means that they can define other classes. But they can’t be instantiated themselves.

Why Classes Should Sometimes Be Abstract

Imagine that you go to a restaurant and sit down. The waiter hands you a menu. You open it to find that there’s only one item: food.

That’s pretty abstract. Would you order it? Would you eat it? You probably wouldn’t. Saying something is food is not enough. It needs breaking down into something more concrete.

What about pasta? Well, that is a more specific type of food. And we know that it probably has noodles and sauce. But there are a lot of different kinds of pasta out there, so it’s still abstract.

What Is Abstract and What Is Concrete?

Fettuccine Alfredo is a concrete example of both food and pasta. The same thing applies to classes. Not every class should be instantiated. Some classes should only define the structure of other classes.

Here’s an example with an abstract Food class, and a child MacadamiaNuts class:

abstract class Food {
constructor(public name: String) {}
abstract totalCalories(): number;
abstract description(): string;
abstract flavor(): string;
}
class MacadamiaNuts extends Food {
constructor() {
super("One Cup of Macadamia Nuts");
}
totalCalories() {
return 962;
}
description() {
return "A nut from Hawaii.";
}
flavor() {
return "rich, buttery, and nutty";
}
}
let nuts = new MacadamiaNuts();
console.log(nuts.name)
console.log(nuts.description())

Here’s the code.

Abstract classes tell other classes how they’re supposed to behave. In the example above, if you’re going to be a food class, you must have functions that allow access to your name, flavor, description, and calories.

Notice that the MacadamiaNuts class extends Food. That is saying that MacadamiaNuts agrees to follow the rules of Food. Also, notice that constructor calls super. That command instantiates the parent class before the constructor instantiates MacadamiaNuts.

If you’re learning to program, you can have more fun with these programming games.

Abstraction Practice

  • Visit the link above and use the sandbox to create an abstract class called Soup.
  • Create a concrete child of the Soup class, called Cereal.
  • Use console.log to test your code. What happens if your Cereal class is missing one of the functions defined in Soup?

But What Is the Point of a Class You Can’t Instantiate?

At first, abstract classes may seem unnecessary. After all, you can’t actually use them to make an object. And it’s not like they pass down their functions. Functions have to be rewritten in every child class.

There are two main reasons you need abstract classes. They keep your code consistent, and they make sure that other developers also write consistent code. You won’t always be working alone. The whole team needs to follow the same rules. You can learn more from the TypeScript documentation on abstract classes.

Source: makeuseof.com

Related posts

GDDR6 vs. GDDR6X vs. GDDR7: What’s the Difference?

MSI Claw Review: Intel’s Debut Gaming Handheld has Big Potential

Copilot Is the Best Way to Use GPT-4 Turbo for Free