Showing posts with label API Design. Show all posts
Showing posts with label API Design. Show all posts

Tuesday, February 27, 2018

Swagger API Test UI for easing PoC development

Background

Developing PoCs (Proof of Concepts) or samples to prove some approach or technology is suitable for our project is some every software engineer does as part of their job. Also if something goes wrong with existing systems in production we often create a sample to isolate and reproduce the problem to analyze further. If the role is of Architect, they have to involve more into these research kind of activities. Please note that create these PoCs are slightly different from prototyping as prototype is more towards visualizing the concept in the initial time only.

The goal of PoC if it is to troubleshoot an issue is to create it to the closest way possible to mimic the actual application in trouble. If the issue is production the time will be limited to create app from scratch. When we say closest it should be closest in terms of the technology, threading model, security etc...

Problem

If it is windows application of console applications, it is easy to develop a PoC and run the same way the original application runs. Even if original application is triggered in the context of a different user configured from windows task scheduler or similar, we can still mimic it. But most of the applications are web apps now a days. If we want to reproduce an issue of Web App, it would be difficult if we create a windows console app unless we run the console application using the same service account of app pool which runs the web app. But still the threading model and all will be different. If we want to develop the PoC as web application, it may take some more time than a simple console application which adds delay.

One possible solution

So the best way is to develop WebAPI and host it using the same app pool of original application. Provided there are permissions to host. Suppose we have permissions to host, the next thing is the easiness to test using WebAPI alone. If we have to develop UI for that it would take more time. So what is the solution?

Swashbuckle

Enter Swashbuckle after the long introduction which help us to render UI for the available WebAPI methods. This helps us to test the WebAPIs from a simple UI dynamically generated by it.

Since there are so many links out there which explains how to use it, lets follow the DRY principle. Links below on how to setup Swashbuckle into the WebAPI.

https://github.com/domaindrivendev/Swashbuckle
https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger
http://wmpratt.com/swagger-and-asp-net-web-api-part-1/
https://elanderson.net/2017/10/swagger-and-swashbuckle-with-asp-net-core-2/

There would be so many different views on solving the original problem of creating PoCs. Feel free to comment your technique of rapidly creating PoCs to mimic the real application.

Tuesday, July 25, 2017

Discrepancies in Azure service models and APIs

Different Azure services uses difference models of consumption. This post aims to list down those differences. Below are the categories where we can see differences.
  • Service naming model
    • Unique name inside Azure
    • Unique name inside subscription
  • API URL pattern
    • Instance specific URL
      • Instance name as sub domain
      • Service instance name in URL path
    • Generic URL
  • API authorization.
    • Key - Azure Search
    • Time limited tokens - Translator Text API
  • Passing API authorization
    • Inside URL as query string
    • Inside http headers

Service naming model

This refers to how we create the Azure service. There are mainly 2 types unique in the entire Azure v/s unique in subscription

Unique name inside Azure

Most of the services require us to create a globally unique name. That name will often end up as sub domain or part of URL. 

eg: Storage account

The problem with this mechanism is creation of new service instance from the application on the fly. For example, assume we are offering a SaaS solution and database isolation is one DB / tenant. There is a limit of 5000 databases per Azure SQL Server. When our 5001 tenant registers, we have to create next SQL Server instance from the program. Since the server name has to be unique across entire Azure, our program has to do trial and error methods to get unique name. To workaround this problem, we can take different routes such as generating GUID, create instances upfront etc... But it is something to be considered during the development process. Else it just fails.

Unique name in Subscription

Others end up in creating a name which is unique across the subscription.The AppInsight is the example for such a service.

API URL Pattern

All most all the services are designed to be consumed via http(s) web service endpoints. Mainly ReST based APIs with JSON data format. The URL pattern differs per service. Some service demand URL with its name and some can be accessed using generic URL.

Instance specific URL

Here the name of the service instance is needed in the API URL as sub domain or in the path.

Instance name as sub domain

The Azure storage account is one example for a service which demands globally unique name which ends up as sub domain.

