7/23/26

First impressions of Claude code

Imagine you are sitting in a room with a very senior software developer who is not only an expert coder but also a very skilled architect. Let us call this person Merlin, after the great magician. Merlin's only job is to help you do your work better and faster. Merlin works only for you and no one else. He is available 24/7 and has nowhere to go or be. You explain your requirements and task at hand to Merlin. You discuss the code that you are working on and then you ask Merlin to suggest a few good approaches. In a few minutes, Merlin is able to process all your requirements and understand your code base. He then suggests the best approach for your needs that is not only well designed but also performant. If you are not satisfied with the approach or if you find certain flaws in the approach, you can discusss it with him and he will fine-tune the approach based on the feedback. Once you are satisfied with the approach, Merlin will also write the entire code and tests for you in a few minutes. All you need to do is to review and validate the changes to make sure they align with your business and performance requirements. If something needs changing, just let Merlin know and he will refactor the code and tests accordingly, again, within a few minutes.

 
What if Merlin was real? What if every software developer had a dedicated Merlin to help them all the time?? What are the possibilities with such unlimited expertise at hand?? 

In the world of software development with AI, Claude Code is Merlin. It is a coding assistant that does all the things that Merlin does and then some. I have been using it for about six months now and I have to admit that it is one of most interesting and thought-provoking experiences in my life. Here are my initial impressions:

 It is mind-blowing to see how fast it can understand a large code base and come up with accurate suggestions within a few minutes. It can interpret my natural language commands accurately and is correct most of the time. It comes up suggestions that I have not thought about and finds problems that I have not noticed. It learns from every single interaction, as if it is recoding everything in a book for future reference. I can try several different approaches to my problem, within a span of  minutes. 

On the other hand, I am addicted to the assistant now. I have become so dependent on the tool that I feel I have stopped thinking on my own. I spend a great deal of time on validating and testing all the changes that Claude has made. If I don't do it then I risk shipping software that has been written by a non-human, which could be catastrophic. Claude is smart and very intuitive but it is limited by ability to specify my needs in the best way possible. If my commands are not accurate enough then the results will also be not accurate. This is where the human element comes into play. 

Claude is only as smart as the person that is giving commands. If I am an experienced and smart developer, then I can really push the potential of Claude because I know exactly what I am looking for, and what i need Claude to do for me. I will also be able to find flaws in Claude's thinking or code and be able to make better suggestions. Understanding the code base and the requirements is the responsibility of the human. This is non-negotiable. The right result has to be a beautiful orchestration between humans and AI. AI in the hands of Ignorant or lazy humans can have catastrophic consequences.

The only limitation is the cost associated with using the assistant. You get charged based on your usage. If you can afford to pay for Claude Code, then you are only limited by your imagination. Every company that can afford to pay for Claude can now become powerful, so how does a company differentiate itself from others? or how does one software developer differentiate himself/herself from others?? I guess it will come down to your imagination and your ability to find the right problems to solve. It will also come down to what you will be doing with the time that the assistant is saving you. Now that a lot of the time-consuming tasks are being handled by Claude, what are your core responsibilities now? 

Is Claude going to replace me?? I do not think so. But if i do not learn to use Claude in imaginative ways and realize its potential, then I could be replaced by another developer who does.

9/22/24

Building a REST API from scratch

Designing and building a REST API requires a lot of planning and hard work. For the past year, I have been part of a team that has been building an API to meet a certain requirement in my company. It has been quite a learning process and immensely satisfying. I have decided to document the journey so that the information is available for the future. 

Based on my experience, following are the steps involved in designing and building a good API:
  • Understand the requirements
    • The first step in the process of designing an API is to understand the business requirements. What problem are we trying to solve?  Who are the consumers? What is the scope and scale? Do we really need a new API or is there any existing API that can be enhanced to meet our need? It is extremely important to collaborate with the product managers and product owners regularly to clarify all the questions that you need answered. This is THE most critical phase of API development.
  • Identify resources and operations(defining end points)
    • At the core of a rest api are resources. Through the API end points, we are figuring out the best way for the consumers to access these resources in a user-friendly manner. The API end points need to be very intuitive and there should be a certain consistency to the design.
  • Create Stoplight documentation for the API end points
    • Documenting each of the end points in detail adds additional clarity and exposes potential loopholes in our design. It helps us streamline the request and response payloads associated with each end point. Once we have the documentation, we can share it with other team members and solicit early feedback. We now have a source of truth for development. 
  • Picking the appropriate database (if there is a need)
    • Based on the service requirements, we need to figure out what kind of a database makes sense. If we are looking at structured data with a lot of relationships between the data and there is going to be a lot of analysis of the data (beyond basic queries), a SQL database would probably make sense. If we want more flexibility on the kind of data that will be stored and if we are going to be dealing with frequent schema changes, we should probably go with a noSQL database that allows storing unstructured data. Other considerations include team member expertise with various databases and support for various databases within the company. If more teams are using it, you have more people to ask questions. If there is already an existing infrastructure for the database setup and deployment, it makes things much easier.
  • Data model design
    • Once you have decided on the database, we need to define the schema. In order to have a well-defined schema, it helps a lot to understand all the potential access patterns. We will then define the entities, relationships between the entities, the constraints, logging/auditing requirements, replication, security of the data etc. We need to account for future flexibility, scalability and performance. Once you have the initial design draft in place, document the design in a wiki and request the team for feedback at an early stage so that we can catch any design flaws early.
  • Security design
    • Create a Continuous Threat Modeling document (CTM) to document all the information pertaining to the security of the service. Most companies usually have a CTM template that is used across the company. You will need to define the authentication and authorization for each of the API end points,. You will need to mention any encoding/decoding that is being used anywhere in the service (including data at rest). You will need to explain how you plan to deal with bad data in the request payload or URIs.  You will need to explain the transportation security in place (like SSL). If you are using a cloud provider like AWS, then you will have to explain the security apparatus in the cloud. In addition, we need to make sure to restrict access to stoplight and other API related wiki pages to ensure the integrity of the data. Request for feedback from the team, as soon as the initial draft is in place, so that changes can be made at an early stage.
  • Code Implementation
    • Picking the right tech stack. In most cases, this is probably going to be based on what is already being used in the company. Nowadays most techs stacks offer similar features and unless there is a really special requirement that would warrant a specific language/tool, it makes sense to stick with the most popular ones within the company. Design the operations in a modular, extensible and reusable manner with attention to encoding/decoding wherever necessary. Make sure to pay attention to string encodings. Make sure to not use user-supplier information to build keys in the backend since they are subject to change. Make sure to validate the input for each operation before allowing the operation to proceed. Make sure to log messages as needed. design the exception handling carefully to account for all kinds of exceptions with appropriate messaging, so that it becomes easy to troubleshoot issues when they arise. Make sure to add unit/integration/contract/functional and smoke tests for the end points. Build the testing infrastructure in a modular, extensible and reusable manner as well. Make sure to have good code coverage. Code coverage and styling and security checks can be strictly enforced in the Jenkins pipeline as well.
  • Development and Deployment Environments:
    • It is important to have a good understanding of the various environments in place for the API. We can have different environments like dev, where all the development happens, followed by Staging, which is where the QA team tests and finally the Prod environment. During development, if we are adding any backend resources or configurations, we need to make sure we do it in a way that enables them to be deployed to each of the environments in a consistent manner. We also need to have notifications in place to be notified of success/failure during the deployment. We also need to work with the devops teams to ensure that appropriate security is in place for each environment.
  • Testing:
    • Work with the QA teams in parallel to ensure that test plans are in place for each of the end points. In addition to manual testing, the QA teams should have their own automated testing in place. If the API is being consumed inside an application, there need to be end-end tests for the same. There can be UI tests to validate the responses in the front-end.
  • Performance and Load testing
    • It is important to test the performance of our APIs to make sure the latency is within the acceptable range. We can use tools like Blazemeter for the purpose. It is also important to determine the maximum load our APIs can handle so that we can configure the backend servers appropriately. Based on the test results, we can look into additional measures like code optimizations, altering the database schema  or implementing caching. It also helps to have a good understanding of observability tools like Splunk and Kibana so that we can query the vast amounts of error logs and troubleshoot problems effectively.
  • Documenting the entire process in a wiki so that we have a blueprint in place the next time we decide to build another API. 

