Abstract Classes - abhinavsaxena.net

advertisement
In this article we will discuss key concepts of object orientation with their practical implementation in
C#. We will discuss here basics ofOOPS including Interfaces, Access Modifiers, inheritance,
polymorphism etc. This is my second article on csharp-corner.com.
My first article was "Memory Management in .NET",
you can find this article at http://www.c-sharpcorner.com/
UploadFile/tkagarwal/
MemoryManagementInNet11232005064832AM/
MemoryManagementInNet.aspx
Key Concepts of Object Orientation




Abstraction
Encapsulation
Polymorphism
Inheritance.
Abstraction is the ability to generalize an object as a data type that has a specific set of
characteristics and is able to perform a set of actions.
Object-oriented languages provide abstraction via classes. Classes define the properties and methods
of an object type.
Examples:


You can create an abstraction of a dog with characteristics, such as color, height, and weight,
and actions such as run and bite. The characteristics are called properties, and the actions are
called methods.
A Recordset object is an abstract representation of a set of data.
Classes are blueprints for Object.
Objects are instance of classes.
C# Example of Class:
public class Draw
{
// Class code.
}
Object References
When we work with an object we are using a reference to that object. On the other hand, when we are
working with simple data types such as Integer, we are working with the actual value rather than a
reference.
When we create a new object using the New keyword, we store a reference to that object in a
variable. For instance:
Draw MyDraw = new Draw;
This code creates a new instance of Draw. We gain access to this new object via the MyDraw variable.
This variable holds a reference to the object.
Now we have a second variable, which also has a reference to that same object. We can use either
variable interchangeably, since they both reference the exact same object. The thing we need to
remember is that the variable we have is not the object itself but, rather, is just a reference or pointer
to the object itself.
Early binding means that our code directly interacts with the object, by directly calling its methods.
Since the compiler knows the object's data type ahead of time, it can directly compile code to invoke
the methods on the object. Early binding also allows the IDE to use IntelliSense to aid our
development efforts; it allows the compiler to ensure that we are referencing methods that do exist
and that we are providing the proper parameter values.
Late binding means that our code interacts with an object dynamically at run-time. This provides a
great deal of flexibility since our code literally doesn't care what type of object it is interacting with as
long as the object supports the methods we want to call. Because the type of the object isn't known
by the IDE or compiler, neither IntelliSense nor compile-time syntax checking is possible but we get
unprecedented flexibility in exchange.
If we enable strict type checking by using Option Strict On at the top of our code modules, then the
IDE and compiler will enforce early binding behavior. By default, Option Strict is turned off and so we
have easy access to the use of late binding within our code.
Access Modifiers
Access Modifiers are keywords used to specify the declared accessibility of a member of a type.
Public is visible to everyone. A public member can be accessed using an instance of a class, by a
class's internal code, and by any descendants of a class.
Private is hidden and usable only by the class itself. No code using a class instance can access a
private member directly and neither can a descendant class.
Protected members are similar to private ones in that they are accessible only by the containing
class. However, protected members also may be used by a descendant class. So members that are
likely to be needed by a descendant class should be marked protected.
Internal/Friend is public to the entire application but private to any outside applications. Internal is
useful when you want to allow a class to be used by other applications but reserve special functionality
for the application that contains the class. Internal is used by C# and Friend by VB .NET.
Protected Internal may be accessed only by a descendant class that's contained in the same
application as its base class. You use protected internal in situations where you want to deny access to
parts of a class functionality to any descendant classes found in other applications.
Composition of an OBJECT
We use an interface to get access to an object's data and behavior. The object's data and behaviors
are contained within the object, so a client application can treat the object like a black box accessible
only through its interface. This is a key object-oriented concept called Encapsulation. The idea is that
any programs that make use of this object won't have direct access to the behaviors or data-but
rather those programs must make use of our object's interface.
There are three main parts of Object:
1. Interface
2. Implementation or Behavior
3. Member or Instance variables
Interface
The interface is defined as a set of methods (Sub and Function routines), properties (Property
routines), events, and fields (variables or attributes) that are declared Public in scope.
Implementation or Behavior
The code inside of a method is called the implementation. Sometimes it is also called behavior since it
is this code that actually makes the object do useful work.
Client applications can use our object even if we change the implementation-as long as we don't
change the interface. As long as our method name and its parameter list and return data type remain
unchanged, we can change the implementation all we want.
So Method Signature depends on:




Method name
Data types of parameters
Either Parameter is passed ByVal or ByRef.
Return type of method.
It is important to keep in mind that encapsulation is a syntactic tool-it allows our code to continue to
run without change. However, it is not semantic-meaning that, just because our code continues to
run, doesn't mean it continues to do what we actually wanted it to do.
Member or Instance Variables
The third key part of an object is its data, or state. Every instance of a class is absolutely identical in
terms of its interface and its implementation-the only thing that can vary at all is the data contained
within that particular object.
Member variables are those declared so that they are available to all code within our class. Typically
member variables are Private in scope-available only to the code in our class itself. They are also
sometimes referred to as instance variables or as attributes. The .NET Framework also refers to them
as fields.
We shouldn't confuse instance variables with properties. A Property is a type of method that is geared
around retrieving and setting values, while an instance variable is a variable within the class that may
hold the value exposed by a Property.
Interface looks like a class, but has no implementation.
The only thing it contains is definitions of events, indexers, methods and/or properties. The reason
interfaces only provide definitions is because they are inherited by classes and structs, which must
provide an implementation for each interface member defined. So, what are interfaces good for if they
don't implement functionality? They're great for putting together plug-n-play like architectures where
components can be interchanged at will. Since all interchangeable components implement the same
interface, they can be used without any extra programming. The interface forces each component to
expose specific public members that will be used in a certain way.
Because interfaces must be defined by inheriting classes and structs, they define a contract. For
instance, if class foo inherits from the IDisposable interface, it is making a statement that it
guarantees it has the Dispose() method, which is the only member of the IDisposable interface. Any
code that wishes to use class foo may check to see if class foo inherits IDisposable. When the answer
is true, then the code knows that it can call foo.Dispose().
Defining an Interface: MyInterface.c
interface IMyInterface
{
void MethodToImplement();
}
Above listing shows defines an interface named IMyInterface. A common naming convention is to
prefix all interface names with a capital "I", but this is not mandatory. This interface has a single
method named MethodToImplement(). This could have been any type of method declaration with
different parameters and return types. Notice that this method does not have an implementation
(instructions between curly braces- {}), but instead ends with a semi-colon, ";". This is because the
interface only specifies the signature of methods that an inheriting class or struct must implement.
All the methods of Interface are public by default and no access modifiers (like private, public) are
allowed with any method of Interface.
Using an Interface: InterfaceImplementer.cs
class InterfaceImplementer : IMyInterface
{
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
The InterfaceImplementer class in above listing implements the IMyInterface interface. Indicating that
a class inherits an interface is the same as inheriting a class. In this case, the following syntax is
used:
class InterfaceImplementer : IMyInterface
Note that this class inherits the IMyInterface interface; it must implement its all members. While
implementing interface methods all those needs to be declared public only. It does this by
implementing the MethodToImplement() method. Notice that this method implementation has the
exact same signature, parameters and method name, as defined in the IMyInterface interface. Any
difference will cause a compiler error. Interfaces may also inherit other interfaces. Following listing
shows how inherited interfaces are implemented.
Interface Inheritance: InterfaceInheritance.cs
using System;
interface IParentInterface
{
void ParentInterfaceMethod();
}
interface IMyInterface : IParentInterface
{
void MethodToImplement();
}
class InterfaceImplementer : IMyInterface
{
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
public void ParentInterfaceMethod()
{
Console.WriteLine("ParentInterfaceMethod() called.");
}
}
The code in above listing contains two interfaces: IMyInterface and the interface it inherits,
IParentInterface. When one interface inherits another, any implementing class or struct must
implement every interface member in the entire inheritance chain. Since the InterfaceImplementer
class in above listing inherits from IMyInterface, it also inherits IParentInterface. Therefore, the
InterfaceImplementer class must implement the MethodToImplement() method specified in the
IMyInterface interface and the ParentInterfaceMethod() method specified in the IParentInterface
interface.
In summary, you can implement an interface and use it in a class. Interfaces may also be inherited by
other interface. Any class or struct that inherits an interface must also implement all members in the
entire interface inheritance chain.
Inheritance is the idea that one class, called a subclass, can be based on another class, called a base
class. Inheritance provides a mechanism for creating hierarchies of objects.
Inheritance is the ability to apply another class's interface and code to your own class.
Normal base classes may be instantiated themselves, or inherited. Derived classes can inherit base
class members marked with protected or greater access. The derived class is specialized to provide
more functionality, in addition to what its base class provides. Inheriting base class members in
derived class is not mandatory.
Access Keywords
base -> Access the members of the base class.
this -> Refer to the current object for which a method is called.
The base keyword is used to access members of the base class from within a derived class:
Call a method on the base class that has been overridden by another method. Specify which baseclass constructor should be called when creating instances of the derived class. A base class access is
permitted only in a constructor, an instance method, or an instance property accessor.
In following example, both the base class, Person, and the derived class, Employee, have a method
named Getinfo. By using the base keyword, it is possible to call the Getinfo method on the base class,
from within the derived class.
// Accessing base class members
using System;
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee: Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass
{
public static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
Output
Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG
Base class constructors can be called from derived classes. To call a base class constructor, use the
base() constructor reference. This is desirable when it's necessary to initialize a base class
appropriately.
Here's an example that shows the derived class constructor with an address parameter:
abstract public class Contact
{
private string address;
public Contact(string b_address)
{
this.address = b_address;
}
}
public class Customer : Contact
{
public Customer(string c_address) : base(C_address)
{
}
}
In this code, the Customer class does not have an address, so it passes the parameter to its base
class constructor by adding a colon and the base keyword with the parameter to its declaration. This
calls the Contact constructor with the address parameter, where the address field in Contact is
initialized.
One more example which shows how base-class constructor is called when creating instances of a
derived class:
using System;
public class MyBase
{
int num;
public MyBase()
{
Console.WriteLine("In MyBase()");
}
public MyBase(int i)
{
num = i;
Console.WriteLine("in MyBase(int i)");
}
public int GetNum()
{
return num;
}
}
public class MyDerived : MyBase
{
static int i = 32;
// This constructor will call MyBase.MyBase()
public MyDerived(int ii) : base()
{
}
// This constructor will call MyBase.MyBase(int i)
public MyDerived() : base(i)
{
}
public static void Main()
{
MyDerived md = new MyDerived(); // calls public MyDerived() : base(i) and
// passes i=32 in base class
MyDerived md1 = new MyDerived(1); // call public MyDerived() : base(i)
}
}
Output
in MyBase(int i)
in MyBase()
The following example will not compile. It illustrates the effects of not including a default constructor
in a class definition:
abstract public class Contact
{
private string address;
public Contact(string address)
{
this.address = address;
}
}
public class Customer : Contact
{
public Customer(string address)
{
}
}
In this example, the Customer constructor does not call the base class constructor. This is obviously a
bug, since the address field will never be initialized.
When a class has no explicit constructor, the system assigns a default constructor. The default
constructor automatically calls a default or parameterless base constructor. Here's an example of
automatic default constructor generation that would occur for the preceding example:
public Customer() : Contact()
{
}
When a class does not declare any constructors, the code in this example is automatically generated.
The default base class constructor is called implicitly when no derived class constructors are defined.
Once a derived class constructor is defined, whether or not it has parameters, a default constructor
will not be automatically defined, as the preceding code showed.
Calling Base Class Members
Derived classes can access the members of their base class if those members have protected or
greater access. Simply use the member name in the appropriate context, just as if that member were
a part of the derived class itself. Here's an example:
abstract public class Contact
{
private string address;
private string city;
private string state;
private string zip;
public string FullAddress()
{
string fullAddress = address + '\n' + city + ',' + state + ' ' + zip;
return fullAddress;
}
}
public class Customer : Contact
{
public string GenerateReport()
{
string fullAddress = FullAddress();
// do some other stuff...
return fullAddress;
}
}
In above example, the GenerateReport() method of the Customer class calls the FullAddress() method
in its base class, Contact. All classes have full access to their own members without qualification.
Qualification refers to using a class name with the dot operator to access a class memberMyObject.SomeMethod(), for instance. This shows that a derived class can access its base class
members in the same manner as its own.
More Tips regarding Inheritance:


A static member cannot be marked as override, virtual, or abstract. So following is an error:
public static virtual void GetSSN()
You can't call static methods of base class from derived class using base keyword.
In above example if you declare a static method as follows:
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public static void GetInfo()
{
// Implementation
}
}
now you can't call this method using base.GetInfo() from derived class instead you have to call
Person.GetInfo() from derived class.
Inside Static members we can access only static fields, methods etc.
Following example will give error, because we can't access name in GetInfo() because name is not
static.
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public static void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
Virtual or abstract members cannot be private.


If you are not overriding a virtual method of base class in derived class, you can't use base
class method by using base keyword in derived class. Also when you will create an instance of
derived class, it will call derived class method and you will only be able to access base class
method when you will create instance of base class.
You can't decrease access level of a method in derived class when you are overriding a base
class method in derived class, vice versa is possible.
Means you can make protected method of base class to public in derived class.
The "this" keyword refers to:

the current instance for which a method is called. Static member functions do not have a this
pointer. The this keyword can be used to access members from within constructors, instance
methods, and instance accessors.
The following are common uses of this:
To qualify members hidden by similar names, for example:
public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}
In above example, this.name refers to private variable name in the class. If we write name = name,
then this will refer to argument name of the constructor Employee and not to private variable name in
the class. In this case private variable name will never be initialized.