Eg: https://<storage account>.blob.core.windows.net/ 

The services such as WebApps really demands the URL separation using sub domain.

Service instance name in URL path

If we look at some services we can see the service name is appearing inside the URL path after the domain.

eg: Analysis service  asazure://westus.asazure.windows.net/<analysisservicename>

Generic URL

In this category, there won't be any URL which has the service name in it. Instead they use a generic URL to hit the Azure service and identify service via parameters. Parameters can be request headers containing API keys or tokens.

eg: Application Insights

API Authorization

Authentication & authorization are essential factors in web service based API world. There are 2 different methods we can see in Azure services.

Key based

Key is same as in real world. The key can be used multiple times, until the lock is replaced. Similarly in Azure world, the validity of key is till that key is replaced. If anyone obtain our key, they can keep  using our service till we identify the theft and replace.

eg: Azure search. It demands us to put the key in the header.

Token based

In simple sense, token are short lived keys. Using a key or some other mechanism, we can create a token and use it for predefined time. Once it expires we have renew the token. Tokens has better security but difficult to use.

eg: Text Translator API. Details available here on how to use from Postman.

Passing API Authorization

Another area is how we can pass the authorization whether it is key or token

Inside URL as QueryString

Some services accept the authorization via the URL in the form of query string. 

Inside http headers

Other services needs the authorization in the header. eg: Translator Text API

More categories

API Version

Some services such as Azure Search needs version in the API. The versioning is in the form of date 
eg:https://<search service>.search.windows.net/indexes/<index>/docs?api-version=2016-09-01&search=<search key>&highlight=content

But the Translator Text follows v# versioning eg:https://api.microsofttranslator.com/v2/Http.svc/GetTranslations?text=jaguar&from=en&to=es&maxTranslations=5

Another way we can find for versioning is in Storage. It demands the version inside the http headers. Refer for details. Also it needs version as x-ms-version header.

Some random thoughts

Ideally as per the API guidelines (even from Microsoft) all the APIs which an application or platform provides should follow same standards. They should look like all are designed by same person. That way, consumers don't have to invest much time learning the APIs and usage. 

But in case of Azure, we cannot proceed with that principle. We have to learn to use different services separately. Why Microsoft Azure service APIs has this discrepancy?

We cannot assume that the teams who designed & developed APIs don't know this basic principle of API design. They should be having their own reasons why they did so. If we look at the Translator Text API, may be team thinks that, it should be really protected using auto expiring tokens where the Azure search team thought, search results are less secure and just needs to be protected by a key. May be from consumers point we value our search result data more than a generic translation method.

Another reason might be legacy code. Means connecting legacy code and putting into production may end up in having different API models. Also if a product is bought from other company via acquisition or so, it may end up differently. At the end the time to market matters which is nothing but money. Sometimes when weighing the money we will get due to fast release v/s beautifying the API, money gets priority. 

Competition matters here too. Sometimes first-mover strategy gives a big advantage and it may lock in clients.

Whatever the case, it seems there are no design notes publicly available describing the rationale behind these different decisions similar to Angular. We have to take our best guess why it is so and learn it. 

Tuesday, July 18, 2017

Azure Cognitive Services - Translator Text API - Calling from Postman

Azure cognitive service suit offers a lot of different APIs. One if it is language translation. It is named as Translator Text API. The good point is that it is offered as freemium meaning there is a free tier.

Calling the Translator API

Since it is service it is offered as web service. There are so many samples to use this service from different languages such as C#, JavaScript, PHP etc... which are available in their GitHub repo. But there is tutorial how can we simply call it from Postman which is web developers best friend to consume APIs.

Steps

