Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Tuesday, January 13, 2015

Can my business object / entity / model class contain Save()?

This is a very old question. Lets try to answer it with the mind of a passionate programmer who wants his code to be the best quality code. Here we will be examining different possibilities and understand why some techniques are not recommended.

What if the Save() is part of my entity class?

Lets think in the way that, the Save() is part of the business object. What are the pros and cons

Pros

  1. Data and the functions manipulating it are in single unit and its encapsulated.

Cons

  1. If we want to change the data persistence mechanism from SQL Server database to XML, we want to modify all the entity classes.
  2. Violation of SRP - The class will change for 2 reasons. If a new property added or persistence mechanism changed.

What if the Save() is moved to Repository class

Here the Save() will be part of another class. Lets call that class as Repository. Pros and cons below

Pros

  1. Underlying storage mechanism can change without a change in the entity class.

Cons

  1. Repository might need separate methods to save different entities such as SaveEmployee() SaveOrder() etc...Otherwise one method which accepts base class of entity classes and use reflection to identity the properties to be saved. Need to keep track of what property maps to what field in database or node in xml.
  2. The consumer of the entity classes needs to remember one more class name to work with entities. API cannot be explored by developers. Need documentation.

What if the Save() is available in entity and repository and they are loosely connected?


In this technique, Save() will be available in entity class as well as repository class. The difference here is, the entity class method body will not contain any logic to persist the data. It just pass the execution to the repository. The repository knows how to persist. Some code snippet below

Core classes

public abstract class EntityBase
    {
        public abstract void Save();
    }
    interface IRepository
    {
        void Save(EntityBase entity);
    }
    static class RepositoryFactory
    {
        public static IRepository Get()
        {
            IRepository repository=default(IRepository);
            //Logic to decide repository based on config or any other criteria.
            return repository;
        }
    }

Below are the application specific classes.

    public class Account:EntityBase
    {
        public string Name { get; set; }
        public decimal balance { get; set; }
        public override void Save()
        {
            RepositoryFactory.Get().Save(this);
        }   
    }
 
    class SqlServerRepository:IRepository
    {
        void IRepository.Save(EntityBase entity)
        {
            //Use reflection to get the properties to be saved.
            //Or need to have separate methods like SaveAccount(), SaveCustomer() in the repository.
        }
    }
    //The UI parts. It can be the controller in case of MVC.
    class AccountViewmodel
    {
        Account acc = new Account() { Name = "Sales", Balance = 30000 };
        void SaveCommand()
        {
            acc.Save();
        }
    }

I know this is not a production ready code. But this gives idea how the Save() method can be written by honoring the SRP and keeping the easiness of API usage.

Tuesday, December 23, 2014

Developing for developers - Designing and developing APIs

Couple of months backs I got a chance to be part of an initiative in our project, where we have to develop APIs for our server platform. The server platform is evolved with one of the project we are doing for one particular client. Now client want to extend that platform to be usable to their other projects. When we say its server platform, it basically manages servers, helps to provision new servers to scale horizontally, provide some platform data such as where some particular data is located. The data is expected to come in terabytes and it has some data storage mechanism which is multi-tenant. It really feels to me like we are reinventing the cloud and I tried to express here and there. Sometimes, I need to be quite, else who is going to pay me:-) Obviously there are reasons from other end also. There are many legacy code to be carried to this platform and client is having security concerns on hosting in the client. If we use Windows Azure, we might be ending up in limitation. Anyway its really interesting to be part of it especially when it is coming to API design and development.

My experience with API development starts with my first company which sells custom .Net libraries .There I was supporting .Net controls and fixing defects occasionally. At that time nobody told me about the importance of API development. But I realized myself, that API is something very important because we are developing for developers. If we didn't do it right, its very costly to change as all of our developers need to change their code as well. Think about the .Net library. Most of  the classes remains same for years. Now we cannot think about Microsoft renaming the MessageBox.Show() method to MessageBox.Alert(). I believe its same for other languages as well. I was really wondering in my early stages of carrier that, how they are coming up with these framework classes, its inheritance hierarchy, members and the access modifiers of each member. If something went to faulty, its very costly to recover.

In my second company, I got very little chance to work on critical APIs, but there were chances to code for their WPF custom control library. But in third and present company, there were no chance  still last 5 years. All I was doing is to help developers to fix their code which they written only to meet the release. Obviously there were some scope of drawing boxes as design. Most of the developers (including me sometimes because of pressure) were not programming, but gathering code to make a release.