To pass an object as a parameter to other methods, for example:
CalcTax(this);
To declare indexers, for example:
public int this [int param]
{
get
{
return array[param];
}
set
{
array[param] = value;
}
}
It is an error to refer to this in a static method, static property accessor, or variable initializer of a field
declaration.
In this example, this is used to qualify the Employee class members, name and alias, which are
hidden by similar names. It is also used to pass an object to the method CalcTax, which belongs to
another class.
// keywords_this.cs
// this example
using System;
public class Employee
{
public string name;
public string alias;
public decimal salary = 3000.00m;
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
// Printing method:
public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:
Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
}
}
public class Tax
{
public static decimal CalcTax(Employee E)
{
return (0.08m*(E.salary));
}
}
public class MainClass
{
public static void Main()
{
// Create objects:
Employee E1 = new Employee ("John M. Trainer", "jtrainer");
// Display results:
E1.printEmployee();
}
}
Output
Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00
Abstract Classes
Abstract classes are a special type of base classes. In addition to normal class members, they have
abstract class members. These Abstract class members are methods and properties that are declared
without an implementation. All classes derived directly from abstract classes must implement all of
these abstract methods and properties.
Abstract classes can never be instantiated. This would be illogical, because of the members without
implementations.So what good is a class that can't be instantiated? Lots! Abstract classes sit toward
the top of a class hierarchy. They establish structure and meaning to code. They make frameworks
easier to build. This is possible because abstract classes have information and behavior common to all
derived classes in a framework. Take a look at the following example:
abstract public class Contact // Abstract Class Contact.
{
protected string name;
public Contact()
{
// statements...
}
public abstract void generateReport();
abstract public string Name
{
get;
set;
}
}
Contact, is an abstract class. Contact has two abstract members, and it has an abstract method
named generateReport(). This method is declared with the abstract modifier in front of the method
declaration. It has no implementation (no braces) and is terminated with a semicolon. The Name
property is also declared abstract. The accessors of properties are terminated with semicolons.
public class Customer : Contact // Customer Inherits Abstract Class Contact.
{
string gender;
decimal income;
int numberOfVisits;
public Customer()
{
// statements
}
public override void generateReport()
{
// unique report
}
public override string Name
{
get
{
numberOfVisits++;
return name;
}
set
{
name = value;
numberOfVisits = 0;
}
}
}
public class SiteOwner : Contact
{
int siteHits;
string mySite;
public SiteOwner()
{
// statements
}
public override void generateReport()
{
// unique report
}
public override string Name
{
get
{
siteHits++;
return name;
}
set
{
name = value;
siteHits = 0;
}
}
}
The abstract base class Contact has two derived classes, Customer and SiteOwner. Both of these
derived classes implement the abstract members of the Contact class. The generateReport() method
in each derived class has an override modifier in its declaration. Likewise, the Name declaration
contains an override modifier in both Customer and SiteOwner.
C# requires explicit declaration of intent when overriding methods. This feature promotes safe code
by avoiding the accidental overriding of base class methods, which is what actually does happen in
other languages. Leaving out the override modifier generates an error. Similarly, adding a new
modifier also generates an error. Abstract methods must be overridden and cannot be hidden, which
the new modifier or the lack of a modifier would be trying to do.
The most famous of all abstract classes is the Object class. It may be referred to as object or Object,
but it's still the same class. Object is the base class for all other classes in C#. It's also the default
base class when a base class is not specified. The following class declarations produce the same exact
results:
abstract public class Contact : Object
{
// class members
}
abstract public class Contact
{
// class members
}
Object is implicitly included as a base class if it is not already declared. Besides providing the abstract
glue to hold together the C# class framework, object includes built-in functionality, some of which is
useful for derived classes to implement.
Difference between Interface and Abstract Class








Interfaces are closely related to abstract classes that have all members abstract.
For an abstract class, at least one method of the class must be an abstract method that means
it may have concrete methods.
For an interface, all the methods must be abstract
Class that implements an interface much provide concrete implementation of all the methods
definition in an interface or else must be declare an abstract class
In C#, multiple inheritance is possible only through implementation of multiple interfaces.
Abstract class can only be derived once.
An interface defines a contract and can only contains four entities viz methods, properties,
events and indexes. An interface thus cannot contain constants, fields, operators,
constructors, destructors, static constructors, or types.
Also an interface cannot contain static members of any kind. The modifiers abstract, public,
protected, internal, private, virtual, override is disallowed, as they make no sense in this
context.
Class members that implement the interface members must be publicly accessible.
Overriding Summery:
A derived class may override a virtual method of the base class with the keyword override. The
following restrictions must be followed.






