Design to Accommodate Change

Design to Accommodate Change

Make sure your code will be easy to maintain and adapt as it evolves.  Design to Accommodate Change. Planning for the future now is like setting up your 401k.  You can take the time to research and make educated plan of execution, or you can just wing it and worry about how things work out later.  But any serious investor will tell you. planning is the key to success.

I have been preaching (uh I mean teaching) some basic principles of good coding for a while now.   Although I have many more principles to bring to you,  it will be of no consequence  if I don’t provide you with the tools to put them into practice.  Recently I posted a Q & A on the Four Concepts of OOP as an Interview Note.   These are the building blocks of where to begin.  Let’s take a deep look at each one.

Review the code and see if you recognize which of the four concepts it represents.  Don’t worry, I will reveal each follow the code as well…

C#

   // Base Class
   class Shape
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // Derived class
   class Rectangle: Shape
   {
      public int getArea()
      {
         return (width * height);
      }
   }

   class RectangleTester
   {
      static void Main(string[] args)
      {
         Rectangle Rect = new Rectangle();

         Rect.setWidth(5);
         Rect.setHeight(7);

         // Print the area of the object.
         Console.WriteLine("Total area: {0}",  Rect.getArea());
         Console.ReadKey();
      }
   }

VB

' Base Class
Class Shape
	Public Sub setWidth(w As Integer)
		width = w
	End Sub
	Public Sub setHeight(h As Integer)
		height = h
	End Sub
	Protected width As Integer
	Protected height As Integer
End Class

' Derived class
Class Rectangle
	Inherits Shape
	Public Function getArea() As Integer
		Return (width * height)
	End Function
End Class

Class RectangleTester
	Private Shared Sub Main(args As String())
		Dim Rect As New Rectangle()

		Rect.setWidth(5)
		Rect.setHeight(7)

		' Print the area of the object.
		Console.WriteLine("Total area: {0}", Rect.getArea())
		Console.ReadKey()
	End Sub
End Class

Inheritance
The Inherits statement is used to declare a new class, called a derived class, based on an existing class, known as a base class. Derived classes inherit, and can extend, the properties, methods, events, fields, and constants defined in the base class.  This is a prime example of the DRY Principle.  Inheriting another class means you only have written the code once, you only have one place to manage the code and you have lowered you expected Technical Debt.

C#

public class clsShape
{
    public int _radius = 5;

    public virtual double getArea()
    {
        return 0;
    }
}

public class clsCircle : clsShape
{
       public override  double getArea()
    {
        return 3.14 * _radius * _radius;
    }
}

public class clsSphere : clsShape
{
    public override double getArea()
    {
        return 4 * 3.14 * _radius * _radius;
    }
}

VB

Public Class clsShape
	Public _radius As Integer = 5

	Public Overridable Function getArea() As Double
		Return 0
	End Function
End Class

Public Class clsCircle
	Inherits clsShape
	Public Overrides Function getArea() As Double
		Return 3.14 * _radius * _radius
	End Function
End Class

Public Class clsSphere
	Inherits clsShape
	Public Overrides Function getArea() As Double
		Return 4 * 3.14 * _radius * _radius
	End Function
End Class

Polymorphism
Polymorphism refers to functionally different classes with identically named methods or properties that can be used interchangeably by client code at run time.  This is a good example of LoD (Law of Demeter).  Let’s envision some code that is uses the area of a shape.  The code does not need to know anything about a shape object, only that there is a function called getArea() within that will return a needed value.    Any changes made to a shape class will not effect the code calling getArea lessening Technical Debt and making the overall project more maintainable and scalable.

C#

public class Person
{

	public Int16 Height { get; set; }
	public Int16 Weight { get; set; }

	private DateTime _dob;
	public DateTime Dob {
		get { return _dob; }
		set { _dob = value; }
	}

	public Int16 Age {
			// return value by calculation
		get { }
	}

}

VB

    Public Class Person

        Public Property Height() As Int16
        Public Property Weight() As Int16

        Private _dob As DateTime
        Public Property Dob As DateTime
            Get
                Return _dob
            End Get
            Set(value As DateTime)
                _dob = value
            End Set
        End Property

        Public ReadOnly Property Age() As Int16
            Get
                ' return value by calculation
            End Get
        End Property

    End Class

Abstraction
Abstraction is the combining similar functions into a single construct to hide all but the relevant data about an object in order to reduce complexity and increase efficiency.   The user of the person class does not need to know (or perform for itself) how age is calculated.

Encapsulation
Encapsulation is the packing of data and functions into a single component. It allows selective hiding of properties and methods in an object by making the fields in a class private and providing access to the fields via public methods.

The main benefit here again lies with the ability to modify code in the person class without breaking the code of others who use the person object.

The main reason these four concepts are the core to Object Oriented Programming is that they give maintainability, flexibility and extensibility to the code.

 

 

Share This:
Facebooktwitterredditpinterestlinkedintumblr

Jim is a skilled software engineer and author of applications aimed both at home users and various industry markets. Jim's work has been utilized in the public safety, manufacturing, and banking industries. His newest endeavor is aimed at the wine making market. Jim enjoys giving back to the Software Development Community by being active on Stack Overflow. He is also Editor-in-Chief, Author and Developer here at RealWorldDeveloper.com.

Posted in Best Practices Tagged with:

Leave a Reply

Your email address will not be published. Required fields are marked *

*