When I got the new opportunity, I thought of doing some great things. I already targeted some  developers who are passionate in programming. But unfortunately, I got a completely different team who were gathering code for delivery as I mentioned above. After 2-3 weeks it came to notice that though they were great delivery guys, they are not much aware of SOLID principles or any other software engineering aspects of programming. It was really fun how I came to notice it. As the server platform components are already available in existing application,we started extracting those components. After extracting the code, we decided to re-factor it to look like a platform code.Class name ,Namespace changes etc... The problem started there.

As of my understanding, if somebody who already practiced SOLID principles, can re-factor any code by analyzing the technical aspects / code flow. But here, the team was struggling to re-factor and the reason they told was they don't know the business of application. The timers were really hard to understand for them. I was really wondering at this statement because I had re-factored big amount of code by understanding the logic by looking at the existing code. I had no clue what is the business requirement of those code or nobody gave me requirement documents. I think this is the case with all the service companies who are delivering from offshore. So arranged training on SOLID principles.

This leads to setting up one more training on API design. Or how to design APIs in a developer friendly and long lasting, backward compatible manner. For me too, it was really a learning experience. Got names for practices which we are already doing and of course obtained the experience of other API developers. Embedded the presentation below. Hope fully I can upload the video too.

References

http://wiki.qt.io/API_Design_Principles

Edits

9Oct2015 - Added references section.

Tuesday, November 18, 2014

State pattern v/s Orchestrator

Requirement

Normally in programming we encounter scenarios where we need to carry out many operations in sequence. The sequence of operations can change based on client's business requirement changes. At this point we can assume that there is no parallelism required. How do we code such a scenario efficiently?

To tackle this, either we can write everything in single function or we can split the entire operation as step functions and have another controller function calling the those in the required order. Some people who are inspired by patterns go for pattern oriented programming and most of them end up in state pattern.

Before we go further, if anybody still thinking that what is the problem in writing the code in sequence or in single function? I would suggest get better understanding about the below concepts of programming.

  • Object Oriented Programming
  • Single Responsibility Principle
  • Re-usability
  • Separation of concerns

State pattern

State pattern defines the system as discrete states of object where each state knows what are it's next  possible states. It also has mechanism for changing the state upon any event. Events can be anything such as keyboard input, UI action such as button click, a service invocation, a timer elapsed event etc...

There are defined ways and many libraries available as well which helps us to implement state pattern. Some libraries support encapsulating different states into different classes and we can connect them. But as the basic nature is one state knowing other, its very difficult to change the sequence without changing the state classes.

Below are some links which contains implementation of state pattern and libraries.

State pattern v/s state machine

Now most of us will get a question in our mind. What is the difference between state pattern and state machine. As of my understanding state pattern is just another state machine implementation which is clean and dead simple. We can build state machine using iterator / yield, Windows Workflow Foundation , or more simpler stateless library.

Orchestrator / Sequencer pattern

We have seen what is state pattern. But is that suitable in the requirement mentioned at the beginning of this post?  According to the requirements the flow can change based on business requirements ie  logic in one step should not tell what is my next step . In state pattern each state should know about other state and tell the engine to go that particular step. If we use that state pattern we cannot build independent steps which can be interchangeable. In most of the cases, steps will be dependent each other. But our requirement is specifically about independent steps. So what is the alternative by honoring all the programming principles.

The solution leads towards orchestrator or sequencer pattern where we can define the sequence and just start the sequence by giving context which the steps are going to manipulate. It will take steps one by one and execute. I was not able to relate this requirement with any of the GOF design pattern, that's why I had to use orchestrator. Template pattern in GOF is somewhat similar. But in that we could see implementation class contains all the operation methods which seems we are violating the SRP in SOLID. 

What is Orchestrator pattern requirement

  • It needs to provide an abstraction (preferably interface) to create concrete step implementation classes.
  • Support for receiving data context into the steps.
  • It should be having support for defining / sequencing our steps.
  • A StartExecution method
  • Prefer 2 modes of execution
    • Pipe line mode - Returned value of one step should be feed as input of next step
    • Normal - All the execution methods in steps will get the context passed via StartExecution method.
A sample implementation is in progress. Hopefully I can share in next post.

Difference between state pattern and orchestrator (Sequencer)