6/19/24

A Use Case for DynamoDB

 DynamoDB is a noSQL database from Amazon. More information here.

Let us assume we are building a REST API that deals with three main resources: City, Team, Player. Each resource has different attributes.

Following are the endpoints for each resource:

  • City:
    • POST: AddCity
    • PATCH: UpdateCity
    • DELETE: DeleteCity
    • GET: ListCities and GetCityByID
  • Team:
    • POST: AddTeam
    • PATCH: UpdateTeam
    • DELETE: DeleteTeam
    • GET: ListTeams and GetTeamByID
  • Player:
    • POST: AddPlayer
    • PATCH: UpdatePlayer
    • DELETE:DeletePlayer
    • GET: ListPlayers and GetPlayerByID


Based on the end points, it is evident that we will mostly be doing simple read/write operations and there will be no real need for any complex queries. Sometimes there can be a high volume of read operations, but thats about it. So fast read writes and scalability is our main criteria and of course cost optimization associated with software and hardware and usage.
  • Implementation with some SQL database (ex: SQL Server)
    • You will have to provision the servers and the software.
    • Maintain the servers in the future.
    • Manage the scaling as data grows. Might require additional servers.
    • We will have to manage the replication, partitioning etc.
    • We will need three tables for the three entities - city, team and player and associated referential integrity relationships between them. The database generates the keys for the tables and support for constraints is also built-in.
    • Updates to the database schema are non-trivial. Adding additional attributes to a city or a team would require a good deal of work.
    • No special support for fast read/write operations
    • We can write complex queries (which is not our requirement)
    • We will be charged irrespective of the amount of usage
  • Implementation with DynamoDB
    • It is a managed database, so no need for any software or hardware installations
    • No maintenance of the software or hardware. Amazon will take care of this.
    • We can use just one table for all the three entities. We store data as key-value pairs and as a result, we can store rows of varying attributes in DynamoDB. So we can store a row for the city, a row for the team and a row for the player in the same table. The only requirement is that each row should have a unique primary key attribute (which is defined in the schema definition). This is my favorite aspect of DynamoDB.
    • Since we are storing the data as key-value pairs, adding additional attributes or removing existing attributes (other than primary key) is trivial. This makes DynamoDB very powerful for scenarios that require flexibility(with dynamic requirements).
    • Supports fast read/write operations, which is our main requirement.
    • Amazon will scale the table as it grows, we do not need to worry about it.
    • We do not have to worry about partitioning or replication of data.
    • Amazon does not charge for the amount of data, but for the number of reads/writes. We can optimize the costs by designing the schema based on our access patterns. This is the most important aspect to keep in mind when dealing with DynamoDB. For example - if we are trying to update a row with 100kb of data, DynamoDB will charge a lot more than if we were trying to update a row with 1kb of data. So we can perform optimizations like storing the data that will be updated, in a separate row and so on.
    • We will have to generate the keys for the table. Other than enforcing the primary key constraint, DynamoDB does not support any other kind of uniqueness or constrains by default. We will need to implement those on our own. The beauty is that we can add manage additional constraints by adding additional rows to the same table and performing atomic operations in our code. For example - if we had a requirement that a city cannot have more than one team with the same name. As soon as we add new team for a city, within the same transaction, we can add another row with a primary key value that is a combination of cityID and team name. The next time we try to add another team with the same name in a city, it will violate the primary key constraint. So it is pretty easy to implement custom constraints in DynamoDB.
It is very clear that DynamoDB is better suited for our REST API requirements than any other SQL or noSQL databases. There are other noSQL options like MongoDB and Cassandra, with their own distinct advantages, but they do not make sense for our requirements. MongoDB for example supports a lot of data types and aggregate queries and transactions while Cassandra supports varying columns of data. 

3/5/22

Microservices - the good and the not-so-good

A microservice can be considered as a self contained unit of functionality, that is usually small to medium in size.  Since the beginning of last year, I have been working on a large web application that is is powered by microservices. This was my first exposure to microservices and I have come to realize that they have their own advantages and disadvantages.

The good:

  • A microservice is a well defined unit of functionality. It does only one thing and does it well.
  • A microservice is usually small in size and is easy to develop and test and maintain.
  • A microservice is an independent unit of functionality, so any tech stack can be used to develop it
  • If you decide to use the same tech stack for new microservices, you can copy/paste an existing microservice and reuse the configuration and deployment scripts and maybe even some code.
  • Each microservice can have it's own security requirements
  • Each microservice can be developed by a small dedicated team of engineers
  • It is easy to make changes and deploy a microservice without fear of impacting other applications or services. A great deal of regression or smoke testing is not required like in the case of monolithic applications
The not-so-good:
  • Troubleshooting an error in an application powered by microservices is not straight-forward. Each call can potentially traverse across several microservices before the required results are returned. It becomes necessary to pass certain request related data (like a Request ID) from the application to all the services in the chain so that all the errors can be logged with the same request and can be used to identify and troubleshoot errors.
  • From a development point of view, each microservice is a separate project and a small dedicated team of engineers usually manage a few microservices. so it becomes hard to get up to speed and become familiar with many different projects. This becomes even more difficult if a different tech stack is used for different microservices
  • All interactions with microservices happen via Http and it is a totally different paradigm compared to regular application development. The testing and debugging is done via tools like Postman. It takes some getting used to. 
  • Since microservices are well defined units of functionality, they make calls to other microservices for additional information. As a result, there is a lot of dependency between microservices. This can get frustrating, especially during development stage, since some teams keep changing their interfaces constantly. This can also result in a lot of code rewrite.
  • Since microservices depend on other microservices, the capability of a given microservice is limited by those dependencies. For example, a microservice may be able to process 50 requests per minute (RPM), but if one of the other dependency microservice can only handle 20 RPM. then this microservice will need to work with that speed.
  • Since different microservices could potentially be developed and maintained by different teams in different time zones, a great deal of collaboration and understanding is required for completing a project. This can be very frustrating at times and can lead to a lot of friction.
  • You will need to use tools like Splunk (there are several others) for logging and querying information about various microservices. This represents a learning curve, especially if you need to write complex queries for displaying information on dashboards. Splunk, for example, uses regular expressions to query data for meaningful insights. This is again a totally different paradigm compared to typical monolithic applications.
  • You will need to document the functionality provided by each microservice via documentation tools like Swagger or Stoplight (there are others as well). This requires a good deal of work and good attention to detail since your documentation is your source of truth for the service users. Any changes need to be updated promptly as well.

2/22/22

Planning for Error Logging

The purpose of error logging is to log information about errors in a way which makes it easy to diagnose and troubleshoot issues when they arise. While error logging is necessary for all applications, it is indispensable when it comes to large distributed applications. 

In the past, I have written some error logging code but I had never worked on a extensive error logging requirement, that too, from scratch. Last month, as I started work on error logging for a large batch project, I quickly realized that a lack of planning and insight can lead to logs that are hard to track, analyze and troubleshoot and could have disastrous consequences on the outcome of the project. 

Here are some questions and thoughts to keep in mind while planning and coding for it:

  • Questions
    • Why do we want to log errors?
    • What do we want to do with the logs?
    • Are we going to just search and view them in a tool like Splunk?
    • Are we going to build dashboards on top of the logs? if yes, what types of statistics do we want to show on the dashboards?
    • what are the different types of errors that need to be logged to account for the various stats that we are interested in?
    • What information needs to be logged with each error?
    • If we are going to build dashboards, we need to be able to query the logs. So what format makes sense for querying?
  • Thoughts
    • Ensure that the format and structure of the data is concise and meaningful
    • Ensure that the messages and formats are consistent across the board
    • Try to use common libraries and classes to centralize the access to logging code for consistency and ease of maintenance.
    • Create specific exception classes for each scenario, so that we can track, analyze and troubleshoot errors faster.
    • Write extensive unit tests with excellent coverage including tests on specific error messages because it is very difficult to test all scenarios when code changes are made to the error logging code.
    • If you are dealing with microservices, make sure to log all information required to track errors that span several services. RequestId is an example of one such piece of information that can be used to connect a request across various services and help troubleshoot issues.


12/28/19

Designing a Ticket Turnstile System at a Subway Train Station

