Showing posts with label Object Oriented Programming & Systems (OOPS). Show all posts
Showing posts with label Object Oriented Programming & Systems (OOPS). Show all posts

23 September 2018

difference between encapsulation and abstraction

Abstraction and Encapsulation are the 2 of the 4 building blocks in OOPS. In the previous posts, I have already blogged in a separate post on Abstraction and Encapsulation . In this blog post let's try to understand what is the difference between encapsulation and abstraction.

Encapsulation is all about building the functionality of an entity inside a class hiding the complexity so that users of such classes can use them without worrying about how the stuff has been implemented.

Where as abstraction is all about what a class provides to the developers. With abstraction developers only look at what a class provides looking at the interfaces/abstract classes it implements.

30 June 2018

Encapsulation in OOPS

Encapsulation is one of the 4 building blocks of OOPS. I have already written about other 3 OOPS concepts namely Inheritance, Polymorphism and Abstraction. In this blog post, we will discuss Encapsulation is OOPS.

What is dictionary meaning of Encapsulation

Encapsulation means "Enclose something in or as if in a capsule" (as per "oxforddictionaries.com" dictionary).

What is Encapsulation in OOPS

Having understood the meaning of Encapsulation, in general, let's understand what does it mean in the Object-Oriented programming world.

Image Courtesy: shutterstock


  • Wikipedia says Encapsulation in OOPS is data hiding of the data members of the class like properties, fields etc. To implement this definition of data hiding you will make use of access specifiers.
  • As per the other definition, Encapsulation is all about bundling the data with the methods which operate on that data.

    In other words Encapsulation is about putting together methods/functions and data members all in one place called class so that users of those classes can easily make use of it.

Why we need Encapsulation

Having understood what is Encapsulation, now let's turn our attention into what is the advantage of it and what Encapsulation brings to the table in the object-oriented programming world.

With Encapsulation users of the classes need not worry about what how class provides its functionality. Similar to a real-world capsule. As a patient you really no need to know what is inside a capsule, that is something your physician worries about it and prescribe it to you.

As a user of the SmtpClient class in the .NET framework which sends a MailMessage to a recipient address, you don't need to know about how does it actually sends an email. The email sending logic is encapsulated inside the SmtpClient class (by an author of the class i.e., Microsoft)

26 December 2015

difference between value type and reference type

Recently I got a chance to talk to a bunch of entry level professionals working on a software development project. During the discussion, a question came up on what is value type, what is a reference type and what is the difference between the two. Answer I got for those questions weren't satisfactory.

So at that moment I thought let me blog on this topic, so that other similar students can read and enhance their knowledge on difference between the value type and reference types in simple words with relevant tutorial examples.

What is a value type?

When you pass a variable to a method, if the variable value gets passed instead of the variable itself, then they are called value types. Didn't understand?. Don't worry, let's consider an example.

public static void Main(string[] args)
{
int salary = 1000;
IncrementSalary(salary, 100);
Console.Writeline(salary);
}

public statis IncrementSalary(int salary, int byAmount)
{
salary = salary + byAmount;
}

What is the output of the above C#.NET example?

  • Is it 1000?
  • Is it 1100?

Actual output

1000

If your answer was 1100, then your understanding of value types is incorrect. Read further to understand, "What is a value type"?

When you call a method "IncrementSalary" and the pass the variable "salary" to it, actually an another variable, which is

  • pointing to a different memory location than that of salary variable
  • AND
  • having the same value of the salary variable

is passed.

So whatever variable value gets updated inside the "IncrementSalary" method, the value stored in the new memory location will get updated. Hence updates to the variable will not be reflected in the caller method's variable (i.e., Main() method in this case)

Examples of value types in .NET C#

More or less all structures, i.e, int, decimal, DateTime, long etc

What is reference type?

When you pass a variable to a method, if the variable reference gets passed to the passed to the method parameter then they are called reference types. Let's consider a sample C# .NET tutorial example.

public class PromotionOffer{
public int Discount {get;set;}
}