Summarizing the differences between state pattern and sequencer. State pattern requires one state to know other. If the logic changes we need to modify the concrete state classes. In orchestrator the states/steps are independent.

Tuesday, November 11, 2014

Simple interface based programming

For some long I was searching for a good article which explains how to use interface in .Net programming. It is not for a developer who is passionate in programming, got good knowledge in object oriented programming and comes with computer science degree. But for people who came into the field because others compelled and not having computer science background. At some point I thought of writing one myself. But I was able to find a good one. Below are the link(s). I will be updating if I came across another one.

https://www.simple-talk.com/dotnet/.net-framework/designing-c-software-with-interfaces/

Tuesday, October 28, 2014

Stateful or Stateless classes?

What is mean by state of an object?

Before we discuss about Stateless or Stateful classes we should have better understanding about what is mean by the state of an object. Its same as the English meaning "the particular condition that someone or something is in at a specific time." of state.

When we come to programming and think about the condition of object at a specific time, its nothing but the value of it's properties or member variables at a given point of time. Who decides what are the properties of objects. Its the class. Who decides what are the properties and members inside a class?Its programmer who coded that class. Who is programmer? Everybody who reads this blog including me who is writing this post. Are we all experts in taking decision on what are the properties needed for each class?

I don't think so. At least its true in case of programmers in India who come into the software industry by only looking at the salary and programming as a daily job. First of all its not something can be taught in colleges like how other engineering disciplines works. It needs to come via experience because programming is in its early stages compared to other engineering and its more like art than engineering. Engineering can sometimes have hard rules but art cannot. Even after being in the programming for around 15 years (sorry I count my college days as well in programming experience)  I still take considerable amount of time to decide what are the properties needed for a class and the name of the class itself.

Can we bring some rules to what are the properties needed? In other words what properties, should the state of an object include? Or should the objects be stateless always. Below are some thoughts on this area.

Entity classes / Business Objects

There are multiple names such as entity classes , business objects etc...given to classes which are representing a clear state of something. If we take example of  Employee class, it's sole purpose is to hold the state of an employee. What that state probably can contain? EmpId, Company, Designation, JoinedDate etc...I hope there would be no confusions till this point. Everybody agrees that this type of classes should be stateful without much arguments, because this is taught in college.

But how we should do salary calculation? 
  • Should the CalculateSalary() needs to be a method inside the Employee class?
  • Should there be a SalaryCalculator class and that class should contain the Calculate() method
  • In case there is SalaryCalculator class 
    • Whether it should have properties such as BasicPay,DA HRA etc?
    • Or the Employee object needs to be a private member variable in that SalaryCalculator which is injected via constructor?
    • Or SalaryCalculator should expose Employee public property (Get&SetEmployee methods in Java)

Helper / Operation / Manipulator classes

This is the type of classes which do a task. SalaryCalculator fall into this type. There are many names to this type where classes do actions and can be found in programs with many prefix and suffixes such as
  • class SomethingCalculator eg:SalaryCalculator
  • class SomethingHelper eg: DBHelper
  • class SomethingController eg: DBController
  • class SomethingManager 
  • class SomethingExecutor
  • class SomethingProvider
  • class SomethingWorker
  • class SomethingBuilder
  • class SomethingAdapter
  • class SomethingGenerator
A long list can be found here. People have different opinion in using which suffix for what situation. But our interest is something else. 

Whether can we add state to this type of classes? I would suggest stateless. Lets examine why I am saying 'no', in rest of this post.

Hybrid classes

According to wikipedia encapsulation in object oriented programming is "Encapsulation is the packing of data and functions into a single component". Does this mean all the methods which manipulate that object should be there in the entity class? I don't think so. The entity class can have state accessor methods such as GetName() ,SetName(), GetJoiningDate ,GetSalary() etc...

But CalculateSalary() should be outside. Why its so?

According to the SOLID - Single Responsibility Principle "A class should change only for one reason". If we keep CalculateSalary() method inside the Employee class that class will change for any of the below 2 reasons which is a violation.
  • A state change in Employee class eg: A new property has been added to Employee
  • There is a change in the calculation logic
I hope its clear. Now we have 2 classes in this context. Employee class and SalaryCalculator class. How do they connect each other. There are multiple ways. One is to create object of SalaryCalculator class inside the GetSalary method and call the Calculate() to set the salary variable of Employee class. If we do so it became hybrid because it is acting like entity class and it initiate operation like helper class. I really don't encourage this type of hybrid classes. But in situations such as Save entity method, this is kind of OK with some sort of delegation of operation.

