Abstraction and Encapsulation
There are 2 main paradigms for programming languages now: imperative and object oriented. While these are vastly different paradigms, they do the exact same thing: changing and moving around some numbers. Your "Player" object doesn't really exists. Its numeric representation is just somewhere in the RAM and you just can only access it if you have to reference(pointer) to that object. But humans don't think this way. Real world doesn't work this way. So we use abstraction to make somewhat believable object that represents real world things. And this is the core concept of object oriented languages(imperative languages also have abstraction, but it's not their core concept).
Abstraction is reducing real things down to concepts. Real things are complex. They are made of atoms(and even more small particles if you go further) and even the small things you can see in daily life consist of billions and trillions of atoms. But computers can't represent that. They only understand numbers. So we do what we must and abstract those atoms into some numbers.
If you were to make a sword in a game, what would it need? Most people would think graphic, damage, animation, hit sound or even durability. But real swords don't have any of that. You can't "deal 10 damage" with your sword in real life. It just cuts things. The damage that we gave to the sword is abstraction. We see that when a real sword is used to attack things, they take some form of physical damage. And each sword swing does roughly about the same damage. If we extend this little further, various things can take various amount of damage until it loses its core features. So we make weapons "deal damage" and make enemies "have health" and "die" in games. So weapon's code should look something like this:
public class Weapon{
public float damage;
public void Update(){
Enemy enemy = // detect collision
if(enemy != null){
enemy.health -= damage;
if(enemy.health <= 0){
enemy.Die();
}
}
}
}
And it works fine. Player can damage enemies with the weapon. And this could be the only thing needed for a small game.
But say, you want to add an enemy with defense. Now things become complex. You have to find every line that says enemy.health -= damage; or similar and change all of them into something like this:
enemy.health -= damage;
// change above to
damage -= enemy.defense;
enemy.health -= damage;
And you might miss some and create a very hard to find bug. After the agony of fixing those bugs, you also find out some enemies need special interaction when they get damaged. There's got to be a easier way to do this. And there is. It's encapsulation.
Encapsulation is a subtype of abstraction. All encapsulations are abstraction, but not all abstractions are encapsulation. Let's see the new weapon code with encapsulation
public class Weapon{
private float damage;
public void OnCollision(Enemy enemy){
enemy.Damage(damage);
}
}
Comments
Post a Comment