Back to Basics: OOP and Layered Application Design (Fundamentals to N-Tiered Architecture)

After doing an introduction to basic OOP Principles,

  1. Classes and Objects
  2. Inheritance
  3. Polymorphism (in Taglish)
  4. Encapsulation (also in Taglish, mostly in Filipino)

I am moving the series further to discuss another programming basic which is building an application with its components separated by logical layers. This principle will also serve to be a foundation for writing Tiered Solutions when I get later to the series.

While there have been a lot of enhancements to the .NET Framework since I first wrote about this subject in 2005 or 2006, principle remains the same and I will be writing similarly because previous statistics revealed that those were the most read portions of my blog. There must also have clarity in how that was written so I elected to put the same approach.

To give a brief background, the process of layering is done to group similar program functions into a component for good uses such as flexibility, code readability, and separation of concerns to name a few. Below is an example of a high level diagram of the most common approach.

Where

Presentation Layer provides users with interaction to business functions and processes through its presentation processing logics. Most often in the form of a Web Site Application, Windows Based Applications, and Device Specific Implementations such as ATMs, Tablets, Smart phones, etc.

Business Layer exposes the core functionality of software either by a library or web services exposed to the consuming presentation tier. In practice, program functions are usually encapsulated to a business logic code. It can sometimes contain components that integrate other application components such as a job or a trigger to a Windows Service, depending on your requirements, in other instances; those reside directly from the presentation layer or downstream to the Data Layer.

Data layer provides access to data hosted within the boundaries of the system, a custom data processing logic and data exposed by other networked systems; perhaps accessed through services. The data layer exposes generic interfaces that the components in the business layer can consume.

There are other layers that are considered to be reused across other tiers or on a specific function. Examples are Security, Interfaces, and Helpers some of which we will use the next set of articles.

To kick start the series, let us prep the solution we will be using to get more sense into the diagram I have showed earlier. Open up Visual Studio (or an Express Edition variant such as for Desktop or for Web).

Create a solution with projects (and corresponding project types) listed below. If you have been into the previous articles, we are going to be writing a fictitious Grading system so my students from the previous articles can easily follow.

  1. Grading.Interfaces (Class Library Project)
  2. Grading.Helpers (Class Library Project)
  3. Grading.DataAccess (Class Library Project)
  4. Grading.Business (Class Library Project)
  5. Grading.Services (although a little more advance, but this will showcase another programming principle that is more becoming common especially in the cloud era).
  6. Grading.WebUI (for Web) or Grading.WinUI (for Desktop)

In this set of exercises, we will be using my favorite database management system which is SQL Server (you may use the express variants).

Watch out as we continue this series.

———————————–

Filipino translation:

Para sa pagpapatuloy ng sinimulan kong serye na tumalakay sa ilang importanteng disiplina ng OOP, ang mga susunod na panulat ay tatalakay ng isa pang programming basic kung saan pinapaliwanag ang pagbuo ng isang application gamit ang paghihiwalay ng mga lohikal na mga bahagi. Ang prinsipyo na ito ay magsisilbi rin na pundasyon para sa pagsusulat ng Tiered Solutions sa mga susunod pang mga serye.

Kahit nagkaroon na ng maraming bago sa .NET Framework mula ng una kong naisulat ang tungkol sa paksang ito noong 2005 o 2006, ang mga prinsipyo ay nananatiling pareho. Sang-ayon din sa inilarawan ng istatistika na ang bahagi ng aking blog na may kinalaman dito ang may pinaka-maraming pagbasa kaya pananatilihin ko ang parehas na istilo.

Para magbigay ng maiksing salaysay, ang proseso ng paghihiwahiwalay ng mga bahagi ng programa ay upang makapag-bigay na mas angkop na pag-pangkat ng code upang mas madaling mabasa at makapagbigay ng mas malayang paggamit. Ang larawan sa itaas ay isang halimbawa ng isang mataas na antas ng nagpapakita ng isa sa pinaka-karaniwang diskarte.

(larawan)

Kung saan

Presentation Layer ay nagbibigay ng pakikipag-ugnayan sa mga gumagamit at kung ano ang kayang gawin ng programa sa pamamagitan ng Web Site Application, Windows Based Applications, at Device Specific Implementations katulad ng isang ATM, Tablets, Smart phones, at iba pa.

Business Layer ay naglalantad ng pangunahin at serbisyo na kayang ipamalas ng isang programa na nagbibigay ng karaniwang gamit para sa Web Site o iba pang nasa Presentation Layer. Madalas ay itinatago nito ang mga proseso na hindi kailangang ipakita sa mga taga konsumo nito.