Unlike many other APIs, this involves 2 step process. Steps given below
  1. Get the token from Azure using STS url which is currently https://api.cognitive.microsoft.com/sts/v1.0/issueToken. This URL is present in Azure portal when we navigate to Translate service instance. This may change in future.
    1. Calling this URL has to be POST with "Ocp-Apim-Subscription-Key" in the header. The value for this header is the keys present in Azure portal.
    2. The result of this call will give us a short lived token which has to be used in next step
    3. Once the token expires, we have to get renew. 10 mins is the expiry.
  2. Now using the token we can call the real, web service located at below URL
    1. https://api.microsofttranslator.com/v2/Http.svc
    2. This method accepts some parameters a query string and some parameters via POST / request data.

Example

Below goes the screenshots. 

Getting Translator Text API Keys from Azure portal. Image credits to MSDN Blogs. This key is used in next step to get token.

The above screenshot shows how to call token service from Postman to get the short lived token used for actual API call. The Ocp-Apim-Subscription-Key should be kept secret as it will help others to use our quota. It has to be changed explicitly if it is leaked.

The above image shows the real Translator Text API call. API needs the token obtained in the previous step. The token has to be prefixed with Bearer and a space before using in this call via Authorization header.
This API accepts required parameter in a hybrid way. Some are in the query string and some can be in optional POST request.
Make sure the optional post request body is properly formatted. One such format is given below.

If the POST request body has any format mismatch the request will be rejected by the server.

Happy posting...

References & more reading

https://blogs.msdn.microsoft.com/data_otaku/2016/11/05/goofing-around-with-the-cognitive-services-translator-api/
https://dev.cognitive.microsoft.com/docs/services/57346a70b4769d2694911369/operations/57346edcb5816c23e4bf7421
https://msdn.microsoft.com/en-us/library/ff512423.aspx

Tuesday, July 12, 2016

Using GitHub API to show our projects in personal sites or blog

Introduction

There are still debates going on regarding whether Github is a developer's resume or not. Whatever happens it is good to show the list of GitHub projects in a software engineer's personal site to whom he/she is contributing to.

Integrating Github API to www.JoymonOnline.in

Below is the diagram shows how I have integrated GitHub into my personal site.

www.JoymonOnline.in is a web site

Most of us know the difference between web site and web app. Here in this case we are dealing with a web site where the HTML is generated at server side and send to client. Client browser is supposed to just render the markup given by web server.

How the GitHub API looks like

Its just a URL. More specifically ReST urls which points to resources. Below is one example API url. This gives details about the repository joyful-visualstudio. Just copy paste the url into browser address bar and hit enter. The data will be displayed.

How to call GitHub API

Coming to technical programming aspects. Here in this site the API is called using WebClient class. This is a simple class in .Net framework which can be used to deal with web sites and web APIs.

Authentication / Security

If the request is not authenticated, we can perform read operations. But there is a limit in such calls. That limit is based on the IP address from where the call originates. In this case the call originates from ASP.Net code of http://joymononline.in web site. The site is hosted in shared hosting plan. It means there will be other sites in same server machine. They may call GitHub without authentication and from GitHub point all originate from same IP and it limits.

To get rid of that problem we can authenticate the requests with token. The simple way is to obtain the token from GitHub and keep in the site and transfer via header. The header name used is 'Authorization'. Now the limit is per token, its high limit and no need to worry about shared hosting.

Securing API token

Make sure the token is not public. In JoymonOnline where source is hosted in public repository in Github itself, token is not visible. Its inserted during the deployment time from AppVeyor CI solution.

.Net Client SDK

GitHub also has client sdk to make the interaction easier. If we are using client SDK we don't need to worry about low level http related WebClient class.

Tuesday, June 9, 2015

WebAPI SelfHosting via OWIN v/s HttpSelfHostServer

WebAPI can be hosted via 2 ways. The traditional way using HttpSelfHostServer and the new OWIN based hosted. Below is an attempt to compare both techniques.

API Controller

Below is the controller class I am going to host using both the hosting techniques.

Differences between HttpSelfHostServer and OWIN Hosting

In HttpSelfHostServer we can see most of the things as configurable. But in OWIN, its by convention.

References

https://frendsrnd.wordpress.com/2014/02/03/httpselfhostserver-hosted-web-api-with-https-and-windows-authentication-enabled/

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, 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{}