public static void Main(string[] args
{
PromotionOffer offer = new PromotionOffer();
offer.Discount = 10;
IncrementOfferDiscount(offer, 10);
Console.Writeline(offer.Discount);
}

public static IncrementOfferDiscount(PromotionOffer offer,
                                     int byPercenatge)
{
offer.Discount += byPercentage;
}

What is the output of the above C#.NET example?

  • Is it 10?
  • Is it 20?

Actual output

20

If your answer was 10, then your understanding on reference type is incorrect. Read further to understand, "what is a reference type".

When you call the method "IncrementOfferDiscount" and pass in the promotionOffer variable, the method gets the same reference of the variable used by the calling method(in this case, it is Main() method). So whenever you update the properties of the reference type variable in the method called, it will update the same copy of the values held by the calling method.

So after you call the IncrementOfferDiscount() method and print the Discount of promotionOffer object, you will see the updated value 20.

Examples of reference types in .NET C#

All inbuilt classes in the .NET framework and custom classes you define are reference types.

Now I hope you understood what is value type, what is reference type and the difference between value type and reference type.

Note:
  • The built-in String class is a reference type, but .NET framework treats it differently, because of string intern concept(which is same in JAVA as well)
  • The value types can be passed to a method as reference types using out and ref keywords. Learn more about ref and out keywords in C# .NET by reading my another post "ref v/s out in .NET"

11 April 2015

prefer composition over inheritance

During design discussion have you heard about the phrase "prefer composition over inheritance" and wondered what does that mean? In this post let's see what actually means when your architect says "prefer composition over inheritance" .

Inheritance is one of the building blocks of OOPS. We have been taught to use inheritance in class designs. Using inheritance, you also gain code reuse. Code re-usability is definitely a good coding practice. Then what's the phrase "prefer composition over inheritance" and what's wrong with inheritance?

Actually there is nothing wrong with inheritance. Inheritance should be used to define a hierarchical relationship. If you don't see a hierarchical relationship between two entities, then don't use inheritance just to gain code re-usability. Your motive to use inheritance shouldn't just code re-usability.

An example showing use of composition over inheritance

Let's consider Televisions. Television shows running pictures, produces sound and gets various channels. In real-world Television make use of display screens to show pictures, speakers to produce sound and set-top box to get channels. So Television should have all these functions.

There are two options for Television to exhibit its capabilities:

  • OPTION #1: Television class can derive from Screen display, Speakers and set of box, etc to get their capability.
  • OPTION #2: Instead compose Television class to get required functionality.
class diagram showing prefer compoistion over inheritance

Disadvantage of using inheritance to build Television class

Inheritance is a IS A relationship. In real-world Television set IS not just a speaker. Saying Television IS A screen display doesn't make much sense. Television is much more than above-said capabilities. So making Television class to derive from individual specialized classes doesn't establish a proper IS A relationship.

Advantage of preferring object composition over inheritance to build Television

Composition represents HAS A relationship. Applying this to television it makes sense to say, Television HAS A screen display, Television HAS A speaker and HAS A set of box. Here COMPOSITION represents the relationship better between the Television and the individual devices it makes use of. And hence the saying "PREFER COMPOSITION OVER INHERITANCE".

Having said "prefer composition over inheritance", inheritance isn't going away. Inheritance is definitely one of building block of OOPS, it has its use cases to represent real-world hierarchical relationship; for more info refer Inheritance in OOPS.

You might be interested in the below blog posts.

Loose coupling v/s tight coupling

Singleton design pattern explained with an example

Implementin IComparer for multiple types sorting of requirements

03 April 2015

dependency injection

While designing software systems, Architects press for loosely coupled software design. In this post let's see how to build loosely coupled class composition using dependency injection.

This blog post mainly aimed at explaining what is dependency injection with practical examples.

Code implemented without dependency injection

public class EmailManager
{
 public Send(Message message)
 {
  //Send email using SmtpClient
 }
}

You will use EmailManager class to send an email in your Client which probably looks something like below:

public class Client
{
   public void ProcessOrder(Order newOrder)
   {
    // Other business logic
    // Send email
    EmailManager mgnr = new EmailManager();
    manager.Send(message);
   }
}

Issues with code not using dependency injection

Above code will serve the purpose but there are two problems with code in the Client class.

  1. Cannot unit test ProcessOrder() method in the Client client.
  2. If requirements is changed from sending Email to text message, then you will have to modify Client class to use a new SMSManager instead of current EmailManager class. Changing an existing class to meet changing business requirement isn't always an option because of the regression involved. It violates OPEN for EXTENSION CLOSED for MODIFICATION design principle.

Refactor the code to eliminate design issues using Dependency injection

  • CHANGE #1:Changes to EmailManager class. Let's create a interface 'INotificationManager' and declare Send() method, later make the EmailManager to implement the interface.
  • CHANGE #2: Add a constructor to Client class to expect an object implementing INotificationManager interface

After the code refactoring the it will look like below:

public interface INotifictionManager
{
 void Send(Message message);
}

public class EmailManager:INotifictionManager
{
public void Send(Message message)
  {
    //logic to send email
   }
}

public class Client
{
  private INotificationManager _manager =null;
  public Client(INotifictionManager manager)
   {
    _manager =manager;
   }
   
  public void ProcessOrder(Order newOrder){
  {
    //..other logic...and build Message to be sent
    // send notification
    _manager.send(message);
  }
}

If you look at Client class in refactored code, its no longer creating an instance of EmailManager, that means it easy to unit the ProcessOrder() method using mocking.

Second, if in future business requirements changes from sending an email to sending a text message, then there will be no change in your client class. Instead of passing EmailManager instance, you will pass an instance of SmsTextManager class. That means there will be no change in your Client even if your requirement changes in future to send different type of notification.

If you have come so far reading the post and wondering where is the dependency injection, my answer is "You have already seen the dependency injection in the refactored code."

Finding what is dependency injection

Depedency Injection

The Client class need to send notification while processing an order. So The Client class has a dependency on the logic to send a notification. If you look at the refactored code, this logic is provided by INotifictionManager interface. So Client class has dependency on an instance of type INotifictionManager.

If you look carefully the Client class is not creating an instance of type INotifictionManager, instead of someone while instantiating Client is passing an instance of INotifictionManager type. So Client dependency on notification in being injected into it via INotifictionManager type. THIS IS CALLED DEPENDENCY INJECTION.

12 October 2014

OOPS question:On interface design implementation

When you go for an interview it’s almost certain that interviewer will ask “what is the difference between abstract class and an interface”. Upon answering this, the questions usually go deeper to know more about your understanding of interfaces.

Let’s go through such one question on interface designs.

Say you have one interface called "IBankAccount". From this interface, you have derived two classes. These classes are "ChildAccount" and "AdultAccount". The UML class diagram for this is below:

UML class diagram showing Interface design and implementation

Question: Now if you want to add one more method "WithdrawWithNoLimit()" to "AdultAccount" class how would you design it? Do you alter your "IBankAccount" interface?

Most of us think, let's add the new method "WithdrawWithNoLimit()" to "IBankAccount" interface. With this change the UML class diagram looks like below:

UML class diagram showing Interface design and implementation

But the above design approach has one big disadvantage. For no reason, the "ChildAccount" class end up in implementing the new method "WithdrawWithNoLimit()" and throwing the "System.NotSuuportedException" exception. With this design, the number of methods in a single interface is increasing and this is referred as "Fat interface". This is usually not good design.

Now let's think of another design approach. How about creating one more interface called "IPrivilegeBankAccount" and moving the new method "WithdrawWithNoLimit()" inside this. Then the "AdultAccount" class can derive from the new interface. And in this approach there will be no changes to the class "ChildAccount"; This design follows the "Open Close" SOLID design principle as well.

This new design UML class diagram is below:

UML class diagram showing Interface design and implementation

We need not stop here on improving the interface design. I believe depending on requirements the design can even further be improved. So comments are welcome!.

01 June 2014

difference between abstract class and interface in c#

When you start designing class level diagrams, knowing the difference between abstract class and interface helps you in choosing right designs.

Syntactical difference

  • Abstract class can have abstract and non abstract methods. Abstract methods cannot have implementation and non abstract methods will have implementation. And these non abstract can have reusable implementation for the derived class where applicable.
  • Interface methods cannot have implementation, they are just declaration.

Difference when it come to Inheritance

  • A C# class cannot inherit from more than one class.
  • However a C# class can inherit from more than one interface. In C# .NET multiple inheritance if needed can be achieved using interfaces. If two base interfaces have the same method we can use explicit interface implementation.

Which is more flexible? interface or abstract class?

Abstract class are flexible compare to an interface. Let's take an example.

Assume that you are building a library which has contract defined using interfaces. These libraries are used by a lot of projects in your organization. First, you have released contracts.dll. So people are using the contracts which are defined by interfaces.

Now new requirements have come, to meet those requirements you are required add a new method to the existing interface which is already in use by many projects. Later when you deploy this new contracts.dll containing the interface, all the existing implementation will start failing. This is because the classes which implemented the interfaces don't have the new method implementation. So interfaces aren't backward compatible.

Assume that for instance, you have defined your contracts using the abstract class instead of an interface. You can easily add new non abstract methods to your abstract class without breaking the existing implementations. Here the existing implementations are classes deriving from the abstract class. The newly added non abstract methods can throw System.NotImplementedException when released. Hence abstract classes are more flexible compared to interfaces.

RELATED ARTICLES

18 May 2013

inheritance in oops

Inheritance is one of the main features of Object Oriented Programming concepts. Inheritance plays an important role in object oriented design. Let's go through the below sections to understand inheritance in OOPS:

What is Inheritance in OOPS?

Inheritance allows the derived classes to use features/functionality of the base class and also defines the relationships between the two objects. Code re-usability is one of the benefits of inheritance.

Inheritance examples in C# .NET

Best way to understand inheritance is to look at real-world examples. For instance in animal kingdom Homosepeans have characteristics of mammals. In OOPS terminology human beings are inherited from the mammals. So mammals are base class and human beings are derived class.

Let's consider a real-world inheritance example using the below C# class sample.

namespace InheritanceTutorial
{
  public class Doctor
  {
    public void DiagnosePatient() { }
    public void PrescribeMedicine() {}
  }
  
  public class Surgeon:  Doctor
  {
    public void DoSurgery() { }
  }
    
  public static void Main(string[] args)
  {

    Surgeon surgeon = new Surgeon();

     // Derived class instance invoking base 
     // class methods.
     // There by inheritance helps in code re-usability 
     // and also proper relationship 
     // between the classes.
     surgeon.DiagnosePatient();
     surgeon.PrescribeMedicine();

    surgeon.DoSurgery();
   }
}

Analogy of the above inheritance tutorial example:

  1. Doctor and Surgeon are two classes.
  2. Surgeon class inherits from the Doctor class. Here Doctor is base class and Surgeon is derived class.
  3. Derived class Surgeon is making use of the code present in the base class Surgeon. Derived classes customize base class behavior by overriding them or define new behaviors.
  4. Inheritance not just helps in code re usability. Using inheritance we can define "IS A" relationship.

Inheritance defines "IS A" relationship:

Considering the above inheritance example Surgeon IS A Doctor. Do not implement inheritance relationship for the sake of code re-usability. Always look out for IS A relationship. Your class design using inheritance makes sense only if every derived class exhibits IS A relationship with their base classes.

UML representation for OOPS inheritance:

In UML, OOPS inheritance will be represented by generalization relationship. In UML representation of inheritance, there a solid line running from derived class to base class with a closed arrowhead. Below UML diagram shows how to represent inheritance relationship between classes.

What do consider when implementing inheritance:

  1. Your proposed derived class should represent IS A relationship with the base class. If there is NO IS A relationship, then inheritance is not the right option. Don't try to fit the inheritance everywhere.
  2. Depth of Inheritance indicates how many classes are present in its inheritance hierarchy. It would be difficult to maintain the code if your inheritance class hierarchy chain is very long.
  3. Inheritance is static in nature, unlike polymorphism. At design time only, the relationship between the base class and derived class is fixed. And the behavior what derived class exhibits is also fixed.

Design pattern based on Inheritance:

Template method design pattern makes use inheritance. Derived classes in Template design pattern customize one or more algorithm steps behavior, which are defined in the base class.