Data layer naman ay nagbibigay ng access sa data o impormasyon na naka-host sa loob ng mga hangganan ng sistema.

May mga iba pang mga layer na itinuturing na reused sa kabuuan ng iba pang mga Tier o sa isang tiyak na function. Mga halimbawa nito ay Security, Interface, at Helpers; ang ilan sa mga ito ay gagamitin sa susunod na hanay ng mga artikulo.

Ang gagamitin nating database management system ay SQL Server.

Read IT, love IT, live IT! J

Advertisements

Back to Basics: OOP and C# – Part 3 (Polymorphism)

In Part 2, we went into the definition of Inheritance and have shown example of it’s implementation. This week, we’ll be covering one of the OOP Principles that I mentioned in previous posts which is polymorphism.

Also, I realized that there had been a lot of great tutorials in the web already, and since I am delivering this to the Sophomore Class I will be teaching to in a couple of days, I decided to do this a little differently. I am going to ‘experiment’ and mixed some local dialects to it so it would be better understood here in the Philippines (a.k.a. TaglishTagalog/English).

Kung titingnan nyo yung nakaraang posts, makikita nyo dun yung project na ginamit at itutuloy lang natin dito. Pero bago yun, ibigay muna natin yung kahulugan ng Polymorphism sa Taglish:

Mula sa MSDN:

Polymorphism is a Greek word that means “many-shaped” and it has two distinct aspects:

  1. At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object’s declared type is no longer identical to its run-time type.
  2. Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class’s version of the method to be executed.

Ang sabi dito, yung mga objects sa derived class, ay pwedeng ituring na bahagi ng base class sa loob ng method parameters, collections, o sa mga arrays kapag pinatakbo yung program. Pag nangyari yun, iba na yung type ng object sa declaration kumpara kapag pinatakbo mo na sya. Halimbawa (pansinin nyo na itutuloy lang natin yung nakaraang project):