Keyword override is used in the definition of child class method that is going to override the
base class's virtual method.
The return type must be the same as the virtual method have in base class.
The name of the method should also be same.
The parameter-list must also be same in order, number and type of parameters.
The accessibility of the overriding method should not be more restricted than that of the
accessibility defined with virtual method of the base class. This accessibility either be the same
or less restricted.
The virtual methods can be sealed in the child or derived classes to prevent further
modifications in the implementation of the virtual method in the derived classes, by declaring
them as sealed methods.
Hiding Base Class Members
Sometimes derived class members have the same name as a corresponding base class member. In
this case, the derived member is said to be "hiding" the base class member.
When hiding occurs, the derived member is masking the functionality of the base class member. Users
of the derived class won't be able to see the hidden member; they'll see only the derived class
member. The following code shows how hiding a base class member works.
abstract public class Contact
{
private string address;
private string city;
private string state;
private string zip;
public string FullAddress()
{
string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;
return fullAddress;
}
}
public class SiteOwner : Contact
{
public string FullAddress()
{
string fullAddress;
// create an address...
return fullAddress;
}
}
In this example, both SiteOwner and its base class, Contact, have a method named FullAddress(). The
FullAddress() method in the SiteOwner class hides the FullAddress() method in the Contact class. This
means that when an instance of a SiteOwner class is invoked with a call to the FullAddress() method,
it is the SiteOwner class FullAddress() method that is called, not the FullAddress() method of the
Contact class.
Although a base class member may be hidden, the derived class can still access it. It does this
through the base identifier. Sometimes this is desirable. It is often useful to take advantage of the
base class functionality and then add to it with the derived class code. The next example shows how
to refer to a base class method from the derived class.
abstract public class Contact
{
private string address;
private string city;
private string state;
private string zip;
public string FullAddress()
{
string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;
return fullAddress;
}
}
public class SiteOwner : Contact
{
public string FullAddress()
{
string fullAddress = base.FullAddress();
// do some other stuff...
return fullAddress;
}
}
In this particular example, the FullAddress() method of the Contact class is called from within the
FullAddress() method of the SiteOwner class. This is accomplished with a base class reference. This
provides another way to reuse code and add on to it with customized behavior.
Versioning
Versioning, in the context of inheritance, is a C# mechanism that allows modification of classes
(creating new versions) without accidentally changing the meaning of the code. Hiding a base class
member with the methods previously described generates a warning message from the compiler. This
is because of the C# versioning policy. It's designed to eliminate a class of problems associated with
modifications to base classes.
Here's the scenario: A developer creates a class that inherits from a third-party library. For the
purposes of this discussion, we assume that the Contact class represents the third-party library.
Here's the example:
public class Contact
{
// does not include FullAddress() method
}
public class SiteOwner : Contact
{
public string FullAddress()
{
string fullAddress = mySite.ToString();
return fullAddress;
}
}
In this example, the FullAddress() method does not exist in the base class. There is no problem yet.
Later on, the creators of the third-party library update their code. Part of this update includes a new
member in a base class with the exact same name as the derived class:
public class Contact
{
private string address;
private string city;
private string state;
private string zip;
public string FullAddress()
{
string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;
return fullAddress;
}
}
public class SiteOwner : Contact
{
public string FullAddress()
{
string fullAddress = mySite.ToString();
return fullAddress;
}
}
In this code, the base class method FullAddress() contains different functionality than the derived
class method. In other languages, this scenario would break the code because of implicit
polymorphism. However, this does not break any code in C# because when the FullAddress() method
is called on SiteOwner, it is still the SiteOwner class method that gets called.
This scenario generates a warning message. One way to eliminate the warning message is to place a
new modifier in front of the derived class method name, as the following example shows:
using System;
public class WebSite
{
public string SiteName;
public string URL;
public string Description;
public WebSite()
{
}
public WebSite( string strSiteName, string strURL, string strDescription )
{
SiteName = strSiteName;
URL = strURL;
Description = strDescription;
}
public override string ToString()
{
return SiteName + ", " +URL + ", " +Description;
}
}
public class Contact
{
public string address;
public string city;
public string state;
public string zip;
public string FullAddress()
{
string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;
return fullAddress;
}
}
public class SiteOwner : Contact
{
int siteHits;
string name;
WebSite mySite;
public SiteOwner()
{
mySite = new WebSite();
siteHits = 0;
}
public SiteOwner(string aName, WebSite aSite)
{
mySite = new WebSite(aSite.SiteName,aSite.URL,aSite.Description);
Name = aName;
}
new public string FullAddress()
{
string fullAddress = mySite.ToString();
return fullAddress;
}
public string Name
{
get
{
siteHits++;
return name;
}
set
{
name = value;
siteHits = 0;
}
}
}
public class Test
{
public static void Main()
{
WebSite mySite = new WebSite("Le Financier","http://www.LeFinancier.com","Fancy Financial Site");
SiteOwner anOwner = new SiteOwner("John Doe", mySite);
string address;
anOwner.address = "123 Lane Lane";
anOwner.city = "Some Town";
anOwner.state = "HI";
anOwner.zip = "45678";
address = anOwner.FullAddress(); // Different Results
Console.WriteLine("Address: \n{0}\n", address);
}
}
Here's the output:
Address:
Le Financier, http://www.LeFinancier.com, Fancy Financial Site
This has the effect of explicitly letting the compiler know the developer's intent. Placing the new
modifier in front of the derived class member states that the developers know there is a base class
method with the same name, and they definitely want to hide that member. This prevents breakage of
existing code that depends on the implementation of the derived class member. With C#, the method
in the derived class is called when an object of the derived class type is used. Likewise, the method in
the base class is called when an object of the Base class type is called. Another problem this presents
is that the base class may present some desirable new features that wouldn't be available through the
derived class.
To use these new features requires one of a few different workarounds. One option would be to
rename the derived class member, which would allow programs to use a base class method through a
derived class member. The drawback to this option would be if there were other classes relying upon
the implementation of the derived class member with the same name. This scenario will break code
and, for this reason, is considered extremely bad form.
Another option is to define a new method in the derived class that called the base class method. This
allows users of the derived class to have the new functionality of the base class, yet retain their
existing functionality with the derived class. While this would work, there are maintainability concerns
for the derived class.
Sealed Classes
Sealed classes are classes that can't be derived from. To prevent other classes from inheriting from a
class, make it a sealed class. There are a couple good reasons to create sealed classes, including
optimization and security.
Sealing a class avoids the system overhead associated with virtual methods. This allows the compiler
to perform certain optimizations that are otherwise unavailable with normal classes.
Another good reason to seal a class is for security. Inheritance, by its very nature, dictates a certain
amount of protected access to the internals of a potential base class. Sealing a class does away with
the possibility of corruption by derived classes. A good example of a sealed class is the String class.
The following example shows how to create a sealed class:
public sealed class CustomerStats
{
string gender;
decimal income;
int numberOfVisits;
public CustomerStats()
{
}
}
public class CustomerInfo : CustomerStats // error
{
}
This example generates a compiler error. Since the CustomerStats class is sealed, it can't be inherited
by the CustomerInfo class.The CustomerStats class was meant to be used as an encapsulated object
in another class. This is shown by the declaration of a CustomerStats object in the Customer class.
public class Customer
{
CustomerStats myStats; // okay
}
Polymorphism
Polymorphism is reflected in the ability to write one routine that can operate on objects from more
than one class-treating different objects from different classes in exactly the same way. For instance,
if both Customer and Vendor objects have a Name property, and we can write a routine that calls the
Name property regardless of whether we're using a Customer or Vendor object, then we have
polymorphism.
A vehicle is a good example of polymorphism. A vehicle interface would only have those properties
and methods that all vehicles have, a few of which might include paint color, number of doors,
accelerator, and ignition. These properties and methods would apply to all types of vehicles including
cars, trucks, and semi-trucks.
Polymorphism will not implement code behind the vehicle's properties and methods. Instead,
polymorphism is the implementation of an interface. If the car, truck, and semitruck all implement the
same vehicle interface, then the client code for all three classes can be exactly the same.
C# gives us polymorphism through inheritance. C# provides a keyword virtual that is used in the
definition of a method to support polymorphism.
Child class are now free to provide their own implementation of this virtual method, that is called
overriding. The following points are important regarding virtual keyword:If the method is not virtual, the compiler simply uses the reference type to invoke the appropriate
method.
If the method is virtual, the compiler will generate code to checkup the reference type at runtime it is
actually denoting to, then the appropriate method is called from the class of the reference type.
When a virtual method is called, runtime check (late method binding) is made to identify the object
and appropriate method is invoked, all this is done at runtime.
In case of non-virtual methods, this information is available at compile time, so no runtime check to
identify the object is made, so slightly efficient in the way non-virtual methods are called. But the
behavior of virtual method is useful in many ways; the functionality they provide is fair enough to bear
this slight loss of performance.
Implementing Polymorphism
The key factor here is the ability to dynamically invoke methods in a class based on their type.
Essentially, a program would have a group of objects, examine the type of each one, and execute the
appropriate method. Here's an example:
using System;
public class WebSite
{
public string SiteName;
public string URL;
public string Description;
public WebSite()
{
}
public WebSite( string strSiteName, string strURL, string strDescription )
{
SiteName = strSiteName;
URL = strURL;
Description = strDescription;
}
public override string ToString()
{
return SiteName + ", " +URL + ", " +Description;
}
}
When we inherit above class, we have two choices to invoke constructor of the class. So this is an
example of design time polymorphism. Here at design time we have to decide which method we need
to invoke while inheriting the class.
Polymorphism is the capability of a program to carry out dynamic operations by implementing
methods of multiple derived classes through a common base class reference. Another definition of
polymorphism is the ability to treat different objects the same way. This means that the runtime type
of an object determines its behavior rather than the compile-time type of its reference.
Summary
The following article is the second of a three-part article series that presents definitions and samples
for different Object-Oriented Programming (OOP) concepts and its implementation in .NET. The first
part examined the concepts of classes, objects, and structures. This part examines the concepts of
inheritance, abstraction, and polymorphism. The third and last part will examine the concepts of
interface, multiple interface inheritance, collections, and overloading.
Introduction
In Part 1 of Object-Oriented Programming Concepts and .NET, I defined the concepts of class, object,
and structure. In addition to defining the concepts, I explained real world samples and presented
sample code in C# and VB.NET to create classes and structs. The first article also explains objects as
independent building blocks.
In Part 2 of Object-Oriented Programming Concepts and .NET, I will explain the concepts of
inheritance, abstraction, and polymorphism. I will also present a Unified Model Language (UML) class
diagram to represent an object model that will help as a visual aid to explain some concepts. The
purpose of this article is to explain a series of relationships between objects.
Inheritance
In the real world there are many objects that can be specialized. In OOP, a parent class can inherit its
behavior and state to children classes. This concept was developed to manage generalization and
specialization in OOP and is represented by a is-a relationship.
The following OO terms are commonly used names given to parent and child classes in OOP:




Superclass: Parent class.
Subclass: Child class.
Base class: Parent class.
Derived class: Child class
The most common real world sample to explain inheritance is the geometric shapes object model.
Squares, circles, triangles, rectangles, pentagons, hexagons, and octagons are geometric shapes. The
following figure shows a sample set of geometric figures:
Figure 1. Geometric shapes.
The concept of generalization in OOP means that an object encapsulates common state an behavior
for a category of objects. The general object in this sample is the geometric shape. Most geometric
shapes have area, perimeter, and color. The concept of specialization in OOP means that an object can
inherit the common state and behavior of a generic object; however, each object needs to define its
own special and particular state an behavior. In Figure 1, each shape has its own color. Each shape
has also particular formulas to calculate its area and perimeter.
Inheritance makes code elegant and less repetitive. If we know that all shapes have color, should we
program a color attribute for each shape? The answer is no! Would it be a better idea to create a
shape class that has a color attribute and to make all the specialized shapes to inherit the color
attribute? The answer is yes!
An object model for this sample could have a shape parent class and a derived class for each specific
shape. The following UML class diagram shows the set of classes needed to model the geometric
shapes sample. Observe the field, properties, and methods for each class:
Figure 2. The Shape class is the parent class. Square, Rectangle, and Circle are derived classes that
inherit from Shape. The triangle-connector in the diagram represents an is-a relationship.
The .NET framework has many base classes. Everything is derived from System.Object. You can
create almost anything you imagine using the built-in functionality provided in the .NET Framework
Class Library.
To create a derived class in C#, the class declaration should be done as:
class child: parent
To create a derived class in VB.NET, the class declaration should be done as:
Class child
Inherits parent
End Class
Multiple inheritance
Multiple inheritance is the possibility that a child class can have multiple parents. Human beings have
always two parents, so a child will have characteristics from both parents.
In OOP, multiple inheritance might become difficult to handle because it allows ambiguity for the
compiler. There are programming languages such as C++ that allow multiple inheritance; however,
other programming languages such as Java and the .NET Framework languages do not allow multiple
inheritance. Multiple inheritance can be emulated in .NET using Multiple Interface Inheritance, which I
will explain in Part 3 of this series.
Sealed class
A sealed class is a class that does not allow inheritance. Some object model designs need to allow the
creation of new instances but not inheritance, if this is the case, the class should be declared as
sealed.
To create a sealed class in C#, the class declaration should be done as:
sealed class Shape
To create a sealed class in VB.NET, the class declaration should be done as:
NonInheritable Class Shape
Abstraction
Abstraction is "the process of identifying common patterns that have systematic variations; an
abstraction represents the common pattern and provides a means for specifying which variation to
use" (Richard Gabriel).
An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract
classes contain one or more abstract methods that do not have implementation. Abstract classes allow
specialization of inherited classes.
Figure 2 shows a Shape class, which is an abstract class. In the real world, you never calculate the
area or perimeter of a generic shape, you must know what kind of geometric shape you have because
each shape (eg. square, circle, rectangle, etc.) has its own area and perimeter formulas. The parent
class shape forces all derived classes to define the behavior for CalculateArea() and
CalculatePerimeter(). Another great example is a bank account. People own savings accounts,
checking accounts, credit accounts, investment accounts, but not generic bank accounts. In this case,
a bank account can be an abstract class and all the other specialized bank accounts inherit from bank
account.
To create an abstract class in C#, the class declaration should be done as:
abstract class Shape
To create an abstract class in VB.NET, the class declaration should be done as:
MustInherit Class Shape
To following code shows a sample implementation of an abstract class:
/// C#
using System;
namespace DotNetTreats.OOSE.OOPSamples
{
public abstract class Shape
{
private float _area;
private System.Drawing.Color _color;
private float _perimeter;
public float Area
{
get
{
return _area;
}
set
{
_area = value;
}
}
public System.Drawing.Color Color
{
get
{
return _color;
}
set
{
_color = value;
}
}
public float Perimeter
{
get
{
return _perimeter;
}
set
{
_perimeter = value;
}
}
public abstract void CalculateArea();
public abstract void CalculatePerimeter();
}
}
Listing 1. The Shape abstract class in C#.
Polymorphism
Polymorphism allows objects to be represented in multiple forms. Even though classes are derived or
inherited from the same parent class, each derived class will have its own behavior. Polymorphism is a
concept linked to inheritance and assures that derived classes have the same functions even though
each derived class performs different operations.
Figure 2 shows a Rectangle, a Circle, and Square. All of them are shapes and as shapes their area and
perimeter can be calculated; however, each shape calculates its area in a specialized way. Declaring a
member as abstract allows polymorphism. The Shape class defines the CalculateArea() and
CalculatePerimeter() methods as abstract, this allows each derived class to override the
implementation of the parent's methods.
To following sample code shows an implementation of a derived class (rectangle). The specific
CalculateArea() and CalculatePerimeter() methods for the rectangle class illustrate polymorphism:
/// C#
using System;
namespace DotNetTreats.OOSE.OOPSamples
{
class Rectangle : Shape
{
private float _height;
private float _width;
public rectangle(float height, float width)
{
_height = height;
_width = width;
}
public float Height
{
get
{
return _height;
}
set
{
_height = value;
}
}
public float Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
public override void CalculateArea()
{
this.Area = _height * _width;
}
public override void CalculatePerimeter()
{
this.Perimeter = (_height * 2) + (_width * 2);
}
}
}
Listing 2. Polymorphism represented in the Rectangle's methods.
Virtual keyword
The virtual keyword allows polymorphism too. A virtual property or method has an implementation in
the base class, and can be overriden in the derived classes.
To create a virtual member in C#, use the virtual keyword:
public virtual void Draw()
To create a virtual member in VB.NET, use the Overridable keyword:
Public Overridable Function Draw()
Override keyword
Overriding is the action of modifying or replacing the implementation of the parent class with a new
one. Parent classes with virtual or abstract members allow derived classes to override them.
To override a member in C#, use the override keyword:
public override void CalculateArea()
To override a member in VB.NET, use the Overrides keyword:
Public Overrides Function CalculateArea()
Conclusion
Inheritance allows developers to manage a generalization and specialization relationship between
objects. OOP concepts such as abstraction and polymorphism help to define better object models
where object hierarchies are designed with reusability in mind. In this article, I examined the concept
of inheritance, abstraction, and polymorphism. The third and last part of this series will examine the
concepts of interface, multiple interface inheritance, collections, and overloading.
Note: The sample source code* for this article works only in Visual Studio 2005.
Reference


Matt Weisfeld, The Object-Oriented Thought Process, SAMS, 2000.
Robin A. Reynolds-Haertle, OOP with Microsoft Visual Basic .NET and Microsoft Visual C# .NET
Step by Step, Microsoft Press, 2002.

OOPs Concepts in C#

I will discuss these topics in this Article

 Polymorphism

 Inheritance

 Abstraction

 Encapsulation

Inheritance

One of the key concepts of Object Oriented Programming is inheritance. With inheritance, it
is possible to create a new class from an existing one and add new features to it. Thus
inheritance provides a mechanism for class level re-usability. The new programming language
C# also supports inheritance. The syntax is straightforward.

class Base
{
}
class Derived : Base
{
}

The operator ":"is used to indicate that a class is inherited from another class. Remember that
in C#, a derived class can't be more accessible than it's base class. That means that it is not
possible to declare a derived class as public, if it inherits from a private class. For example the
following code will generate a compile time error.

class Base
{
}
public class Derived : Base
{
}

In the above case the Base class is private. And we are trying to inherit a public class from a
private class.
Let us look at a concrete example.
Here, Derived class inherits public members of the Base class x,y and Method(). The objects of
the Derived class can access these inherited members along with its own member z.

using System;
class Base
{
public int x = 10;
public int y = 20;
public void Method()
{
Console.WriteLine("Base Method");
}
}
class Derived : Base
{
public int z = 30;
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
Console.WriteLine("{0},{1},{2}",d1.x,d1.y,d1.z); // displays 10,20,30
d1.Method();// displays 'Base Method'
}
}


Inheritance & Access Modifiers

A derived class inherits every thing from the base class except constructors and destructors.
The public members of the Base class becomes the public members of the Derived class also.
Similarly the protected members of the base class become protected members of the derived
class and internal member becomes internal members of the derived class. Even the private
members of the base class are inherited to the derived class, even though derived class can't
access them.

Inheritance & Data Members

We know all base class data members are inherited to the derived, but their accessibility
remains unchanged in the derived class. For example in the program given below

using System;
class Base
{
public int x = 10;
public int y = 20;
}
class Derived : Base
{
public int z = 30;
public void Sum()
{
int sum = x+y+z;
Console.WriteLine(sum);
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Sum();// displays '60'
}
}

Here class Derived have total three data members, two of them are inherited from the Base
class.
In C#, even it is possible to declare a data member with the same name in the derived class
as shown below. In this case, we are actually hiding a base class data member inside the
Derived class. Remember that, still the Derived class can access the base class data member
by using the keyword base .

using System;
class Base
{
public int x = 10;
public int y = 20;
}
class Derived : Base
{
public int x = 30;
public void Sum()
{
int sum = base.x+y+x;
Console.WriteLine(sum);
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Sum();// displays '60'
}
}

But when we compile the above program, the compiler will show a warning, since we try to
hide a Base class data member inside the Derived class. By using the keyword new along with
the data member declaration inside the Derived class, it is possible to suppress this compiler
warning. The keyword new tells the compiler that we are trying to explicitly hiding the Base
class data member inside the Derived class. Remember that we are not changing the value of
the Base class data member here. Instead we are just hiding or shadowing them inside the
Derived class. However the Derived class can access the base class data member by using the
base operator.

using System;
class Base
{
public int x = 10;
public int y = 20;
}
class Derived : Base
{
public new int x = 30;
public void Sum()
{
int sum = base.x+y+x;
Console.WriteLine(sum);
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Sum();// displays '60'
}
}


Inheritance & Member Functions

What ever we discussed for data members are valid for member functions also. A derived
class member function can call the base class member function by using the base operator. It
is possible to hide the implementation of a Base class member function inside a Derived class
by using the new operator. When we declare a method in the Derived class with exactly same
name and signature of a Base class method, it is known as method hiding'. But during the
compilation time, the compiler will generate a warning. But during run-time the objects of the
Derived class will always call the Derived class version of the method. By declaring the derived
class method as new, it is possible to suppress the compiler warning.

using System;
class Base
{
public void Method()
{
Console.WriteLine("Base Method");
}
}
class Derived : Base
{
public void Method()
{
Console.WriteLine("Derived Method");
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Method(); // displays 'Derived Method'
}
}

Uses of new and base operators are given in the following program.

using System;
class Base
{
public void Method()
{
Console.WriteLine("Base Method");
}
}
class Derived : Base
{
public new void Method()
{
Console.WriteLine("Derived Method");
base.Method();
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Method(); // displays 'Derived Method' followed by 'Base Method'
}
}


Inheritance & Constructors

The constructors and destructors are not inherited to a Derived class from a Base class.
However when we create an object of the Derived class, the derived class constructor
implicitly call the Base class default constructor. The following program shows this.

using System;
class Base
{
public Base()
{
Console.WriteLine("Base class default constructor");
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 =new Derived();// Displays 'Base class default constructor'
}
}

Remember that the Derived class constructor can call only the default constructor of Base
class explicitly. But they can call any Base class constructor explicitly by using the keyword
base.