Recently, I interviewed at a company where the interviewer asked me to explain how I would go about designing a ticket turnstile system at a subway train station. For some inexplicable reason, I just talked about it at a very high level, making incorrect assumptions along the way. I never made an attempt to first write down my thoughts on the notebook in front of me and then try to go about explaining my ideas to the interviewer (and to add to my bad luck, the interviewer also did not ask me to draw or explain anything on the white board).

After I came home, I decided to work on that design again, starting with a basic use case, with a pen and a notebook in hand. As i started writing down my thoughts, I realized that the requirements were not complex at all. By not writing down my ideas on paper, I had just complicated things for myself and that made me come across as an incompetent engineer, incapable of designing software systems. Enough venting and crying. In under 10 minutes this is what I was able to come up with :

  • Consider a simple use case of a person, who has just bought a ticket for a ride from station X to station Y. I am therefore going to assume that there is a unique barcode generator of some sort and when the user bought a ticket, he was assigned a ticket with a unique barcode.
  • Now that the user has bought the ticket, I am going to assume that there is a separate database of all tickets that are current and this particular ticket has been moved to that database. I am assuming that there is one row of information per ticket in the database. This row would include fields like the serial number,location, payment details, IsCheckedIn and IsCheckedOut.
  • My assumption is that once the user scans the ticket at the starting point, the IsCheckedIn field is set to true and when the user exits from the destination station, the IsCheckedOut field is set to true.So considering a happy path, the user would checkin and checkout without any issues and the database would be updated accordingly and that would signal a completed transaction for that ticket.
  • Because the data for each ticket requires just one row, given the fact that there is no other relational data, I am assuming that we do not need to use a relational database. We can use a no-sql database like ravendb where all the information can be stored in a single document or a JSON blob.
  • Because each ticket is unique and there is nothing relational, there shouldn't be any performance issues due to locking of resources. All that needs to happen is the updating of the IsCheckedIn and IsCheckedOut fields for each ticket. As a result, the performance of the system would be a function of the processing power of the database server and the number of connections it can handle.There will be no need for any kind of database replications to keep the information up to date.
  • Now, let us say, the user has bought a ticket and for some reason, he is not able to get into the station (or get out) because the scanner wont recognize his ticket for some reason. So I am going to assume that the user will go to an attendant at the station, who will try to look up the ticket on a computer. So the design would need to include a client, that will point to the same database of all current tickets.
  • Once the user has checked out from the destination station, the IsCheckedOut field will be set to true, meaning that the transaction is complete. This record can then be moved to another database of all completed transactions, where they can stay for a mandated(by government, is my assumption) time period before the same barcodes can be recycled.
  • For security reasons, I am also assuming that both the IsCheckedIn and IsCheckedout fields need to be set to true for a transaction to be considered as complete. My assumption is - the user can scan out only if the user has scanned in.

I still feel bad about not having come up with something along these lines during the interview. This is how I normally approach all my design projects (writing down my thoughts on paper), not sure why I kept talking in the air that day. Was I tense or careless or stressed out or just plain stupid? It still haunts me.

12/2/19

Azure App Services : Serverless functions

Azure offers a set of PAAS(Platform-As-A-Service) offerings known as App Services. Serverless functions are one of the services under the App Services Category.