Buksan nyo yung Instructor class, tapos dagdagan nyo ng isang virtual method. (Yun pa yung isang konsepto nya, kapag gumawa ka ng virtual method sa base class, naka deklara na yung pangalan nya at implementasyon, pero pwede mong gamitin yung pangalan sa derived class at magbigay ng panibagong implementasyon (gamit yung override).

Overridable virtual method

Overridable virtual method

Ayun, tapos magdagdag tayo ng tatlo pang derived class na gamit yung Instructor bilang base class. Halimbawa:

Override method on derived class

Override method on derived class

Pansinin nyo, kakalagay ko palang nung override na pangalan tapos lumabas na kaagad na rekomendasyon sa intellisense yung Teach na method.

Ayun, kapag nilagay natin yung kumpleto (pinagsama ko nalang sa isang file yung tatlong class):

Derrived classes with Teach method

Derived classes with Teach method

Ngayon, ilagay naman natin sya sa main program para masubukan natin kung paano sya tatawagin… ang intention nito ay para maipakita na pwedeng magamit yung Programming, SoftwareDesign, at DatabaseDesign kahit saan na ginamit yung Instructor. Hindi narin natin kailangang mag cast sa tamang type kasi kakayanan ng gawin yun nung paggamit ng base class papuntang derived class.

Polymorphism at work

Polymorphism at work

Ang isa pang mapupuna natin sa halimbawa ay yung pagtawag sa method na Teach, na ang implementasyon nila ay hango sa derived class, pero nilagay din nating halimbawa yung pagtawag sa base method ng Teach dun sa Programming class, kaya parehas natin makikita sa resulta yung ginawa ng Teach sa base class at Teach pag tumakbo na yung sa linya ng Programming na class

Polymorphism at runtime

Polymorphism at runtime

Sya nga pala, yung ‘var’ na nakikita nyo, pag-compile nyan, Instructor din na type ang kalalabasan nyan. Kung sinadya ko sya sa code, ganito lang din sya — foreach (Instructor subject in teaches) — malinaw na ba? I hope this work well for you, hanggang sa muli!   (just realized that this is the only Taglish part, and most of it were in Tagalog, hahe) read it, love it, live it 🙂

Back to Basics: OOP and C# – Part 2 (Inheritance)

In Part 1, I did a quick review of Class and Objects with Visual Studio 2012 Express for Desktop on a C# Console Project. To see the Person Class that we will be referencing to continue this series, you can read back here.

Now that you probably have a working Person class if you followed on with the first part, let us begin adding a new class file and name it “Instructor”.

Instructor class

Instructor class

To have Instructor class derived from Person class, you will need to add using the format  “: {base class}” next to the class declaration.

Instructor inheriting from Person

i.e. Instructor inheriting from Person

this process enabled the derived class Instructor to reuse, extend and modify properties and methods that the base class Person had with the exception of the constructor.

For instance, we wanted to add a List of Subjects the Instructor teaches, a method that Adds a subject into the list; and creating another derived class Student that will have the Year Level property:

Derived classes (Instructor and Student) of Person

Derived classes (Instructor and Student) of Person

Note: In Visual Studio, you can perform common refactoring routines with a set of shortcut keys. i.e. to Encapsulate a field, you may hold Ctrl<key> then press ‘R’ then ‘E’ (Ctrl + R + E) while the cursor is in the same line and a dialog will appear (or you may also right click the property to find the context menu for Refactoring).

Each of the derived classes Instructor and Student now represents two different specializations of the Person class.

Further,

From MSDN:A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.

to illustrate, let us extend the Student class to have Grades.Transitive Inheritance (Person > Student > StudentGrades)

Noticed how YearLevels enum which is of Student was used, and how Lastname and Firstname of Person was used. Below is a visual representation of the hierarchy:

Inheritance Class Diagram

Inheritance Class Diagram

That covers some basics of Inheritance. There are more which includes Abstract and Virtual Methods which is really the basis for polymorphism. I am going to cover that shortly.

Another terminology used is Abstract base class. This is done if you want to prevent direct instantiation with the new keyword so it can only be used to derived class. An example is when you see me use the Person class from Program.cs in Part 1. If the Person class has been declared as Abstract instead, it can only be used within Student which is a derived class.

I will be covering the rest of implementation when I get to the later part of the series including Interfaces.

Till next… Read it, love it, live it 😉

Back to Basics: OOP and C#

My older brother has connected me to a student of InfoTech Institute of Arts and Sciences which required a resource speaker for their midterm requirements.

So I chatted with her a little bit and got to an agreement that we are covering ‘building a cloud based solution’ but we need to teach them the fundamentals as pre-requisites since we are bringing it to 2nd year students.

And the best place to start is to brush up their OOP Principles (with C#).

If you quickly pull up your favorite search engine, you’d come by 3 popular terminologies and there is a wealth of resources in the web to help you with its definition – and yes, I am talking about Encapsulation, Inheritance and Polymorphism. Since the intention of my next few series is for the attendees to have a place where they can review my upcoming talk, while this can still be useful to you, this will be a targeted discussion.

Part 1: A quick review on Class and Objects

Supposed we are to treat this activity (activity – referring to ongoing lecture) as a software, and everything we do is part of a computer program, how do we write it? One approach is to try and write a narrative of your observation inside this class.

For instance:

Michael Corpuz is teaching to the 2nd year students Principles of OOP in Room 100 at 9:00am during Tuesdays and Thursdays.

Identify verbs and nouns to form as your objects and methods. i.e. Michael Corpuz, 2nd Year Students, Principles of OOP, Room 100, teaching, 9:00am, Tuesdays and Thursdays.

In some cases, they would treat Instructor (Michael Corpuz) as Class separate to a Student (Students can also be a class that is a collection of Student) and Year Level (2nd year) as a Property. Others would go by defining a Person Class since that is common of an Instructor and Students and adding a property Person Type where you can define if that Person is a Student or an Instructor. Others would go as far as defining Person as a Base Class (note the change ‘base’ from above) and using that as a foundation for Instructor Class and Student Class. That is referred to as Inheritance. Before we dig deeper into that, let us now build the classes for purposes of comparison.

Open Visual Studio 2012 (or equivalent Express Edition) to create a C# Console Project. In my case, I pulled up Express 2012 for Windows Desktop – and click ‘New Project’ shown below:

New Project

New Project

Visual C# > Console Application

Visual C# > Console Application

For the purposes of this demonstration, we are using the 2nd approach above, we are not ready for Inheritance yet. From the ‘Solution Explorer’, right click the project you just created and add new Class and name it Person — by default, the file Person.cs will have a class declaration with the name Person under a namespace which is also by default the name of the project.

 

Person Class

Person Class

 

Quick Tip: typing ‘enum’, you will see the intellisense pull up a code snippet icon aside from the ‘enum’ type itself, hitting ‘tab’ key will use the snippet on your code view for faster construction of your codes. you can do the same for Property by typing ‘prop’ or ‘propa’ then hit ‘tab’ key twice.

Properties and Methods

 

Note that we did not use “Year Level” property yet, that will come in handy discussing Inheritance.

 

Person person = new Person();

 

 

Using the Person class from the main program.

Using the Person class from the main program.

 

 

Program output

Program output

 

Part 2: <<link to be posted here>>.