using System;
class Base
{
public Base()
{
Console.WriteLine("Base constructor1");
}
public Base(int x)
{
Console.WriteLine("Base constructor2");
}
}
class Derived : Base
{
public Derived() : base(10)// implicitly call the Base(int x)
{
Console.WriteLine("Derived constructor");
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();// Displays 'Base constructor2 followed by
'Derived Constructor''
}
}

Note that by using base() the constructors can be chained in an inheritance hierarchy.

Polymorphism & Virtual Methods

A virtual method in C# specifies an implementation of a method that can be polymorphicaly
overridden derived method. A non-virtual method can't be polymorphically override in a
Derived class.
A virtual method can be declared by using the keyword virtual as follows.

class Base
{
public virtual void Method()
{
}
}

When we declare a virtual method, it must contain a method body. Other wise the compiler
will generate an error. Remember that, since virtual methods are used for achieving
polymorphism and since polymorphism works only with objects, it not possible to declare a
static method as virtual in C#. Similarly the private methods are also not possible to declare
virtual, since they can't override inside a derived class.
In C#, it is not necessary to override a Base class virtual method inside a Derived class.
The following program will work absolutely correct.

using System;
class Base
{
public virtual void Method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Method(); // Displays 'Base Method'
}
}

Or even it is possible to override a virtual method non-polymorphically inside a Derived class
as shown below.

using System;
class Base
{
public virtual void Method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public virtual void Method()
{
Console.WriteLine("Derived method");
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Method(); // Displays 'Derived Method'
}
}

Even it is possible to omit the keyword virtual from the Derived class method or it is possible
to declare the Derived class method as new.
When we want to override a virtual method polymorphically inside a Derived class, we have to
use the keyword override along with the method declaration. The example is shown below.
In C#, a Base class reference can hold an object of the Derived class and when it invokes the
methods, it will invoke always the Derived class methods, if you already override that method
inside the Derived class by using the override keyword. Also the Base class method must
declare using the keyword virtual. This is what is known as Polymorphism in C#.

using System;
class Base
{
public virtual void Method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void Method()
{
Console.WriteLine("Derived method");
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.Method(); // Displays 'Base Method'
}
}

As with a virtual method, we must include a method body with an override method; other wise
the compiler will generate an error during compilation.
Remember that in C#, we can use the override keyword with only virtual method, when
overriding inside a Derived class. An overridden declaration must be identical in every way to
the virtual method, it overrides. They must have the same access level; the same return type,
the same name and same method signature. The overridden methods are implicitly virtual in
nature and hence they can override in subsequent Derived classes. As like virtual methods,
override methods can't be declared as static or private.
In Object Oriented programming Encapsulation is the first pace. Encapsulation is the
procedure of covering up of data and functions into a single unit (called class). An
encapsulated object is often called an abstract data type.







1.
2.
3.
4.
Introduction
Background
Prerequisites
The Main Content
o 4.1. What is Software Architecture?
o 4.2. Why Architecture is important?
o 4.3. What is OOP?
o 4.4. What is an Object?
o 4.5. What is a Class?
o 4.6. How to identify and design a Class?
o 4.7. What is Encapsulation (or information hiding)?
o 4.8. What is Association?
o 4.9. What is the difference between Association, Aggregation and Composition?
o 4.10. What is Abstraction and Generalization?
o 4.11. What is an Abstract class?
o 4.12. What is an Interface?
o 4.13. What is the difference between a Class and an Interface?
o 4.14. What is the difference between an Interface and an Abstract class?
o 4.15. What is Implicit and Explicit Interface Implementations?
o 4.16. What is Inheritance?
o 4.17. What is Polymorphism?
o 4.18. What is Method Overloading?
o 4.19. What is Operator overloading?
o 4.20. What is Method Overriding?
o 4.21. What is a Use case?
o 4.22. What is a Class Diagram?
o 4.23. What is a Package Diagram?
o 4.24. What is a Sequence Diagram?
o 4.25. What is two-tier architecture?
o 4.26. What is three-tier architecture?
o 4.27. What is MVC architecture?
o 4.28. What is SOA?
o 4.29. What is the Data Access Layer?
o 4.30. What is the Business Logic Layer?
o 4.31. What is Gang of Four (GoF) Design Patterns?
o 4.32. What is the difference between Abstract Factory and Builder design patterns?
5. What is the Conclusion?
6. What I Referred?
7. History
1. Introduction
I have noticed an increase in the number of articles published in the Architect category in code-project
during the last few months. The number of readers for most of these articles is also high, though the
ratings for the articles are not. This indicates that readers are interested in reading articles on
Architecture, but the quality does not match their expectations. This article is a constructive attempt
to group/ define/ explain all introductory concepts of software architecture for well seasoned
developers who are looking to take their next step as system architects.
One day I read an article that said that the richest 2 percent own half the world's wealth. It also said
that the richest 1 percent of adults owned 40 percent of global assets in the year 2000. And further,
that the richest 10 percent of adults accounted for 85 percent of the world's total wealth. So there is
an unbalanced distribution of wealth in the physical world. Have you ever thought of an unbalanced
distribution of knowledge in the software world? According to my view point, the massive expansion of
the software industry is forcing developers to use already implemented libraries, services and
frameworks to develop software within ever shorter periods of time. The new developers are trained to
use (I would say more often) already developed software components, to complete the development
quicker. They just plug in an existing library and some how manage to achieve the requirements. But
the sad part of the story is, that they never get a training to define, design the architecture for, and
implement such components. As the number of years pass by, these developers become leads and
also software architects. Their titles change, but the old legacy of not understanding, of not having
any architectural experience continues, creating a vacuum of good architects. The bottom line is that
only a small percentage of developers know how to design a truly object oriented system. The solution
to this problem is getting harder every day as the aggressive nature of the software industry does not
support an easy adjustment to existing processes, and also the related online teaching materials are
either complex or less practical or sometimes even wrong. The most of them use impractical,
irrelevant examples of shapes, animals and many other physical world entities to teach concepts of
software architecture. There are only very few good business-oriented design references.
Unfortunately, I myself am no exception and am a result of this very same system. I got the same
education that all of you did, and also referred to the same resource set you all read.
Coming back to the initial point, I noticed that there is a knowledge gap, increasing every day,
between the architects who know how to architect a system properly and the others who do not know.
The ones, who know, know it right. But the ones, who do not know, know nothing. Just like the
world’s wealth distribution, it is an unbalanced distribution of knowledge.
2. Background
This article began after reading and hearing the questions new developers have, on basics of software
architecture. There are some good articles out there, but still developers struggle to understand the
basic concepts, and more importantly, the way to apply them correctly.
As I see it, newcomers will always struggle to understand a precise definition of a new concept,
because it is always a new and hence unfamiliar idea. The one, who has experience, understands the
meaning, but the one who doesn’t, struggles to understand the very same definition. It is like that.
Employers want experienced employees. So they say, you need to have experience to get a job. But
how the hell is one supposed to have that experience if no one is willing to give him a job? As in the
general case, the start with software architecture is no exception. It will be difficult. When you start to
design your very first system, you will try to apply everything you know or learned from everywhere.
You will feel that an interface needs to be defined for every class, like I did once. You will find it harder
to understand when and when not to do something. Just prepare to go through a painful process.
Others will criticize you, may laugh at you and say that the way you have designed it is wrong. Listen
to them, and learn continuously. In this process you will also have to read and think a lot. I hope that
this article will give you the right start for that long journey.
“The knowledge of the actions of great men, acquired by long experience in contemporary affairs, and
a continual study of antiquity” – I read this phrase when I was reading the book named “The Art of
War”, seems applicable here, isn’t it?
3. Prerequisites
This article is an effort to provide an accurate information pool for new developers on the basics of
software architecture, focusing on Object Oriented Programming (OOP). If you are a developer, who
has a minimum of three or more years of continuous development experience and has that hunger to
learn more, to step-in to the next level to become a software architect, this article is for you.
4. The Main Content
4.1. What is Software Architecture?
Software Architecture is defined to be the rules, heuristics and patterns governing:



Partitioning the problem and the system to be built into discrete pieces
Techniques used to create interfaces between these pieces
Techniques used to manage overall structure and flow


Techniques used to interface the system to its environment
Appropriate use of development and delivery approaches, techniques and tools.
4.2. Why Architecture is important?
The primary goal of software architecture is to define the non-functional requirements of a system and
define the environment. The detailed design is followed by a definition of how to deliver the functional
behavior within the architectural rules. Architecture is important because it:





Controls complexity
Enforces best practices
Gives consistency and uniformity
Increases predictability
Enables re-use.
4.3. What is OOP?
OOP is a design philosophy. It stands for Object Oriented Programming. ObjectOriented Programming (OOP) uses a different set of programming languages than old procedural
programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects".
Hence, you gain re-usability by means of four main object-oriented programming concepts.
In order to clearly understand the object orientation, let’s take your “hand” as an example. The “hand”
is a class. Your body has two objects of type hand, named left hand and right hand. Their main
functions are controlled/ managed by a set of electrical signals sent through your shoulders (through
an interface). So the shoulder is an interface which your body uses to interact with your hands. The
hand is a well architected class. The hand is being re-used to create the left hand and the right hand
by slightly changing the properties of it.
4.4. What is an Object?
An object can be considered a "thing" that can perform a set of related activities. The set of activities
that the object performs defines the object's behavior. For example, the hand can grip something or
a Student (object) can give the name or address.
In pure OOP terms an object is an instance of a class.
4.5. What is a Class?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe
the details of an object. A class is the blueprint from which the individual objects are created. Class is
composed of three things: a name, attributes, and operations.
Collapse | Copy Code
public class Student
{
}
According to the sample given below we can say that the student object, named objectStudent, has
created out of the Student class.
Collapse | Copy Code
Student objectStudent = new Student();
In real world, you'll often find many individual objects all of the same kind. As an example, there may
be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built
from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class
of objects known as bicycles.
In the software world, though you may not have realized it, you have already used classes. For
example, theTextBox control, you always used, is made out of the TextBox class, which defines its
appearance and capabilities. Each time you drag a TextBox control, you are actually creating a new
instance of the TextBoxclass.
4.6. How to identify and design a Class?
This is an art; each designer uses different techniques to identify classes. However according to Object
Oriented Design Principles, there are five principles that you must follow when design a class,