A Serverless function is a piece of code that can be run independently. It can be triggered by certain events or invoked explicitly depending on the business requirements. Every time a serverless function runs it uses a certain amount of memory and Azure makes sure to run it on the appropriate server (depending on the language used to create the serverless function. You can create serverless functions in different languages like C#, Java, Javascript, Python and some others). So when you configure serverless functions in the Azure portal, you just specify the amount of memory you want to allocate. You do not have to be bothered about managing or scaling the server instances. Because of this, they are known as serverless functions. It is not because they don't run on servers. They do.

Here is an example of a serverless function :

There is a cool online shoe store where you go to buy your shoes. You go to their website and you want to get this brand new model xyz100, but that model is out of stock. So the store offers an option for you to be notified when the stock is replenished. You just need to provide your email which gets stored in their database. Behind the scenes, the store will create a serverless function that will be invoked whenever the model xyz100's stock is replenished. This function will then go to the database and get a list of people(including you) who have requested to be notified when this model is in stock and will send out emails to all of them.


In the case of serverless functions you are charged only when the function runs. You can always increase the amount of memory depending on your business needs. Since serverless functions are stand-alone and can be created in several different languages, they provide a lot of flexibility and freedom when it comes to the development process. You can have separate teams building and managing different functions. You can also choose the technology that best suits the requirement.

App Services in Microsoft Azure : Logic Apps

Azure offers a set of PAAS(Platform-As-A-Service) offerings known as App Services. Logic Apps are one of the services under the App Services Category. They are similar to workflows and can be used to perform a set of connected operations. Here is an example of a logic app :

Let us say there are a set of tables on two different database servers and you are trying to replicate data from one server to the other. Your goal is to monitor the destination tables and perform two specific actions when new data comes in :

  • Call a stored proc that processes the new data and returns a result set.
  • Invoke an API and pass the result set from the previous step.

Within a few minutes, you can create a logic app which can be scheduled to run at specified intervals. This logic app will have two connected nodes. The first one calls a stored procedure that queries the destination tables for new data and does some business rules processing and returns a result set and the second node can then take this result set and pass it to an API.

We can also scale up (i.e. increase the processing power) or scale out (increase the number of instances) very easily via the Azure portal. We do have to deal with any concurrency issues that may arise when several instances of the logic app are running simultaneously.

10/25/19

App Services in Microsoft Azure : Web Apps and Web Jobs

Azure offers a set of PAAS(Platform-As-A-Service) offerings known as App Services. Web Apps and Web Jobs are two of the services under the App Services category.

Before Azure Web Apps, in order to deploy web applications built using the .Net framework, we needed an infrastructure comprising of software and hardware. For example - we needed a machine with a windows operating system, along with the .Net framework components and an IIS web server. We could scale up, but if we needed to scale out, we had to replicate this process several times.

With Web Apps we can now deploy a web application to a Web App without having to worry about setting up any of the underlying infrastructure. Our web application can be up and running in just a few minutes. We can also scale up (i.e. increase the processing power) or scale out (increase the number of instances) very easily via the Azure portal. We can also use Web App as a pre-production environment as well in order to test our application before we go live. We can also do a/b testing with one Web App instance running the production code and another Web App instance running the new features that we are testing. We can then very easily swap the existing production instance with the pre-production instance if needed.

Azure Web jobs are used for deploying batch jobs without worrying about the underlying infrastructure. An example of a batch job that can be deployed to a Web Job would be a windows service. In the past, if we developed a windows service, we needed an infrastructure similar to the web application, in order to install it and run it. With Web Jobs, we just deploy our windows service .exe file to a Web Job and everything is ready to go. Windows Services usually work in tandem with web applications so a Web Job is deployed to the same instance as the related Web App. It is also very easy to debug the Web Apps and Web Jobs.

NOTE: Web Apps and Web jobs support other platforms and languages like Java and Python and others in addition to the .Net platform.

4/14/17

Why do we need Integration Tests?

In the world of software development, every moderately complex software application will have a large code base consisting of several modules. There will be several software developers working on a given module. if you are a software developer, how would you ensure that your changes have not broken some existing functionality? How would you know if some other developer has made some changes that will end up breaking your code changes? One way is to keep testing the application 24/7 and making sure you have covered every possible use case. This is not only a preposterous but also an impossible approach to solving the problem at hand. This is exactly where Integration tests come into play. 

While developing the software application, we create integration tests for as many use cases as we can. At the very least, we need to ensure that we have tests for the core use cases, the bread and butter of the application. Once we have these tests in place, we run them before every new check-in that happens. If any of the existing tests fail, that will mean that the new changes need to reviewed before they can be checked-in. Every developer needs to make it a habit to run these tests before every check-in. 

There should also be continuous integration builds in place for the integration tests project. This will ensure that the tests will get run on different environments along the deployment cycle. This will ensure that there are no environment-specific dependencies that will cause the test to pass in one environment and fail in another. This will ensure that the tests are self-contained and can be run in any environment that we need to. If the company plans to move towards a continuous delivery model, then it becomes even more imperative that the integration tests are run during every build cycle.

Besides the functionality-breaking reasons, there is one other very important reason to have integration tests. Since the integration tests are self-contained, they are repeatable, which means they can be run over and over without causing any side effects. This is something that is not possible functionally. Let us say you are trying to troubleshoot a particular issue that requires certain data to be present. If you wanted to point your code to the application itself, then you would have to recreate the scenario and associated data every single time.This could be a very tiresome and time-consuming process that can be very frustrating. This can be compounded several times if your servers are on different machines across different networks.

With integration tests, you can simulate the issue via code on your local machine. Since the test is repeatable, the required data will need to be created only once. The test can keep creating and dropping the scenario every time it is run. This will eliminate the need to crank up the application on the web server and go through the hassle of creating data inside the application. There is no dependency on external servers and associated latency. We are not impacted if the external servers are brought down for maintenance or if the databases are refreshed.

In the process of troubleshooting the issue via integration tests, we will end up writing more and more integration tests that will remain in place once we have managed to get them to pass. This repeatable nature of integration tests makes them very powerful and valuable.

10/1/16

Designing a Vending Machine

I interact with Vending machines at work every single day, to purchase some snacks or get a drink and so on. I have always wanted to implement one just out of curiosity but never got around to doing it. Then one day I got an email from a software consulting firm asking me if i was interested in interviewing with them and if so, I should do a code exercise and send it back to them. One of the coding exercise options turned out to be a vending machine. It had a set of features that were expected. Though I had no interest in interviewing with that company, I decided that I was going to code the Vending Machine for fun anyways.

Following were the vending machine features in that coding exercise:
  • Accept Coins
    • As a vendor I want a vending machine that accepts coins So that I can collect money from the customer. The vending machine will accept valid coins (nickels, dimes, and quarters) and reject invalid ones (pennies). When a valid coin is inserted the amount of the coin will be added to the current amount and the display will be updated. When there are no coins inserted, the machine displays INSERT COIN. Rejected coins are placed in the coin return. 
    • NOTE: The temptation here will be to create Coin objects that know their value. However, this is not how a real vending machine works. Instead, it identifies coins by their weight and size and then assigns a value to what was inserted. You will need to do something similar
  • Select Product
    • As a vendor I want customers to select products So that I can give them an incentive to put money in the machine. 
    • There are three products: cola for $1.00, chips for $0.50, and candy for $0.65. When the respective button is pressed and enough money has been inserted, the product is dispensed and the machine displays THANK YOU. If the display is checked again, it will display INSERT COIN and the current amount will be set to $0.00. If there is not enough money inserted then the machine displays PRICE and the price of the item and subsequent checks of the display will display either INSERT COIN or the current amount as appropriate.
  • Make Change
    • As a vendor I want customers to receive correct change So that they will use the vending machine again.
    • When a product is selected that costs less than the amount of money in the machine, then the remaining amount is placed in the coin return.
  • Return Coins
    • As a customer I want to have my money returned So that I can change my mind about buying stuff from the vending machine.
    • When the return coins button is pressed, the money the customer has placed in the machine is returned and the display shows INSERT COIN.
  • Sold Out
    • As a customer I want to be told when the item I have selected is not available So that I can select another item.
    • When the item selected by the customer is out of stock, the machine displays SOLD OUT. If the display is checked again, it will display the amount of money remaining in the machine or INSERT COIN if there is no money in the machine.
  • Exact Change Only
    • As a customer I want to be told when exact change is required So that I can determine if I can buy something with the money I have before inserting it.
    • When the machine is not able to make change with the money in the machine for any of the items that it sells, it will display EXACT CHANGE ONLY instead of INSERT COIN.

My implementation included the following classes:

Client: This class represents the end user that will be interacting with the Vending Machine.

public class Client
    {
        public void Start()
        {
            var vm = new VendingMachineFacade(new CoinService(),new ProductService(new ProductRepository(),new ProductInventoryRepository()));

            //case 1 - invalid coins
            var response = vm.AcceptCoin(new InputCoin() { Weight = 1000, Size = 50 });
            if(response.IsSuccess == false)
            {
                //print response.Message to console
                return;
            }

            //case 2 - valid coins,return coins
            vm.AcceptCoin(new InputCoin() { Weight = 100, Size = 50 });
            vm.ReturnCoins();

            //case 3 - valid coins, invalid product code
            vm.AcceptCoin(new InputCoin() { Weight = 100, Size = 50 });
            vm.SelectProduct("COOO1");

            //case 4 - valid coins, valid product code, exact change only
            vm.AcceptCoin(new InputCoin() { Weight = 100, Size = 50 });
            vm.SelectProduct("CO1");

            //case 5 - valid coins, valid product code, less amount entered
            vm.AcceptCoin(new InputCoin() { Weight = 100, Size = 50 });
            vm.SelectProduct("CO1");

            //case 6 - valid coins, valid product code, more amount entered, make change
            vm.AcceptCoin(new InputCoin() { Weight = 100, Size = 50 });
            vm.SelectProduct("CO1");

            //case 7 - valid coins, valid product code, correct(>=) amount entered, sold out
            vm.AcceptCoin(new InputCoin() { Weight = 100, Size = 50 });
            vm.SelectProduct("CO1");

            //case 8 - valid coins, valid product code, correct(>=) amount entered, sold out, return coins
            vm.AcceptCoin(new InputCoin() { Weight = 100, Size = 50 });
            vm.SelectProduct("CO1");
            vm.ReturnCoins();
        }
    }

VendingMachineFacade :  This class represents the vending machine interface that the client will be interacting with.

public class VendingMachineFacade
    {
        private double _cost;
        private CoinService _coinService;
        private ProductService _productService;
        public VendingMachineFacade(CoinService coinService,ProductService prodService)
        {
            _coinService = coinService;
            _productService = prodService;
        }

        //behaviors
        public VendingResponse AcceptCoin(InputCoin coin)
        {
            VendingResponse response = new VendingResponse();                       

            //check if the values correspond to an accepted coin            
            var currentCoin = _coinService.GetCoin(coin.Weight, coin.Size);

            //not a valid coin
            if (currentCoin == null)
            {
                response.Message = "Insert Coin";
                response.IsRejectedCoin = true;
                response.RejectedCoin = coin; //return rejected coin
                return response;                                
            }

            //valid coin
            _cost += currentCoin.Value;
            response.Message = _cost.ToString();
            response.IsRejectedCoin = false;
            return response;
        }
        public VendingResponse SelectProduct(string code)
        {
            var response = new VendingResponse();
            
            //check if the code is valid            
            //if no, return error object with details
            var product = _productService.GetProduct(code);

            //invalid code entered
            if(product == null)
            {
                response.Message = "Invalid Product Selected. Please try again";
                response.IsSuccess = false;
                return response;
            }

            //no coins entered, but selection pressed
            if (_cost == 0)
            {
                //if exact change item, message = "exact change only"
                response.Message = "Insert Coin";
                response.IsSuccess = false;
                return response;
            }

            //entered coins less than cost
            if (_cost < product.Cost)
            {
                response.Message = string.Format("Price : {0}", product.Cost);
                response.IsSuccess = false;
                return response;
            }

            //if exact change product            
            if (_productService.IsExactChangeOnlyProduct(product) && product.Cost != _cost)
            {
                response.Message = "Exact Change Only";
                response.IsSuccess = false;
                return response;
            }

            //all good, valid code and valid amount entered
            var quantity = _productService.GetProductQuantity(code);
            if (quantity > 0)
            {
                response.Message = "Thank You";
                response.IsSuccess = true;
                _productService.UpdateProductQuantity(code);
                MakeChange(_cost - product.Cost);
                return response;
            }
            else
            {
                response.Message = "SOLD OUT";
                response.IsSuccess = false;
                return response;
            }                        
        }
        public ItemChange ReturnCoins()
        {
            return MakeChange(_cost);
        }
        private ItemChange MakeChange(double input)
        {
            ItemChange itemchange = new ItemChange();
            var change = input - _cost;
            if (change == 0) return itemchange;
            double remainingAmount = 0;

            //get the number of quarters in the remaining amount
            var quarters = (int)(change / 0.25);
            if (quarters > 0)
            {
                itemchange.NoOfQuarters = quarters;
                remainingAmount = (change - (quarters * 0.25));
                if (remainingAmount == 0) return itemchange;
            }

            var nickels = (int)(change/ 0.10);
            if(nickels > 0)
            {
                itemchange.NoOfNickels = nickels;
                remainingAmount = (change - (nickels * 0.10));
                if (remainingAmount == 0) return itemchange;
            }            

            var dimes = (int)(change / 0.05);

            if (dimes > 0)
            {
                itemchange.NoOfDimes = dimes;
                remainingAmount = (change - (dimes * 0.05));
                if (remainingAmount == 0) return itemchange;
            }
                        
            return itemchange;
        }        
        private void SoldOut(string code)
        {
            //inventory manager checks quantity
        }
        private void ExactChangeOnly() { }
    }  


InputCoin: This would represent the coin inserted by the user

 public class InputCoin
    {
        public int Weight { get; set; }
        public int Size { get; set; }
    }


CoinService :  This class provides functionality related to Coins.

  public class CoinService
    {
        private static IEnumerable AcceptedCoins = new List() { new Quarter(), new Dime(), new Nickel() };

        public Coin GetCoin(int weight, int size)
        {
            return AcceptedCoins.Where(x => x.Weight == weight && x.Size == size).FirstOrDefault();
        }
    }


ProductService :  This class provides functionality related to the actual products that can be purchased.

  public class ProductService
    {
        private ProductRepository _productRepository;
        private ProductInventoryRepository _productInventoryRepository;
        public ProductService(ProductRepository repository, ProductInventoryRepository inventoryRepository)
        {
            _productRepository = repository;
            _productInventoryRepository = inventoryRepository;
        }

        public int GetProductQuantity(string code)
        {
            var quantities = _productInventoryRepository.GetInventory();
            return quantities[code];
        }

        public Product GetProduct(string code)
        {
            return GetAllProducts().Where(x => x.Code == code).First();
        }

        public IEnumerable GetAllProducts()
        {
            return _productRepository.GetProductList();
        }

        public void UpdateProductQuantity(string code)
        {
            //this should happen in a lock to handle concurrency
            _productInventoryRepository.UpdateInventory(code);
        }

        public bool IsExactChangeOnlyProduct(Product product)
        {
            if (product.Type == ProductType.Chips) return true;
            return false;
        }
    }


ProductRepository : This class is the acts as the ORM layer for interaction with the product datasources.

 public class ProductRepository
    {
        private static List _products;
        //reader writer lock
        public virtual IEnumerable GetProductList()
        {
            if (_products == null)
            {
                _products = new List();
                _products.Add(new Product() { Code = "CO1", Type = ProductType.Cola, Cost = 1.0 });
                _products.Add(new Product() { Code = "CO2", Type = ProductType.Cola, Cost = 1.0 });
                _products.Add(new Product() { Code = "CO3", Type = ProductType.Cola, Cost = 1.0 });

                _products.Add(new Product() { Code = "CH1", Type = ProductType.Chips, Cost = 0.50 });
                _products.Add(new Product() { Code = "CH2", Type = ProductType.Chips, Cost = 0.50 });
                _products.Add(new Product() { Code = "CH3", Type = ProductType.Chips, Cost = 0.50 });

                _products.Add(new Product() { Code = "CA1", Type = ProductType.Candy, Cost = 0.65 });
                _products.Add(new Product() { Code = "CA2", Type = ProductType.Candy, Cost = 0.65 });
                _products.Add(new Product() { Code = "CA3", Type = ProductType.Candy, Cost = 0.65 });
            }

            return _products;
        }
    }
  

ProductInventoryRepository: This class is the acts as the ORM layer for interaction with the product inventory related datasources.

public class ProductInventoryRepository
    {
        private static Dictionary _productQuantities;
        public Dictionary GetInventory()
        {
            if (_productQuantities == null)
            {
                _productQuantities = new Dictionary();
                _productQuantities.Add("CO1", 10);
                _productQuantities.Add("CO2", 10);
                _productQuantities.Add("CO3", 10);

                _productQuantities.Add("CH1", 10);
                _productQuantities.Add("CH2", 10);
                _productQuantities.Add("CH3", 10);

                _productQuantities.Add("CA1", 10);
                _productQuantities.Add("CA2", 10);
                _productQuantities.Add("CA3", 10);
            }

            return _productQuantities;
        }
        public void UpdateInventory(string code)
        {
            //sorround with reader writer lock
            var currentCount = _productQuantities[code];
            if(currentCount > 0)
                _productQuantities[code]--;
        }
    }



ItemChange: This class represents the return amount


public class ItemChange
{
    public int NoOfQuarters;
    public int NoOfNickels;
    public int NoOfDimes;
}


This represents my initial thought process in regards to a Vending Machine implementation. I will continue to tweak this code as time permits and as I get better ideas,

3/13/16

Process Monitor a.k.a Procmon

Process Monitor is an advanced monitoring tool for Windows that shows real-time file system, Registry and process/thread activity. You can get more information here

A couple of months ago, I ran into a very strange issue with some data update functionality involving two separate but related applications, one a WPF client and the other a console application running as a scheduled task.

The data update happened in two ways. In the first case, the user explicitly requested for an update using one of the context menu options inside the WPF Client. In the second case, the data update request was automatically queued up by the same Client when certain state changes happened. These queued requests were then processed by the scheduled console application at a later time.The code to perform the actual data update was in a separate dll and both these applications were referencing the same dll.

What was strange was that the manual request was updating the data successfully whereas the queued up request was failing to do so.

I stepped through the code but I was not able to find anything different. so I decided to use the process monitor to troubleshoot this issue. I ran procmon and monitored the manual data update request. Procmon shows you all the activities like registry access and files being loaded. I didn't notice any assembly loading failures or any other access failures.

I then repeated the same process with the console process. In this case, I noticed that there was an assembly loading failure. The console process was trying to load a particular assembly and it wasn't able to locate it after trying several locations. Procmon shows you all the paths that the process is looking at. The assembly that the process was trying to load was missing and that was the reason for the data update failure. Once we dropped the missing dll into a specific location, the process was able to load it and the data process worked just fine.

We later found out that the install team had forgotten to include that particular dll while building their installers. Once the installer got fixed, the data update issue went away.


3/24/15

Using the Thread Pool in .NET

The Microsoft.Net framework provides a Thread Pool, which is a pool of threads available for applications to use. There is one Thread Pool per CLR and all the Application Domains managed by the CLR will have access to the threads in that Thread Pool.

The applications do not need to go through the hassle of creating and managing the threads as all that is taken care of by the Thread Pool. Using the threads in the Thread Pool is more efficient in terms of resources since the threads can be reused. Using the Thread Pool threads will also lead to an improvement in performance since the creation of threads is a time consuming operation that could negatively impact performance.

One way for applications to use the threads in the Thread Pool is to call the ThreadPool.QueueUserWorkItem method in the System.Threading namespace. This method takes a method and related parameters as input and adds an entry into the Thread Pool's global queue.


//we are adding the method ProcessCreditCard to the ThreadPool queue
System.Threading.ThreadPool.QueueUserWorkItem(ProcessCreditCard, 100);
//this method will be executed by a thread pool thread private void ProcessCreditCard(object input)
{
   //do something here
}
When a thread becomes available in the Thread Pool, it will take this entry from the queue and execute it. The drawback of using this method is that there is no way to interact with the Thread Pool thread that is executing your task. We do not know if the method completed successfully or if there were any exceptions. We also do not have the ability to get a return value from the method. To fix these limitaions Microsoft introduced the concept of Tasks.

Task is a class in the System.Threading.Tasks namespace. It provides an alternative for scheduling tasks for execution by the Thread Pool.

//create a task that will schedule a delegate(ProcessAmount) that returns a bool
 Task t1 = new Task(ProcessAmount);
//this line queues up the delegate for execution by a Thread Pool thread   t1.Start();
//we are waiting for the execution to complete   t1.Wait();
//we are printing the result from the execution   Console.WriteLine(t1.Result);
//this is the delegate that will be executed by a thread pool thread  private bool ProcessAmount()
 {
        return true;
 }
As you can see, we can schedule a task that returns a bool, wait for it to complete and then get the result back.

We also have the ability to cancel the task if necessary.

 CancellationTokenSource source = new CancellationTokenSource();
//this line queues up the delegate for execution by a Thread Pool thread Task t1 = new Task(()=>ProcessAmount(source.Token));
 t1.Start(); source.Cancel();
 private static bool ProcessAmount(CancellationToken token)   {
    //some periodic operation
   //check if the task has been cancelled,    //if yes, this method will throw an OperationCanceledException       token.ThrowIfCancellationRequested();       return true;
   }
The calling code can capture the exception thrown by the Task on cancellation and do whatever is necessary.

The System.Threading.Tasks namespace also contains a static class called Parallel that provides two methods For and ForEach.

Both of them internally use Task objects to execute the code using the Thread Pool threads

//regular For
for(int i=0;i<100 i="" p="">//do something
//Parallel's For
Parallel.For(0,100, SomeDelegate);
When we call the For method of the Parallel class, the thread pool thread's perform this task in parallel resulting in improved performance.It is ideal for situations where you want to execute a large number of tasks in parallel OR if there are long-running tasks. Few operations or short operations are not good for executing in parallel. This is also not an ideal option if the processing needs to happen sequentially since the Thread Pool threads execute in no particular order. This option is also not ideal if the operations share some data since this would require some kind of synchronization that will negatively impact the performance.

Parallel.ForEach and Parallel.Invoke also work similarly.

Parallel LINQ

When dealing with collections via LINQ, we can use Tasks(a.k.a the Thread Pool threads) to execute the operations on the collections in parallel in order to improve performance. This is possible via the AsParallel method of the System.Linq.ParallelEnumerable class. This method can be used to convert sequential queries based on IEnumerable or IEnumerable to parallel queries as follows:

var filteredList = GetItems.AsParallel().where(//do some filtering here);
private IEnumerable GetItems()
{

   //return a list
}
As is the case with Parallel.For and Paralle.ForEach and Parallel.Invoke, Parallel LINQ is ideal for situations where you want to execute a large number of tasks in parallel OR if there are long-running tasks. Few operations or short operations are not good for executing in parallel. This is also not an ideal option if the processing needs to happen sequentially since the Thread Pool threads execute in no particular order. This option is also not ideal if the operations share some data since this would require some kind of synchronization that will negatively impact the performance.

(Reference: CLR via C# by Jeffrey Richter)

4/19/14

Traits in Scala

Scala is a popular programming language that combines the best features of object-oriented and functional programming languages. It has some really cool features that are not available in other languages like C# or Java. Traits is one such feature that provides a viable solution for the problems associated with multiple inheritance in other languages.

Multiple inheritance is not allowed in Java/C# and the only other way to build common functionality among a set of related classes is via interfaces. But interfaces are abstract and require concrete implementation. The other option is to create a class that implements the desired interfaces and then inherit from that class. This is not very convenient.

Following are some of the cool features of a trait:
  • A Trait is much like an abstract class in C#. It can contain abstract members as well as concrete implementations
  • A Trait can contain abstract fields as well as concrete fields
  • A class in Scala can only have one base class but it can implement any number of Traits. So a lot of concrete implementations are readily available for use. 
  • A Trait can extend other Traits.
  • A Trait can extend other classes
  • An instance of a class can implement a Trait. So, not the class, but the desired instances of that class can implement Traits as needed. 
Following are some code samples of Traits:

An abstract Trait called Runner that has an abstract method called Run

trait Runner
{
   def Run(destination:String) //a string input param called "destination"

}


A class called Athlete that provides the implementation for the Trait:
class Athlete extends Runner
{
  //override keyword is not necessary while implementing an abstract method of a trait
  def Run(destination:string) {println(destination)}
}


A concrete Trait called Runner that has a concrete method called Run
trait Runner
{
  def Run(destination:String)  //a string input param called "destination"
  {
    println(destination)

   }
}


A class called Athlete that implements the Trait and calls the Run method. In Scala slang "The Runner functionality is mixed in with the Athlete class"
class Athlete extends Runner { def PrintDestination(destination:String) { Run(destination); } }


A trait called MarathonRunner that extends the trait Runner

trait MarathonRunner extends Runner
{
  def PrintMarathonDestination(destination:String)
  {
   Run(destination)
   }
}


A class called Athlete that implements both Runner and MarathonRunner
class Athlete extends Runner with MarathonRunner { }
NOTE : In Scala, the first trait is implemented using the extends keyword and the second trait is implemented using the with keyword


Let us say that there is a trait called HalfMarathonRunner, an instance of the class Athlete can implement this trait:
val objAthlete = new Athlete with HalfMarathonRunner


A trait with an abstract field
trait Runner
{
 val MaxDistance:int //no initial value means abstract
}


a trait with a concrete field
trait Runner
{
  val MaxDistance = 15
}

2/9/14

Randomizing Display Ads

I was working on the home page of a website that had a small area on the top right corner that was set aside for advertisements. The real-estate had to be shared by four different Ads provided they satisfied the criteria for display. Each had a different criteria that determined their eligibility for display. Criteria included the logged-in user's age, postal code and gender.

So it was possible that at any given time there could be one, two, three or four Ads eligible for display.Then the Ads that were eligible for display had to be randomized to ensure that each had an equal likelihood of appearing on the page.

The model for the page was as follows:


 public class MyHomeModel
  {
   public bool ShowNexusAd {get;set;}
   public bool ShowIpadAd {get;set;}
   public bool ShowSurfaceAd {get;set;}
   public bool ShowKindleAd {get;set;}
  }


So when we returned the model to the view, each of the properties had to have a value of true or false, that would be used in the view to determine whether to hide or show the particular Ad as follows:

@if(model.ShowNexusAd)
{
  //show Nexus Ad
}


For randomization, I decide to use the Random class in .NET to generate a random number in a specified range (1-9) and then use the value generated to determine which ad to show. The code would like this:

if(ShowNexusAd && ShowIpadAd && ShowSurfaceAd && ShowKindleAd)
{
   //generate a number between 1 and 9(including 1)
   Random randomNumber = new Random(1,9) 
   if(randomNumber <=2)
      ShowNexusAd = true;
   if(randomNumber >2 && randomNumber <=4)
      ShowIpadAd = true;
   if(randomNumber >4 && randomNumber <=6)
      ShowSurfaceAd = true;
   if(randomNumber >6 && randomNumber <=8)
      ShowKindleAd = true;
}


But there is a problem here.......

what if only three of the ads were eligible for display or two or just one? we would end up with code as follows:
if(ShowNexusAd && ShowIpadAd && ShowSurfaceAd && ShowKindleAd)

{
 Random randomNumber = new Random(1,9)
 if(randomNumber <=2) 
  ShowNexusAd = true;
 if(randomNumber >2 && randomNumber <=4) 
  ShowIpadAd = true;
 if(randomNumber >4 && randomNumber <=6) 
  ShowSurfaceAd = true;
 if(randomNumber >6 && randomNumber <=8) 
  ShowKindleAd = true;
}else
if(ShowNexusAd && ShowIpadAd && ShowSurfaceAd )
{
 Random randomNumber = new Random(1,7)
 if(randomNumber <=2) 
  ShowNexusAd = true;
 if(randomNumber >2 && randomNumber <=4) 
  ShowIpadAd = true;
 if(randomNumber >4 && randomNumber <=6) 
  ShowSurfaceAd = true;
}else
if(ShowNexusAd && ShowIpadAd && ShowKindleAd)

{
 Random randomNumber = new Random(1,7)
 if(randomNumber <=2) 
  ShowNexusAd = true;
 if(randomNumber >2 && randomNumber <=4) 
  ShowIpadAd = true;
 if(randomNumber >4 && randomNumber <=6)
  ShowKindleAd= true;
}
.......................and so on with all the possible permutations and combinations

As the number of Ads increase(or even for the existing four Ads) it will become a nightmare to extend this logic and even maintain it. So how do we make the code smart enough to handle this?

I hit upon the following idea(which might not be the greatest idea, but is pretty decent)

I created the following classes:

public abstract class AdDisplayBase
{
 public MyHomeModel ViewModel { get; set; }
 public abstract bool ShowAd { set; }
}

public class NexusAdDisplay : AdDisplayBase
{
 public override bool ShowAd
 {
  set { ViewModel.ShowNexusAd = value; }
 }
}

public class IpadAdDisplay : AdDisplayBase
{
 public override bool ShowAd
 {
  set { ViewModel.ShowIpadAd = value; }
 }
}

public class SurfaceAdDisplay : AdDisplayBase
{
 public override bool ShowAd
 {
  set { ViewModel.ShowSurfaceAd = value; }
 }
}

public class KindleAdDisplay : AdDisplayBase
{
 public override bool ShowAd
 {
  set { ViewModel.ShowKindleAd = value; }
 }
}

My goal was to convert the simple value types(the boolean properties) into reference types, so that I could treat them as objects. This would enable me to add the objects to a collection and handle them in a generic manner. To achieve this, I created an abstraction around the boolean properties by creating a class for each type of Ad.

I then refactored the unmanageable conditional logic above to the following method:

void ManageAdsDisplay(MyHomeModel model)
{
  int randomNum;
  var lstAdsToDisplay = new List();

  if (model.ShowNexusAd ) 
     lstAdsToDisplay.Add(new NexusAdDisplay () { ViewModel = model });
  if (model.ShowIpadAd ) 
     lstAdsToDisplay.Add(new IpadAdDisplay () { ViewModel = model });
  if (model.ShowSurfaceAd ) 
     lstAdsToDisplay.Add(new SurfaceAdDisplay () { ViewModel = model });
  if (model.ShowKindleAd ) 
     lstAdsToDisplay.Add(new KindleAdDisplay () { ViewModel = model });
  
  switch (lstAdsToDisplay.Count)
  {
    case 1:
 lstAdsToDisplay[0].ShowAd = true;
 break;
    case 2:
 randomNum = new Random().Next(1, 9);
 lstAdsToDisplay[0].ShowAd = (randomNum <= 4);
 lstAdsToDisplay[1].ShowAd = (randomNum > 4);
 break;
   case 3:
 randomNum = new Random().Next(1, 10);
 lstAdsToDisplay[0].ShowAd = (randomNum <= 3);
 lstAdsToDisplay[1].ShowAd = (randomNum > 3 && randomNum <= 6);
 lstAdsToDisplay[2].ShowAd = (randomNum > 6 && randomNum <= 9);
 break;
  case 4:
 randomNum = new Random().Next(1, 9);
 lstAdsToDisplay[0].ShowAd = (randomNum <= 2);
 lstAdsToDisplay[1].ShowAd = (randomNum > 2 && randomNum <= 4);
 lstAdsToDisplay[2].ShowAd = (randomNum > 4 && randomNum <= 6);
 lstAdsToDisplay[3].ShowAd = (randomNum > 6 && randomNum <= 8);
 break;
  }
}

By doing this we avoid the need to write complicated and confusing conditional statements and it is pretty easy to extend this design if there are more Ads in the future. To be honest, I am not completely happy with the Switch/Case part of the solution and I am trying to find a better way to do this. It will definitely end up as another blog post if I do.

1/25/14

Adapter Design Pattern

The Adapter design pattern is one of the most basic structural design patterns and it's definition is as follows:

"Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces."

Last week I was working on a part of a web application that pulled a list of users from the Database. This application has a pretty good amount of traffic and as the traffic increased it started putting a lot of load on the DB and slowing down the application. In an attempt to find a viable solution, we decided to try out an in-memory cache to store the user data and speed up access. About 25% of the traffic would get the data from the Cache and the rest would continue to go to the Database.

The code changes for the cache repository had to fit seamlessly into the existing design and the changes had to be made without touching the existing implementation for DB calls. The Adapter pattern turned out to be a perfect choice for the requirement.

Following is the code with just the call to the Database:

public class DbRepository
{
  public IEnumerable<user> GetUsers(int userId)
  {
    //call DB and get data
  }
}

//code calling the repository
public class UserService
{
  public IEnumerable<user> GetAllFriendsFor(int loggedInUserId)
  {
    //call DB repository to get data
   DbRepository repository = new DbRepository();
   return repository.GetUsers(loggedInUserId);    
  }
}

Following is the code after implementing the Adapter design pattern:

public interface IRepository
{
  IEnumerable<user> GetUsers(int userId);
}

public class CacheRepository:IRepository
{
  public IEnumerable<user> GetUsers(int userId)
  {
    //call cache and get data
  }
}

//the adapter
public class DbRepositoryAdapter:DbRepository,IRepository
{
}

public class RepositoryFactory
{ 
  //a variable that determines if the user is in test
  bool UserInCacheTest {get;set;}
  
  //return the appropriate repository
  public IRepository GetRepository()
  {
    if(UserInCacheTest)
   return new CacheRepository();
 
 return new DbRepositoryAdapter();
}
}


//code calling the repository
public class UserService
{
  public IEnumerable<user> GetAllFriendsFor(int userId)
  {
    //call the factory to get the appropriate repository
   IRepository repository = new RepositoryFactory().GetRepository();
   return repository.GetUsers(userId);    
  }
}
Explanation:

  • We create a new interface called IRepository that has a single method. This method will have the same signature as the method in the exisiting DbRepository since we are going to be adapting that repository to fit into the new design. NOTE: Using the same signature as in the existing DbRepository is just a matter of convenience, it is not necessary to do so.
  • We then create a new repository called DbRepositoryAdapter that will inherit from the existing DbRepository and implements the IRepository interface.The DbRepository already has a method with the same signature as the method in IRepository, so it is safe to say that the DbRepositoryAdapter implements the IRepository interface. NOTE: If the signature of the interface method was different, we would need to implement that method and call the DbRepository's method from inside it.
  • We create a new class called CacheRepository that also implements IRepository. 
  • We create a factory class called RepositoryFactory that will return a repository of type IRepository depending on whether the user is in the cache test. 
  • The CacheRepository and the DbRepositoryAdapter both implement IRepository, so we can use interface polymorphism within the UserService to return the appropriate repository.
  • We have incorporated the existing DbRepository into our new design by creating an adapter class on top of it. This way the existing DbRepository class and the new CacheRepository class can work well together.(NOTE: we have not touched the existing DbRepository in any way.). This is the advantage of using the Adapter design pattern.

3/10/13

Generic Contravariance in C#

In my previous post .NET interfaces Part 3 I had written about the IEqualityComparer interface which has the following signature:

 public interface IEqualityComparer<in T>
 {
        bool Equals(T x, T y);        
        int GetHashCode(T obj);
 }
 
The keyword "in" before the type T indicates that this interface is contravariant.

In the same post we were calling the Contains method on a collection of type FootballStar as shown below:

FootballStars.Contains(Peyton2,new StarComparer())
We were passing in an instance of type IEqualityComparer<Star> to a method that was expecting an IEqualityComparer<FootballStar> i.e we were able to pass a less derived type than was specified by the type parameter.

This was possible because the interface IEqualityComparer<in T> is a contravariant interface that allows us to pass a less derived type than the specified type parameter.

Even though we are passing in a less derived type, everything works perfectly because the instances that ultimately get passed to the Equals method of the IEqualityComparer method are still of type FootballStar(since the collection is of type FootballStar), which derives from Star.

If the interface was not Contravariant, we would have to create a new IEqualityComparer of type FootballStar and pass that to the contains method. The compiler will not have it any other way. We would also have to repeat this for every type that derived from Star, assuming that all instances of type Star(e.g. FootballStar, BaseballStar) wish to use the same logic to determine the equality of their instances.

We would end up writing code like this:

//a comparer for FootballStar instances
public class FootballStarComparer:IEqualityComparer<FootballStar>
{
}
//that will be passed to contains FootballStars.Contains(Peyton2,new FootballStarComparer())

//a comparer for BaseballStar instances public class BaseballStarComparer:IEqualityComparer<BaseballStar> { }
//that will be passed to contains BaseballStars.Contains(bbStar1,new BaseballStarComparer())
So instead of using the type inheritance heirarchy and polymorphism we would be writing a lot of repititive code to perform similar tasks.

3/9/13

.NET interfaces Part 3

IEqualityComparer<T>

 public interface IEqualityComparer<in T>
 {
        bool Equals(T x, T y);        
        int GetHashCode(T obj);
 }
 
When to use it:
Let us say you have a custom Type and you plan to use instances of that type in a collection. If you want to use methods like List<T>.contains or Dictionary<T1,T2>.Add, you will need to way to check if an item in your collection equals the item we are trying to find.To facilitate this you can implement the IEqualityComparer<T>.

How is it different from IEquatable<T>?
For every custom type that you wish to check for Equality, you will need to implement the IEquatable<T> interface. But if you have a set of related base/child classes that share a common Equality check functionality, you need to create just one IEqualityComparer<T> where T is the Base type and use it with all other types.

public abstract class Star
    {
        public int Age { get; set; }
        public int GamesPlayed { get; set; }
        public int PointsScored { get; set; }
    }

    public class FootballStar : Star
    {
       
    }

    public class BaseballStar : Star
    {

    }

    //This comparer can be used by all instances of type Star 
    public class StarComparer: IEqualityComparer<Star>
    {
        //strongly typed input parameter
        public bool Equals(Star input1, Star input2)
        {
            if (input1.GamesPlayed == input2.GamesPlayed && 
                  input1.PointsScored == input2.PointsScored) 
               return true;
            return false;
        }
        
        public int GetHashCode(Star input)
        {
            //the XOR value
            return input.GamesPlayed ^ input.PointsScored;
        }
    }

    //calling code
    class Program
    {
        static void Main(string[] args)
        {
     FootballStar Brady = new FootballStar() 
                   { Age = 35, GamesPlayed = 900, PointsScored = 55000 };
            FootballStar Peyton = new FootballStar() 
                   { Age = 35, GamesPlayed = 500, PointsScored = 30000 };
            FootballStar Rodgers = new FootballStar() 
                   { Age = 28, GamesPlayed = 500, PointsScored = 31000 };
            FootballStar Griffin = new FootballStar() 
                   { Age = 28, GamesPlayed = 400, PointsScored = 20000 };

            List FootballStars = new List() 
                   {Brady, Peyton, Rodgers, Griffin};
            
            FootballStar Peyton2 = new FootballStar() 
                  { Age = 35, GamesPlayed = 500, PointsScored = 30000 };

            /* the Equals method of the comparer will be used to 
                  determine the equality
               */
    Console.WriteLine(FootballStars.Contains(Peyton2,new StarComparer()));

            /* Add internally calls GetHashCode of the StarComparer 
                  and will not let you add two keys with the same HashCode
               */
         Dictionary StarDictionary = new Dictionary(3,new StarComparer());
            StarDictionary.Add(Brady, "Patriots");
            StarDictionary.Add(Peyton, "Denver");
            StarDictionary.Add(Rodgers, "Greenbay");
            StarDictionary.Add(Griffin, "Washington");

            //Contains and ContainsKey will both internally call 
            //comparer's Equals and GetHashCode methods
            Console.WriteLine(StarDictionary.ContainsKey(Peyton2));
   Console.WriteLine(StarDictionary.Contains(new KeyValuePair(Peyton2, "Denver")));
 }
}
NOTE:
Since the type T of the comparer is of type Star, any types that derive from it can use the same equality comparer as long as they wish to use the same criteria for determining equality. e.g. if the instances of the type BaseballStar were used in a collection, we can use the same EqualityComparer to test for Equality since BaseballStar inherits from Star

.NET interfaces Part 2

IEquatable<T>

 public interface IEquatable<t>
 {       
   bool Equals(T other);
 }
When to use it:
Let us say you have a custom Type and you plan to use instances of that type in a collection. If you want to use methods like List<T>.contains or List<T>.IndexOf you will need to way to check if an item in your collection equals the item we are trying to find.To facilitate this your custom Type needs to implement the Equals method of IEquatable<T>.

NOTE: Since we are checking for equality, we need to override the default implementations of Object.Equals and Object.GetHashCode methods so that they are consistent with the IEquatable<T>.Equals method.

 public class BasketballStar : IEquatable<BasketballStar>
 {
 public int Age { get; set; }
 public int GamesPlayed { get; set; }
 public int PointsScored { get; set; }

     //The IEquatable's Equals method with a strongly typed 
     //input parameter
     public bool Equals(BasketballStar input)
     {
      if(this.GamesPlayed==input.GamesPlayed && 
         this.PointsScored==input.PointsScored) 
        return true;
      return false;
     }

       //overriding the base Equals to keep consistency with the 
       //Equatable's Equals
 public override bool Equals(object input)
 {
    BasketballStar objStar = input as BasketballStar;
    if (objStar == null) return false;
    return this.Equals(objStar);
 }

 /*
         override the base GetHashCode to be consistent with the 
         Equals methods Since we are basing equality based on games
         played and point scored, the hash code is also an XOR of 
         the same properties. So if two objects are equal, the Equals 
         method must return true and thier GetHashCode values must 
         be the same
        */
 public override int GetHashCode()
 {
    //the XOR value
    return this.GamesPlayed ^ this.PointsScored;
 }
 }

//calling code
class Program
{
   static void Main(string[] args)
   {
     BasketballStar Jordan = new BasketballStar() 
                   { Age = 50, GamesPlayed = 900, PointsScored = 55000 };
     BasketballStar Kobe = new BasketballStar() 
                   {Age = 35, GamesPlayed = 500, PointsScored = 30000};
     BasketballStar Lebron = new BasketballStar() 
                   { Age = 28, GamesPlayed = 500, PointsScored = 31000 };
     BasketballStar Durant = new BasketballStar() 
                   { Age = 28, GamesPlayed = 400, PointsScored = 20000 };
     BasketballStar Jordan2 = new BasketballStar() 
                   { Age = 50, GamesPlayed = 900, PointsScored = 55000 };

    //using a list
   List lstStars = new List();
   lstStars.Add(Jordan);
   lstStars.Add(Kobe);
   lstStars.Add(Lebron);
   lstStars.Add(Durant);

   //contains method internally calls the Equals 
          //method of IEquatable
   Console.WriteLine(lstStars.Contains(Jordan2));

   //using a dictionary
   Dictionary StarsDictionary = new Dictionary(3);

   //Add internally calls GetHashCode and will not let you add two 
          //keys with the same HashCode
   StarsDictionary.Add(Jordan, "Chicago Bulls");
   StarsDictionary.Add(Kobe, "Lakers");
   StarsDictionary.Add(Lebron, "Miami");
   StarsDictionary.Add(Durant, "Oklahoma");

   //the contains and containsKey methods both internally call the 
          //GetHashCode as well as the IEquatable's Equals method
   //so both of them need to return consistent values
   Console.WriteLine(StarsDictionary.ContainsKey(Jordan2));
   Console.WriteLine(StarsDictionary.Contains(new KeyValuePair(Jordan2, "chicago bulls")));
 }
}

3/5/13

.NET interfaces - Part 1

I was re-reading some .net basics a couple of weeks ago just to refresh my memory and I came across some core interfaces that I had used in the past.

At that time i was not blogging and hadn't had a chance to write any posts about them. So I was thinking now is probably a good time to do it.

IComparable<T>


public interface IComparable<in T>
{       
  int CompareTo(T other);
}
When to use it:
Let us say you have a custom Type and you plan to use instances of that type in a collection. Whenever you are dealing with collections one of the obvious requirements is that the items in the collection be sortable.To facilitate this your custom Type needs to implement the CompareTo method of IComparable.

Code is as follows:

public class Texas : IComparable
{
        public string Name { get; set; }
        public int Population { get; set; }

/*
This method compares the population of the current instance with the input instance.
returns 0 if they are equal, 1 if this instance's population is greater than the input's population
and -1 if this instance's population is less than the input's population
*/
public int CompareTo(Texas input)
{
   if (this.Population < input.Population) return -1;
   if (this.Population == input.Population) return 0;
   return 1;
} 
}

//calling code

class Program
{

 static void Main(string[] args)
 {

  List lstTexas = new List();

  lstTexas.Add(new Texas() {Name = "Austin", Population = 500});
  lstTexas.Add(new Texas() {Name = "Houston", Population = 1500});
  lstTexas.Add(new Texas() {Name = "Dallas", Population = 900});
  lstTexas.Add(new Texas() {Name = "San Antonio", Population = 1200});
  lstTexas.Add(new Texas() {Name = "Waco", Population = 200});

  /*
     Sort internally calls the CompareTo method.The CompareTo method is 
     usually not called explicitly but is called from methods
     like the List<T>.Sort or Add(in a sorted list)
  */
   lstTexas.Sort();

  foreach (Texas city in lstTexas)
   Console.WriteLine(city.Name);

 }

}


//output - the cities are sorted in the ascending order of their populations
Waco
Austin
Dallas
San Antonio
Houston

NOTE: When you call Sort() with no arguments, you can only sort in ascending order OR descending order depending on your logic inside the CompareTo method. If you wish you can specify a sort order by using the overload of Sort that takes a Comparision delegate as an argument.