Whenever you feel that your class is falling in this hybrid category, think about re-factoring. if you feel that your classes are not falling in any of these categories stop coding.

State in Helper / Manipulator class

What is the problem if our helper classes keep state? Before that lets look at what are the different combination of state values a SalaryCalculator class can take? Below are some examples

Scenario 1 - Primitive values


    class SalaryCalculator
    {
        public double Basic { get; set; }
        public double DA { get; set; }
        public string Designation { get; set; }
 
        public double Calculate()
        {
            //Calculate and return
        }
    }

Cons

There are chances that the Basic salary can be of a Accountant and the Designation can be "Director"  which is not at all matching.There is no enforced way to make sure that the SalaryCalculator can work independently.

Similarly if this executes in threaded environment, it will fail.

Scenario 2 - Object as state


    class SalaryCalculator
    {
        public Employee Employee { get; set; }
 
        public double Calculate()
        {
            //Calculate and return
        }
    }

Cons

If one SalaryCalculator object is shared by 2 threads and each thread is for different employee, the sequence of execution might be as follows which cause logical errors.
  • Thread 1 sets employee1 object
  • Thread 2 sets employee2 object
  • Thread 1 calls Calculate method and gets Salary for employee2
We can argue that the Employee dependency can be injected via constrictor and make the property read only. Then we need to create SalaryCalculator objects for each and every employee object. So better do not design your helper classes in this way.

Scenario 3 - No state


    class SalaryCalculator
    {
        public double Calculate(Employee input)
        {
            //Calculate and return
        }
    }


This is near perfect situation. But here we can argue that, if all the methods are not using any member variable what is the use of keeping it as non static class.

The second principle in SOLID principles says "Open for extension and closed for modification". What does it mean? When we write a class, it should be complete. There should be no reason to modify it. But should be extensible via sub classing and overriding. So how would our final one looks like?

    interface ISalaryCalculator
    {
        double Calculate(Employee input);
    }
    class SimpleSalaryCalculator:ISalaryCalculator
    {
        public virtual double Calculate(Employee input)
        {
            return input.Basic + input.HRA;
        }
    }
    class TaxAwareSalaryCalculator : SimpleSalaryCalculator
    {
        public override double Calculate(Employee input)
        {
            return base.Calculate(input)-GetTax(input);
        }
        private double GetTax(Employee input)
        {
            //Return tax
            throw new NotImplementedException();
        }
    }

As I mentioned in my previous posts, always program to interface. In the above code snippet, I implemented implicitly. That is to reduce the space here. Always implement explicitly. The Logic of calculation should be kept in a protected function so that the inherited classes can call that function in case required.

Below is the way how this Calculator class should be consumed.

    class SalaryCalculatorFactory
    {
        internal static ISalaryCalculator GetCalculator()
        {
            // Dynamic logic to create the ISalaryCalculator object
            return new SimpleSalaryCalculator();
        }
    }
    class PaySlipGenerator
    {
        void Generate()
        {
            Employee emp = new Employee() { };
            double salary =SalaryCalculatorFactory.GetCalculator().Calculate(emp);
        }
    }

The Factory class encapsulate the logic of deciding which child class to be used. It can be static as above or dynamic using reflection. As far as the reason for change in this class is object creation, we are not violating the "Single responsibility principle"

In case you are going for Hybrid class and need to invoke from the Employee.GetSalary() as below.

    class Employee
    {
        public string Name { get; set; }
        public int EmpId { get; set; }
        public double Basic { get; set; }
        public double HRA { get; set; }
        
        public double Salary
        {
            //NOT RECOMMENDED 
            get{return SalaryCalculatorFactory.GetCalculator().Calculate(this);}
        }
    }

This way we ensure that, even if there is change in the SalaryCalculation logic the Employee class will not change.

Conclusion

Don't code when we are thinking. Don't think when we are coding

  • Spent some time on class design before coding. Show the class diagram to 2-3 fellow programmers and get their opinions.
  • Name the class wisely. There is no hard rule. But below are some I am following
    • Entity classes should be named with nouns which represents a type of object - eg: Employee
    • Helper / Worker class names should be reflecting that its a worker. eg: SalaryCalculator, PaySlipGenerator etc...
    • Verb should never be used as class name - eg:class CalculateSalary{}