SRP - The Single Responsibility Principle A class should have one, and only one, reason to change.
OCP - The Open Closed Principle You should be able to extend a classes behavior, without modifying it.
LSP - The Liskov Substitution PrincipleDerived classes must be substitutable for their base classes.
DIP - The Dependency Inversion PrincipleDepend on abstractions, not on concretions.
ISP - The Interface Segregation PrincipleMake fine grained interfaces that are client specific.
For more information on design principles, please refer to Object Mentor.
Additionally to identify a class correctly, you need to identify the full list of leaf level functions/
operations of the system (granular level use cases of the system). Then you can proceed to group
each function to form classes (classes will group same types of functions/ operations). However a well
defined class must be a meaningful grouping of a set of functions and should support the re-usability
while increasing expandability/ maintainability of the overall system.
In software world the concept of dividing and conquering is always recommended, if you start
analyzing a full system at the start, you will find it harder to manage. So the better approach is to
identify the module of the system first and then dig deep in to each module separately to seek out
classes.
A software system may consist of many classes. But in any case, when you have many, it needs to be
managed. Think of a big organization, with its work force exceeding several thousand employees (let’s
take one employee as a one class). In order to manage such a work force, you need to have proper
management policies in place. Same technique can be applies to manage classes of your software
system as well. In order to manage the classes of a software system, and to reduce the complexity,
the system designers use several techniques, which can be grouped under four main concepts named
Encapsulation, Abstraction, Inheritance, and Polymorphism. These concepts are the four main gods
of OOP world and in software term, they are called four main Object Oriented Programming (OOP)
Concepts.
4.7. What is Encapsulation (or information hiding)?
The encapsulation is the inclusion within a program object of all the resources need for the object to
function - basically, the methods and the data. In OOP the encapsulation is mainly achieved by
creating classes, the classes expose public methods and properties. The class is kind of a container or
capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its
indented functionalities to other classes. In that sense, encapsulation also allows a class to change its
internal implementation without hurting the overall functioning of the system. That idea of
encapsulation is to hide how a class does it but to allow requesting what to do.
In order to modularize/ define the functionality of a one class, that class can uses functions/
properties exposed by another class in many different ways. According to Object Oriented
Programming there are several techniques, classes can use to link with each other and they are
named association, aggregation, and composition.
There are several other ways that an encapsulation can be used, as an example we can take the
usage of an interface. The interface can be used to hide the information of an implemented class.
Collapse | Copy Code
IStudent myStudent = new LocalStudent();
IStudent myStudent = new ForeignStudent();
According to the sample above (let’s assume that LocalStudent and ForeignStudent are implemented
by theIStudent interface) we can see how LocalStudent and ForeignStudent are hiding their, localize
implementing information through the IStudent interface.
4.8. What is Association?
Association is a (*a*) relationship between two classes. It allows one object instance to cause another
to perform an action on its behalf. Association is the more general term that define the relationship
between two classes, where as the aggregation and composition are relatively special.
Collapse | Copy Code
public class StudentRegistrar
{
public StudentRegistrar ();
{
new RecordManager().Initialize();
}
}
In this case we can say that there is an association between StudentRegistrar and RecordManager or
there is a directional association from StudentRegistrar to RecordManager or StudentRegistrar use a
(*Use*)RecordManager. Since a direction is explicitly specified, in this case the controller class is
the StudentRegistrar.
To some beginners, association is a confusing concept. The troubles created not only by the
association alone, but with two other OOP concepts, that is association, aggregation and composition.
Every one understands association, before aggregation and composition are described. The
aggregation or composition cannot be separately understood. If you understand the aggregation alone
it will crack the definition given for association, and if you try to understand the composition alone it
will always threaten the definition given for aggregation, all three concepts are closely related, hence
must study together, by comparing one definition to another. Let’s explore all three and see whether
we can understand the differences between these useful concepts.
4.9. What is the difference between Association, Aggregation and Composition?
Association is a (*a*) relationship between two classes, where one class use another. But aggregation
describes a special type of an association. Aggregation is the (*the*) relationship between two
classes. When object of one class has an (*has*) object of another, if second is a part of first
(containment relationship) then we called that there is an aggregation between two classes. Unlike
association, aggregation always insists a direction.
Collapse | Copy Code
public class University
{
private Chancellor universityChancellor = new Chancellor();
}
In this case I can say that University aggregate Chancellor or University has an (*has-a*) Chancellor.
But even without a Chancellor a University can exists. But the Faculties cannot exist without
the University, the life time of a Faculty (or Faculties) attached with the life time of the University .
If University is disposed the Facultieswill not exist. In that case we called that University is composed
of Faculties. So that composition can be recognized as a special type of an aggregation.
Same way, as another example, you can say that, there is a composite relationship in-between
aKeyValuePairCollection and a KeyValuePair. The two mutually depend on each other.
.Net and Java uses the Composite relation to define their Collections. I have seen Composition is being
used in many other ways too. However the more important factor, that most people forget is the life
time factor. The life time of the two classes that has bond with a composite relation mutually depend
on each other. If you take the .net Collection to understand this, there you have the Collection
Element define inside (it is an inner part, hence called it is composed of) the Collection, farcing the
Element to get disposed with the Collection. If not, as an example, if you define the Collection and it’s
Element to be independent, then the relationship would be more of a type Aggregation, than a
Composition. So the point is, if you want to bind two classes with Composite relation, more accurate
way is to have a one define inside the other class (making it a protected or private class). This way
you are allowing the outer class to fulfill its purpose, while tying the lifetime of the inner class with the
outer class.
So in summary, we can say that aggregation is a special kind of an association and composition is a
special kind of an aggregation. (Association->Aggregation->Composition)
4.10. What is Abstraction and Generalization?
Abstraction is an emphasis on the idea, qualities and properties rather than the particulars (a
suppression of detail). The importance of abstraction is derived from its ability to hide irrelevant
details and from the use of names to reference objects. Abstraction is essential in the construction of
programs. It places the emphasis on what an object is or does rather than how it is represented or
how it works. Thus, it is the primary means of managing complexity in large programs.
While abstraction reduces complexity by hiding irrelevant detail, generalization reduces complexity by
replacing multiple entities which perform similar functions with a single construct. Generalization is the
broadening of application to encompass a larger domain of objects of the same or different type.
Programming languages provide generalization through variables, parameterization, generics
and polymorphism. It places the emphasis on the similarities between objects. Thus, it helps to
manage complexity by collecting individuals into groups and providing a representative which can be
used to specify any individual of the group.
Abstraction and generalization are often used together. Abstracts are generalized through
parameterization to provide greater utility. In parameterization, one or more parts of an entity are
replaced with a name which is new to the entity. The name is used as a parameter. When the
parameterized abstract is invoked, it is invoked with a binding of the parameter to an argument.
4.11. What is an Abstract class?
Abstract classes, which declared with the abstract keyword, cannot be instantiated. It can only be
used as a super-class for other classes that extend the abstract class. Abstract class is the concept
and implementation gets completed when it is being realized by a subclass. In addition to this a class
can inherit only from one abstract class (but a class may implement many interfaces) and must
override all its abstract methods/ properties and may override virtual methods/ properties.
Abstract classes are ideal when implementing frameworks. As an example, let’s study the abstract
class namedLoggerBase below. Please carefully read the comments as it will help you to understand
the reasoning behind this code.
Collapse | Copy Code
public abstract class LoggerBase
{
/// <summary>
/// field is private, so it intend to use inside the class only
/// </summary>
private log4net.ILog logger = null;
/// <summary>
/// protected, so it only visible for inherited class
/// </summary>
protected LoggerBase()
{
// The private object is created inside the constructor
logger = log4net.LogManager.GetLogger(this.LogPrefix);
// The additional initialization is done immediately after
log4net.Config.DOMConfigurator.Configure();
}
///
///
///
///
///
<summary>
When you define the property as abstract,
it forces the inherited class to override the LogPrefix
So, with the help of this technique the log can be made,
inside the abstract class itself, irrespective of it origin.
/// If you study carefully you will find a reason for not to have “set” method
here.
/// </summary>
protected abstract System.Type LogPrefix
{
get;
}
/// <summary>
/// Simple log method,
/// which is only visible for inherited classes
/// </summary>
/// <param name="message"></param>
protected void LogError(string message)
{
if (this.logger.IsErrorEnabled)
{
this.logger.Error(message);
}
}
/// <summary>
/// Public properties which exposes to inherited class
/// and all other classes that have access to inherited class
/// </summary>
public bool IsThisLogError
{
get
{
return this.logger.IsErrorEnabled;
}
}
}
The idea of having this class as an abstract is to define a framework for exception logging. This class
will allow all subclass to gain access to a common exception logging module and will facilitate to easily
replace the logging library. By the time you define the LoggerBase, you wouldn’t have an idea about
other modules of the system. But you do have a concept in mind and that is, if a class is going to log
an exception, they have to inherit theLoggerBase. In other word the LoggerBase provide a framework
for exception logging.
Let’s try to understand each line of the above code.
Like any other class, an abstract class can contain fields, hence I used a private field named logger
declare theILog interface of the famous log4net library. This will allow the Loggerbase class to control,
what to use, for logging, hence, will allow changing the source logger library easily.
The access modifier of the constructor of the LoggerBase is protected. The public constructor has no
use when the class is of type abstract. The abstract classes are not allowed to instantiate the class. So
I went for the protected constructor.
The abstract property named LogPrefix is an important one. It enforces and guarantees to have a
value forLogPrefix (LogPrefix uses to obtain the detail of the source class, which the exception has
occurred) for every subclass, before they invoke a method to log an error.
The method named LogError is protected, hence exposed to all subclasses. You are not allowed or
rather you cannot make it public, as any class, without inheriting the LoggerBase cannot use it
meaningfully.
Let’s find out why the property named IsThisLogError is public. It may be important/ useful for other
associated classes of an inherited class to know whether the associated member logs its errors or not.
Apart from these you can also have virtual methods defined in an abstract class. The virtual method
may have its default implementation, where a subclass can override it when required.
All and all, the important factor here is that all OOP concepts should be used carefully with reasons,
you should be able to logically explain, why you make a property a public or a field a private or a class
an abstract. Additionally, when architecting frameworks, the OOP concepts can be used to forcefully
guide the system to be developed in the way framework architect’s wanted it to be architected
initially.
4.12. What is an Interface?
In summary the Interface separates the implementation and defines the structure, and this concept is
very useful in cases where you need the implementation to be interchangeable. Apart from that an
interface is very useful when the implementation changes frequently. Some say you should define all
classes in terms of interfaces, but I think recommendation seems a bit extreme.
Interface can be used to define a generic template and then one or more abstract classes to define
partial implementations of the interface. Interfaces just specify the method declaration (implicitly
public and abstract) and can contain properties (which are also implicitly public and abstract).
Interface definition begins with the keyword interface. An interface like that of an abstract class
cannot be instantiated.
If a class that implements an interface does not define all the methods of the interface, then it must
be declared abstract and the method definitions must be provided by the subclass that extends the
abstract class. In addition to this an interfaces can inherit other interfaces.
The sample below will provide an interface for our LoggerBase abstract class.
Collapse | Copy Code
public interface ILogger
{
bool IsThisLogError { get; }
}
4.13. What is the difference between a Class and an Interface?
In .Net/ C# a class can be defined to implement an interface and also it supports multiple
implementations. When a class implements an interface, an object of such class can be encapsulated
inside an interface.
If MyLogger is a class, which implements ILogger, there we can write
Collapse | Copy Code
ILogger log = new MyLogger();
A class and an interface are two different types (conceptually). Theoretically a class emphasis the idea
of encapsulation, while an interface emphasis the idea of abstraction (by suppressing the details of the
implementation). The two poses a clear separation from one to another. Therefore it is very difficult or
rather impossible to have an effective meaningful comparison between the two, but it is very useful
and also meaningful to have a comparison between an interface and an abstract class.
4.14. What is the difference between an Interface and an Abstract class?
There are quite a big difference between an interface and an abstract class, even though both look
similar.
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
Interface definition begins with a keyword interface so it is of type interface
Abstract classes are declared with the abstract keyword so it is of type class
Interface has no implementation, but they have to be implemented.
Abstract class’s methods can have implementations and they have to be extended.
Interfaces can only have method declaration (implicitly public and abstract) and fields
(implicitly public static)
Abstract class’s methods can’t have implementation only when declared abstract.
Interface can inherit more than one interfaces
Abstract class can implement more than one interfaces, but can inherit only one class
Abstract class must override all abstract method and may override virtual methods
Interface can be used when the implementation is changing
Abstract class can be used to provide some default behavior for a base class.
Interface makes implementation interchangeable
Interface increase security by hiding the implementation
Abstract class can be used when implementing framework
Abstract classes are an excellent way to create planned inheritance hierarchies and also
to use as non-leaf classes in class hierarchies.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For
example, if you have an application framework, an abstract class can be used to provide the default
implementation of the services and all mandatory modules such as event logging and message
handling etc. This approach allows the developers to develop the application within the guided help
provided by the framework.
However, in practice when you come across with some application-specific functionality that only your
application can perform, such as startup and shutdown tasks etc. The abstract base class can declare
virtual shutdown and startup methods. The base class knows that it needs those methods, but an
abstract class lets your class admit that it doesn't know how to perform those actions; it only knows
that it must initiate the actions. When it is time to start up, the abstract class can call the startup
method. When the base class calls this method, it can execute the method defined by the child class.
4.15. What is Implicit and Explicit Interface Implementations?
As mentioned before .Net support multiple implementations, the concept of implicit and explicit
implementation provide safe way to implement methods of multiple interfaces by hiding, exposing or
preserving identities of each of interface methods, even when the method signatures are the same.
Let's consider the interfaces defined below.
Collapse | Copy Code
interface IDisposable
{
void Dispose();
}
Here you can see that the class Student has implicitly and explicitly implemented the method
named Dispose()via Dispose and IDisposable.Dispose.
Collapse | Copy Code
class Student : IDisposable
{
public void Dispose()
{
Console.WriteLine("Student.Dispose");
}
void IDisposable.Dispose()
{
Console.WriteLine("IDisposable.Dispose");
}
}
4.16. What is Inheritance?
Ability of a new class to be created, from an existing class by extending it, is called inheritance.
Collapse | Copy Code
public class Exception
{
}
public class IOException : Exception
{
}
According to the above example the new class (IOException), which is called the derived class or
subclass, inherits the members of an existing class (Exception), which is called the base class or
super-class. The classIOException can extend the functionality of the class Exception by adding new
types and methods and by overriding existing ones.
Just like abstraction is closely related with generalization, the inheritance is closely related with
specialization. It is important to discuss those two concepts together with generalization to better
understand and to reduce the complexity.
One of the most important relationships among objects in the real world is specialization, which can be
described as the “is-a” relationship. When we say that a dog is a mammal, we mean that the dog is a
specialized kind of mammal. It has all the characteristics of any mammal (it bears live young, nurses
with milk, has hair), but it specializes these characteristics to the familiar characteristics of canis
domesticus. A cat is also a mammal. As such, we expect it to share certain characteristics with the
dog that are generalized in Mammal, but to differ in those characteristics that are specialized in cats.
The specialization and generalization relationships are both reciprocal and hierarchical. Specialization
is just the other side of the generalization coin: Mammal generalizes what is common between dogs
and cats, and dogs and cats specialize mammals to their own specific subtypes.
Similarly, as an example you can say that both IOException and SecurityException are of type
Exception. They have all characteristics and behaviors of an Exception, That mean the IOException is
a specialized kind of Exception. A SecurityException is also an Exception. As such, we expect it to
share certain characteristic withIOException that are generalized in Exception, but to differ in those
characteristics that are specialized inSecurityExceptions. In other words, Exception generalizes the
shared characteristics of both IOException andSecurityException,
while IOException and SecurityException specialize with their characteristics and behaviors.
In OOP, the specialization relationship is implemented using the principle called inheritance. This is the
most common and most natural and widely accepted way of implement this relationship.
4.17. What is Polymorphisms?
Polymorphisms is a generic term that means 'many shapes'. More precisely Polymorphisms means the
ability to request that the same operations be performed by a wide range of different types of things.
At times, I used to think that understanding Object Oriented Programming concepts have made it
difficult since they have grouped under four main concepts, while each concept is closely related with
one another. Hence one has to be extremely careful to correctly understand each concept separately,
while understanding the way each related with other concepts.
In OOP the polymorphisms is achieved by using many different techniques named method
overloading, operator overloading and method overriding,
4.18. What is Method Overloading?
The method overloading is the ability to define several methods all with the same name.
Collapse | Copy Code
public class MyLogger
{
public void LogError(Exception e)
{
// Implementation goes here
}
public bool LogError(Exception e, string message)
{
// Implementation goes here
}
}
4.19. What is Operator Overloading?
The operator overloading (less commonly known as ad-hoc polymorphisms) is a specific case
of polymorphismsin which some or all of operators like +, - or == are treated as polymorphic
functions and as such have different behaviors depending on the types of its arguments.
Collapse | Copy Code
public class Complex
{
private int real;
public int Real
{ get { return real; } }
private int imaginary;
public int Imaginary
{ get { return imaginary; } }
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
}
I above example I have overloaded the plus operator for adding two complex numbers. There the two
properties named Real and Imaginary has been declared exposing only the required “get” method,
while the object’s constructor is demanding for mandatory real and imaginary values with the user
defined constructor of the class.
4.20. What is Method Overriding?
Method overriding is a language feature that allows a subclass to override a specific implementation of
a method that is already provided by one of its super-classes.
A subclass can give its own definition of methods but need to have the same signature as the method
in its super-class. This means that when overriding a method the subclass's method has to have the
same name and parameter list as the super-class's overridden method.
Collapse | Copy Code
using System;
public class Complex
{
private int real;
public int Real
{ get { return real; } }
private int imaginary;
public int Imaginary
{ get { return imaginary; } }
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
public override string ToString()
{
return (String.Format("{0} + {1}i", real, imaginary));
}
}
In above example I have extended the implementation of the sample Complex class given under
operator overloading section. This class has one overridden method named “ToString”, which override
the default implementation of the standard “ToString” method to support the correct string conversion
of a complex number.
Collapse | Copy Code
Complex num1 = new Complex(5, 7);
Complex num2 = new Complex(3, 8);
// Add two Complex numbers using the
// overloaded plus operator
Complex sum = num1 + num2;
// Print the numbers and the sum
// using the overriden ToString method
Console.WriteLine("({0}) + ({1}) = {2}", num1, num2, sum);
Console.ReadLine();
4.21. What is a Use case?
A use case is a thing an actor perceives from the system. A use case maps actors with functions.
Importantly, the actors need not be people. As an example a system can perform the role of an actor,
when it communicate with another system.
In another angle a use case encodes a typical user interaction with the system. In particular, it:

Captures some user-visible function.
 Achieves some concrete goal for the user.
A complete set of use cases largely defines the requirements for your system: everything the user can
see, and would like to do. The below diagram contains a set of use cases that describes a simple login
module of a gaming website.
4.22. What is a Class Diagram?
A class diagrams are widely used to describe the types of objects in a system and their relationships.
Class diagrams model class structure and contents using design elements such as classes, packages
and objects. Class diagrams describe three different perspectives when designing a system,
conceptual, specification, and implementation. These perspectives become evident as the diagram is
created and help solidify the design.
The Class diagrams, physical data models, along with the system overview diagram are in my opinion
the most important diagrams that suite the current day rapid application development requirements.
UML Notations:
4.23. What is a Package Diagram?
Package diagrams are used to reflect the organization of packages and their elements. When used to
represent class elements, package diagrams provide a visualization of the name-spaces. In my
designs, I use the package diagrams to organize classes in to different modules of the system.
4.24. What is a Sequence Diagram?
A sequence diagrams model the flow of logic within a system in a visual manner, it enable both to
document and validate your logic, and are used for both analysis and design purposes. Sequence
diagrams are the most popular UML artifact for dynamic modeling, which focuses on identifying the
behavior within your system.
4.25. What is two-tier architecture?
The two-tier architecture is refers to client/ server architectures as well, the term client/ server was
first used in the 1980s in reference to personal computers (PCs) on a network. The actual client/
server model started gaining acceptance in the late 1980s, and later it was adapted to World Wide
Web programming.
According to the modern days use of two-tier architecture the user interfaces (or with ASP.NET, all
web pages) runs on the client and the database is stored on the server. The actual application logic
can run on either the client or the server. So in this case the user interfaces are directly access the
database. Those can also be non-interface processing engines, which provide solutions to other
remote/ local systems. In either case, today the two-tier model is not as reputed as the three-tier
model. The advantage of the two-tier design is its simplicity, but the simplicity comes with the cost of
scalability. The newer three-tier architecture, which is more famous, introduces a middle tier for the
application logic.
4.26. What is three-tier architecture?
The three tier software architecture (also known as three layer architectures) emerged in the 1990s to
overcome the limitations of the two tier architecture. This architecture has aggressively customized
and adopted by modern day system designer to web systems.
Three-tier is a client-server architecture in which the user interface, functional process logic, data
storage and data access are developed and maintained as independent modules, some time on
separate platforms. The term "three-tier" or "three-layer", as well as the concept of multi-tier
architectures (often refers to as three-tier architecture), seems to have originated within Rational
Software.
The 3-Tier architecture has the following three tiers.
Presentation Tier or Web Server: User Interface, displaying/ accepting data/ input to/ from
the user
2. Application Logic/ Business Logic/ Transaction Tier or Application Server: Data
validation, acceptability check before being added to the database and all other business/
application specific operations
3. Data Tier or Database server: Simple reading and writing method to database or any other
storage, connection, command, stored procedures etc
1.
4.27. What is MVC architecture?
The Model-View-Controller (MVC) architecture separates the modeling of the domain, the
presentation, and the actions based on user input into three separate classes.
Unfortunately, the popularity of this pattern has resulted in a number of faulty usages; each
technology (Java,ASP.NET etc) has defined it in their own way making it difficult to understand. In
particular, the term "controller" has been used to mean different things in different contexts. The
definitions given bellow are the closes possible ones I found for ASP.NET version of MVC.
1. Model: DataSet and typed DataSet (some times business object, object collection, XML etc)
are the most common use of the model.
2. View: The ASPX and ASCX files generally handle the responsibilities of the view.
3. Controllers: The handling of events or the controlling is usually done in the code-behind
class.
In a complex n-tier distributed system the MVC architecture place the vital role of organizing the
presentation tier of the system.
4.28. What is SOA?
A service-oriented architecture is essentially a collection of services. These services communicate with
each other. The communication can involve either simple data passing or it could involve two or more
services coordinating some activity. Some means of connecting services to each other is needed.
The .Net technology introduces the SOA by mean of web services.
The SOA can be used as the concept to connect multiple systems to provide services. It has it's great
share in the future of the IT world.
According to the imaginary diagram above, we can see how the Service Oriented Architecture is being
used to provide a set of centralized services to the citizens of a country. The citizens are given a
unique identifying card, where that card carries all personal information of each citizen. Each service
centers such as shopping complex, hospital, station, and factory are equipped with a computer system
where that system is connected to a central server, which is responsible of providing service to a city.
As an example when a customer enter the shopping complex the regional computer system report it
to the central server and obtain information about the customer before providing access to the
premises. The system welcomes the customer. The customer finished the shopping and then by the
time he leaves the shopping complex, he will be asked to go through a billing process, where the
regional computer system will manage the process. The payment will be automatically handled with
the input details obtain from the customer identifying card.
The regional system will report to the city (computer system of the city) while the city will report to
the country (computer system of the country).
4.29. What is the Data Access Layer?
The data access layer (DAL), which is a key part of every n-tier system, is mainly consist of a simple
set of code that does basic interactions with the database or any other storage device. These
functionalities are often referred to as CRUD (Create, Retrieve, Update, and Delete).
The data access layer need to be generic, simple, quick and efficient as much as possible. It should
not include complex application/ business logics.
I have seen systems with lengthy, complex store procedures (SP), which run through several cases
before doing a simple retrieval. They contain not only most part of the business logic, but application
logic and user interface logic as well. If SP is getting longer and complicated, then it is a good
indication that you are burring your business logic inside the data access layer.
4.30. What is the Business Logic Layer?
I know for a fact that this is a question for most, but from the other hand by reading many articles I
have become aware that not everyone agrees to what business logic actually is, and in many cases it's
just the bridge in between the presentation layer and the data access layer with having nothing much,
except taking from one and passing to the other. In some other cases, it is not even been well thought
out, they just take the leftovers from the presentation layer and the data access layer then put them
in another layer which automatically is called the business logic layer. However there are no god said
things that cannot be changed in software world. You can change as and when you feel comfortable
that the method you apply is flexible enough to support the growth of your system. There are many
great ways, but be careful when selecting them, they can over complicating the simple system. It is a
balance one needs to find with their experience.
As a general advice when you define business entities, you must decide how to map the data in your
tables to correctly defined business entities. The business entities should meaningfully define
considering various types of requirements and functioning of your system. It is recommended to
identify the business entities to encapsulate the functional/ UI (User Interface) requirements of your
application, rather than define a separate business entity for each table of your database. For
example, if you want to combine data from couple of table to build a UI (User Interface) control (Web
Control), implement that function in the Business Logic Layer with a business object that uses couple
of data object to support with your complex business requirement.
4.31. What is Gang of Four (GoF) Design Patterns?
The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They
are categorized in three groups: Creational, Structural, and Behavioral. Here you will find information
on these important patterns.
Creational Patterns
o
o
o
o
o
Abstract Factory Creates an instance of several families of classes
Builder Separates object construction from its representation
Factory Method Creates an instance of several derived classes
Prototype A fully initialized instance to be copied or cloned
Singleton A class of which only a single instance can exist
Structural Patterns
o
o
o
o
o
o
o
Adapter Match interfaces of different classes
Bridge Separates an object’s interface from its implementation
Composite A tree structure of simple and composite objects
Decorator Add responsibilities to objects dynamically
Facade A single class that represents an entire subsystem
Flyweight A fine-grained instance used for efficient sharing
Proxy An object representing another object
Behavioral Patterns
o
o
o
o
o
o
o
o
o
o
o
Chain of Resp. A way of passing a request between a chain of objects
Command Encapsulate a command request as an object
Interpreter A way to include language elements in a program
Iterator Sequentially access the elements of a collection
Mediator Defines simplified communication between classes
Memento Capture and restore an object's internal state
Observer A way of notifying change to a number of classes
State Alter an object's behavior when its state changes
Strategy Encapsulates an algorithm inside a class
Template Method Defer the exact steps of an algorithm to a subclass
Visitor Defines a new operation to a class without change
4.32. What is the difference between Abstract Factory and Builder design patterns?
The two design patterns are fundamentally different. However, when you learn them for the first time,
you will see a confusing similarity. So that it will make harder for you to understand them. But if you
continue to study eventually, you will get afraid of design patterns too. It is like infant phobia, once
you get afraid at your early age, it stays with you forever. So the result would be that you never look
back at design patterns again. Let me see whether I can solve this brain teaser for you.
In the image below, you have both design pattern listed in. I am trying to compare the two one on
one to identify the similarities. If you observe the figure carefully, you will see an easily
understandable color pattern (same color is used to mark the classes that are of similar kind).
Please follow up with the numbers in the image when reading the listing below.
Mark #1: Both patterns have used a generic class as the entry-class. The only difference is the name
of the class. One pattern has named it as “Client”, while the other named it as “Director”.
Mark #2: Here again the difference is the class name. It is “AbstractFactory” for one and “Builder” for
the other. Additionally both classes are of type abstract.
Mark #3: Once again both patterns have defined two generic (WindowsFactory & ConcreteBuilder)
classes. They both have created by inheriting their respective abstract class.
Mark #4: Finally, both seem to produce some kind of a generic output.
Now, where are we? Aren’t they looking almost identical? So then why are we having two different
patterns here?
Let’s compare the two again side by side for one last time, but this time, focusing on the differences.


