Abstraction Vs Encapsulation

This is one of the most frequently asked and discussed question and I found it really confusing in my early stages of programming. Both are indeed very much different.

Abstraction

Abstraction represents taking out expected behaviour from an object. It can be achieved by using protocol (abstract class or interface in C# or Java). It is just about exposing behaviour what is expected from it.

Example: Pizza Hut! when you order pizza you only care about pizza to be delivered at your door, you don’t care how it’s cooked. Abstraction means to define methods whose purpose is to be extended/implemented only, I mean you need to be aware of that once you order pizza you will receive it hot and tasty.

Advantages of Abstraction

Abstraction lets you focus on what the object does instead of how it does.

Encapsulation

Encapsulation is a way to hide functionality (Methods) & Data (Variables) in a Class, which is not usable by other object or it may not be safe if accessible. It can be achieved by access modifiers like public, protected or private.

Example:

Suppose one class  has a method called doIncreaseCount()   which increments count global variable every hour and this variable is public, so some other object which have access to this object can change the value in between intentionally.  Then method doIncreaseCount() will not be able to provide desired result.

Following are the ways to make variable private in Objective C.

Inside .m file

@interface LoginManager{

NSMutableString *_mAuthenticationResult;

NSString *_mUsername;

}

OR

Inside .h file

@interface LoginManager{

@property (nonatomic, strong, readonly) LoginViewController *loginViewController;

}

OR

Inside .h file

@interface LoginManager{

@private

NSString *username;

}

and no @property definition, if you provide @property (nonatomic, strong) LoginViewController *loginViewController it will still be visible to other objects.

Advantages of Encapsulation

Encapsulation helps make code more flexible and maintainable by keeping related data in a single unit and on change it will not affect other module.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s