Abstract Factory: Emphasizes a family of product objects (either simple or complex)
Builder: Focuses on constructing a complex object step by step


Abstract Factory: Focus on *what* is made
Builder: Focus on *how* it is made


Abstract Factory: Focus on defining many different types of *factories* to build many
*products*, and it is not a one builder for just one product
Builder: Focus on building a one complex but one single *product*


Abstract Factory: Defers the choice of what concrete type of object to make until run time
Builder: Hide the logic/ operation of how to compile that complex object


Abstract Factory: *Every* method call creates and returns different objects
Builder: Only the *last* method call returns the object, while other calls partially build the object
Sometimes creational patterns are complementary: So you can join one or many patterns when you
design your system. As an example builder can use one of the other patterns to implement which
components get built or in another case Abstract Factory, Builder, and Prototype can use Singleton in
their implementations. So the conclusion would be that the two design patterns exist to resolve two
type of business problems, so even though they look similar, they are not.
I hope that this shed some light to resolve the puzzle. If you still don’t understand it, then this time it
is not you, it has to be me and it is since that I don’t know how to explain it.
5. What is the Conclusion?
I don't think, that it is realistic trying to make a programming language be everything to everybody.
The language becomes bloated, hard to learn, and hard to read if everything plus the kitchen sink is
thrown in. In another word every language has their limitations. As system architect and designer we
should be able to fully and more importantly correctly (this also mean that you shouldn’t use a ballistic
missile to kill a fly or hire FBI to catch the fly) utilize the available tools and features to build usable,
sustainable, maintainable and also very importantly expandable software systems, that fully utilize the
feature of the language to bring a competitively advance system to their customers. In order to do it,
the foundation of a system places a vital role. The design or the architecture of a software system
is the foundation. It hold the system together, hence designing a system properly (this never mean
an *over* desinging) is the key to the success. When you talk about designing a software system, the
correct handling of OOP concept is very important. I have made the above article richer with idea but
still kept it short so that one can learn/ remind all of important concept at a glance. Hope you all will
enjoy reading it.
Finally, after reading all these, one may argue with me saying that anybody can write all these
concept definitions but do I know how/ when to apply them in real world systems. So for them to see
these concepts being applied in real world systems, please check the source code of the latest of my
open-source project nameRocket Framework.
Note: For newbies Rocket Framework is going to be little too advance but check it, use it and review it
if you have any questions/ criticisms around my design don't hesitate to shoot them here or there..
Download