Agile Software Architecture Sketches and NoUML

June 26, 2013 § Leave a comment

Interesting article I read on  about the role architecture in Agile development. So I thought to share it in my blog.


Agile Software Architecture Sketches and NoUML

Posted by Simon Brown

If you’re working in an agile software development team at the moment, take a look around at your environment. Whether it’s physical or virtual, there’s likely to be a story wall or Kanban board visualising the work yet to be started, in progress and done. Visualising your software development process is a fantastic way to introduce transparency because anybody can see, at a glance, a high-level snapshot of the current progress. As an industry, we’ve become pretty adept at visualising our software development process over the past few years although it seems we’ve forgotten how to visualise the actual software that we’re building. I’m not just referring to post-project documentation, this also includes communication during the software development process. Agility is about moving fast and this requires good communication, but it’s surprising that many teams struggle to effectively communicate the design of their software.

Prescribed methods, process frameworks and formal notations

If you look back a few years, structured processes and formal notations provided a reference point for both the software design process and how to communicate the resulting designs. Examples include the Rational Unified Process (RUP), Structured Systems Analysis And Design Method (SSADM), the Unified Modelling Language (UML) and so on. Although the software development industry has moved on in many ways, we seem to have forgotten some of the good things that these older approaches gave us. In today’s world of agile delivery and lean startups, some software teams have lost the ability to communicate what it is they are building and it’s no surprise that these teams often seem to lack technical leadership, direction and consistency. If you want to ensure that everybody is contributing to the same end-goal, you need to be able to effectively communicate the vision of what it is you’re building. And if you want agility and the ability to move fast, you need to be able to communicate that vision efficiently too.

Abandoning UML

As an industry, we do have the Unified Modelling Language (UML), which is a formal standardised notation for communicating the design of software systems. I do use UML myself, but I only tend to use it sparingly for sketching out any important low-level design aspects of a software system. I don’t find that UML works well for describing the high-level software architecture of a software system and while it’s possible to debate this, it’s often irrelevant because many teams have already thrown out UML or simply don’t know it. Such teams typically favour informal boxes and lines style sketches instead but often these diagrams don’t make much sense unless they are accompanied by a detailed narrative, which ultimately slows the team down. Next time somebody presents a software design to you focussed around one or more informal sketches, ask yourself whether they are presenting what’s on the sketches or whether they are presenting what’s still in their head.

 (Click on the image to enlarge it)

Abandoning UML is all very well but, in the race for agility, many software development teams have lost the ability to communicate visually too. The example NoUML software architecture sketches (above) illustrate a number of typical approaches to communicating software architecture and they suffer from the following types of problems:

  • Colour-coding is usually not explained or is often inconsistent.
  • The purpose of diagram elements (i.e. different styles of boxes and lines) is often not explained.
  • Key relationships between diagram elements are sometimes missing or ambiguous.
  • Generic terms such as “business logic” are often used.
  • Technology choices (or options) are usually omitted.
  • Levels of abstraction are often mixed.
  • Diagrams often try to show too much detail.
  • Diagrams often lack context or a logical starting point.

Some simple abstractions

Informal boxes and lines sketches can work very well, but there are many pitfalls associated with communicating software designs in this way. My approach is to use a small collection of simple diagrams that each show a different part of the same overall story. In order to do this though, you need to agree on a simple way to think about the software system that you’re building. Assuming an object oriented programming language, the way that I like to think about a software system is as follows … a software system is made up of a number of containers, which themselves are made up of a number of components, which in turn are implemented by one or more classes. It’s a simple hierarchy of logical building blocks that can be used to model most of the software systems that I’ve encountered.

  • Classes: in an OO world, classes are the smallest building blocks of our software systems.
  • Components: components (or services) are typically made up of a number of collaborating classes, all sitting behind a coarse-grained interface. Examples might include a “risk calculator”, “audit component”, “security service”, “e-mail service”, etc depending on what you are building.
  • Containers: a container represents something in which components are executed or where data resides. This could be anything from a web or application server through to a rich client application, database or file system. Containers are typically the things that need to be running/available for the software system to work as a whole. The key thing about understanding a software system from a containers perspective is that any inter-container communication is likely to require a remote interface such as a web service call, remote method invocation, messaging, etc.
  • System: a system is the highest level of abstraction and represents something that delivers value to, for example, end-users.

Summarising the static structure of your software with NoUML

By using this set of abstractions to think about a software system, we can now draw a number of simple boxes and lines sketches to summarise the static structure of that software system as follows (you can see some examples on Flickr):

  1. Context diagram: a very high-level diagram showing your system as a box in the centre, surrounded by other boxes representing the users and all of the other systems that the software system interfaces with. Detail isn’t important here as this is your zoomed out view showing a big picture of the system landscape. The focus should be on people (actors, roles, personas, etc) and software systems rather than technologies, protocols and other low-level details. It’s the sort of diagram that you could show to non-technical people.
  2. Containers diagram: a high-level diagram showing the various web servers, application servers, standalone applications, databases, file systems, etc that make up your software system, along with the relationships/interactions between them. This is the diagram that illustrates your high-level technology choices. Focus on showing the logical containers and leave other diagrams (e.g. infrastructure and deployment diagrams) to show the physical instances and deployment mappings.
  3. Components diagrams: a diagram (one per container) showing the major logical components/services and their relationships. Additional information such as known technology choices for component implementation (e.g. Spring, Hibernate, Windows Communication Foundation, F#, etc) can also be added to the diagram in order to ground the design in reality.
  4. Class diagrams: this is an optional level of detail and I will typically draw a small number of high-level UML class diagrams if I want to explain how a particular pattern or component will be (or has been) implemented. The factors that prompt me to draw class diagrams for parts of the software system include the complexity of the software plus the size and experience of the team. Any UML diagrams that I do draw tend to be sketches rather than comprehensive models.

(Click on the image to enlarge it)

A single diagram can quickly become cluttered and confused, but a collection of simple diagrams allows you to easily present the software from a number of different levels of abstraction. And this is an important point because it’s not just software developers within the team that need information about the software. There are other stakeholders and consumers too; ranging from non-technical domain experts, testers and management through to technical staff in operations and support functions. For example, a diagram showing the containers is particularly useful for people like operations and support staff that want some technical information about your software system, but don’t necessarily need to know anything about the inner workings.

Organisational ideas, not a standard

This simple sketching approach works for me and many of the software teams that I work with, but it’s about about providing some organisational ideas and guidelines rather than creating a prescriptive standard. The goal here is to help teams communicate their software designs in an effective and efficient way rather than creating another comprehensive modelling notation. It’s worth reiterating that informal boxes and lines sketches provide flexibility at the expense of diagram consistency because you’re creating your own notation rather than using a standard like UML. My advice here is to be conscious of colour-coding, line style, shapes, etc and let a set of consistent notations evolve naturally within your team. Including a simple key/legend on each diagram to explain the notation will help too.

There seems to be a common misconception that “architecture diagrams” must only present a high-level conceptual view of the world, so it’s not surprising that software developers often regard them as pointless. In the same way that software architecture should be about coding, coaching and collaboration rather than ivory towers, software architecture diagrams should be grounded in reality too. Including technology choices (or options) is a usually a step in the right direction and will help prevent diagrams looking like an ivory tower architecture where a bunch of conceptual components magically collaborate to form an end-to-end software system.

“Just enough” up front design

As a final point, Grady Booch has a great explanation of the difference between architecture and design where he says that architecture represents the “significant decisions”, where significance is measured by cost of change. The context, containers and components diagrams show what I consider to be the significant structural elements of a software system. Therefore, in addition to helping teams with effective and efficient communication, adopting this approach to diagramming can also help software teams that struggle with either doing too much or too little up front design. Starting with a blank sheet of paper, many software systems can be designed and illustrated down to high-level components in a number of hours or days rather than weeks or months. Illustrating the design of your software can be a quick and easy task that, when done well, can really help to introduce technical leadership and instil a sense of a shared technical vision that the whole team can buy into. Sketching should be a skill in every software developer’s toolbox. It’s a great way to visualise a solution and communicate it quickly plus it paves the way for collaborative design and collective code ownership.

Top JavaScript MVC Frameworks

June 19, 2013 § 3 Comments

As more and more logic ends up being executed in the browser, JavaScript front-end codebases grow larger and more difficult to maintain. As a way to solve this issue developers have been turning to MVC frameworks which promise increased productivity and maintainable code. As part of the new community-driven research initiative, InfoQ is examining the adoption of such frameworks and libraries by developers.

  • Backbone.js: Provides models with key-value binding and custom events, collections, and connects it all to your existing API over a RESTful JSON interface.
  • AngularJS: A toolset based on extending the HTML vocabulary for your application.
  • Ember.js: Provides template written in the Handlebars templating language, views, controllers, models and a router.
  • Knockout: Aims to simplify JavaScript UIs by applying the Model-View-View Model (MVVM) pattern.
  • Agility.js: Aims to let developers write maintainable and reusable browser code without the verbose or infrastructural overhead found in other MVC libraries.
  • CanJS: Focuses on striking a balance between size, ease of use, safety, speed and flexibility.
  • Spine: A lightweight framework that strives to have the most friendly documentation for any JavaScript framework available.
  • Maria: Based on the original MVC flavor as it was used in Smalltalk – aka “the Gang of Four MVC”.
  • ExtJS: Amongst other things offers plugin-free charting, and modern UI widgets.
  • Sammy.js: A small JavaScript framework developed to provide a basic structure for developing JavaScript applications.
  • Stapes.js: A tiny framework that aims to be easy to fit in an existing codebase, and because of its size it’s suitable for mobile development.
  • Epitome: Epitome is a MVC* (MVP) framework for MooTools.
  • soma.js: Tries help developers to write loosely-coupled applications to increase scalability and maintainability.
  • PlastronJS: MVC framework for Closure Library and Closure Compiler.
  • rAppid.js: Lets you encapsulate complexity into components which can be easy used like HTML elements in your application.
  • Serenade.js: Tries to follow the ideas of classical MVC than competing frameworks.
  • Kendo UI: Combines jQuery-based widgets, an MVVM framework, themes, templates, and more.

Apache Solr vs ElasticSearch

May 16, 2013 § 1 Comment

Other day I had really good discussion on Apache Solr. I was totally fascinated with Apache Solr, when I did my last project. Another competitive product came to discussion. I still haven’t started playing around with Elastic Search. Here is start to my pet project

Apache Solr vs ElasticSearch

The Feature Smackdown


Feature Solr 4.2 ElasticSearch 0.90.0.RC1
Binary API   SolrJ  TransportClient, Thrift (through a plugin)
JMX support
Client libraries  PHP, Ruby, Perl, Scala, Python, .NET, Javascript PHP, Ruby, Perl, Scala, Python, .NET, Javascript, Erlang, Clojure
3rd-party product integration (open-source) Drupal, Magento, Django, ColdFusion, WordPress, OpenCMS, Plone, Typo3, ez Publish, Symfony2, Riak (via Yokozuna) Django, Symfony2
3rd-party product integration (commercial) DataStax Enterprise Search SearchBlox


Feature Solr 4.2 ElasticSearch 0.90.0.RC1
Data Import DataImportHandler – MySQL, CSV, XML, Tika, URL, Flat File Rivers modules – Wikipedia, MongoDB, CouchDB, RabbitMQ, RSS, Sofa, JDBC, FileSystem, Dropbox, ActiveMQ, LDAP, Amazon SQS, St9, OAI, Twitter
ID field for updates and deduplication
Partial Doc Updates   with stored fields  with _source field
Custom Analyzers and Tokenizers 
Per-field analyzer chain 
Per-doc/query analyzer chain 
Synonyms   Supports Solr and Wordnet synonym format
Multiple indexes 
Near-Realtime Search/Indexing 
Complex documents   Flat document structure. No native support for nesting documents
Multiple document types per schema   One set of fields per schema, one schema per core
Online schema changes   Schema change requires restart. Workaround possible using MultiCore.  Only backward-compatible changes.
Apache Tika integration 
Dynamic fields 
Field copying   via multi-fields
Hash-based deduplication 


Feature Solr 4.2 ElasticSearch 0.90.0.RC1
Lucene Query parsing 
Structured Query DSL   Need to programmatically create queries if going beyond Lucene query syntax.
Span queries   via SOLR-2703
Spatial search 
Multi-point spatial search 
Faceting   The way top N facets work now is by getting the top N from each shard, and merging the results. This can give incorrect counts when num shards > 1.
Pivot Facets 
More Like This
Boosting by functions 
Boosting using scripting languages 
Push Queries   Percolation
Field collapsing/Results grouping   possibly 0.20+
Spellcheck  Suggest API
Autocomplete Beta implementation from community plugin
Query elevation 
Joins   It’s not supported in distributed search. See LUCENE-3759.  via has_children and top_children queries
Filter queries   also supports filtering by native scripts
Filter execution order   local params and cache property  _cache and _cache_key property
Alternative QueryParsers   DisMax, eDisMax  query_string, dis_max, match, multi_match etc
Negative boosting   but awkward. Involves positively boosting the inverse set of negatively-boosted documents.
Search across multiple indexes  it can search across multiple compatible collections
Result highlighting
Custom Similarity 
Searcher warming on index reload   Warmers API


Feature Solr 4.2 ElasticSearch 0.90.0.RC1
Pluggable API endpoints 
Pluggable search workflow   via SearchComponents
Pluggable update workflow 
Pluggable Analyzers/Tokenizers
Pluggable Field Types
Pluggable Function queries
Pluggable scoring scripts
Pluggable hashing 


Feature Solr 4.2 ElasticSearch 0.90.0.RC1
Self-contained cluster   Depends on separate ZooKeeper server  Only ElasticSearch nodes
Automatic node discovery  ZooKeeper  internal Zen Discovery or ZooKeeper
Partition tolerance  The partition without a ZooKeeper quorum will stop accepting indexing requests or cluster state changes, while the partition with a quorum continues to function.  Partitioned clusters can diverge unless discovery.zen.minimum_master_nodes set to at least N/2+1, where N is the size of the cluster. If configured correctly, the partition without a quorum will stop operating, while the other continues to work. See this
Automatic failover  If all nodes storing a shard and its replicas fail, client requests will fail, unless requests are made with the shards.tolerant=true parameter, in which case partial results are retuned from the available shards.
Automatic leader election
Shard replication
Automatic shard rebalancing   it can be machine, rack, availability zone, and/or data center aware. Arbitrary tags can be assigned to nodes and it can be configured to not assign the same shard and its replicates on a node with the same tags.
Change # of shards  specified at index-creation time, with command-line param -DnumShards=n. Cannot be changed once index is created. Shard splitting is a work in progress (SOLR-3755). Additional replicas can be created.  each index has 5 shards by default. Number of primary shards cannot be changed once the index is created. Replicas can be increased anytime.
Relocate shards and replicas   can move shards and replicas to any node in the cluster on demand
Control shard routing   with some config changes  routing parameter
Consistency Indexing requests are synchronous with replication. A indexing request won’t return until all replicas respond. No check for downed replicas. They will catch up when they recover. When new replicas are added, they won’t start accepting and responding to requests until they are finished replicating the index. Replication between nodes is synchronous by default, thus ES is consistent by default, but it can be set to asynchronous on a per document indexing basis. Index writes can be configured to fail is there are not sufficient active shard replicas. The default is quorum, but all or one are also available.


As a number of folks point out in the discussion below, feature comparisons are inherently shallow and only go so far. I think they serve a purpose, but shouldn’t be taken to be the last word on these 2 fantastic search products.

If you’re running a smallish site and need search features without the distributed bells-and-whistles, I think you’ll be very happy with either Solr or ElasticSearch.

The exception to this is if you need RIGHT NOW some very specific feature like field grouping which is currently implemented in Solr and not ElasticSearch. Because of the considerable momentum behind ElasticSearch, it is very likely that the feature-set between the 2 products will converge considerably in the near future.

If you’re planning a large installation that requires running distributed search instances, I suspect you’re going to be happier with ElasticSearch.

As Matt Weber points out below, ElasticSearch was built to be distributed from the ground up, not tacked on as an ‘afterthought’ like it was with Solr. This is totally evident when examining the design and architecture of the 2 products, and also when browsing the source code.



If you see any mistakes, or would like to append to the information on this webpage, you can clone the GitHub repo for this site with:

git clone

and submit a pull request.

How Would You Build Up a City from Components?

April 3, 2013 § 6 Comments

I read one of most interesting article in and love the way it was put across. Here it goes


How Would You Build Up a City from Components?

Posted by Aliaksei Papou


More and more enterprise application development is moving to component frameworks and solutions. Why? Does component architecture have any future? I believe yes and soon all development frameworks will be component-based – it is imminent. Let me show you why.

How do you build up your house? You start with building blocks. It is possible to compare the construction of a web application with the construction of your small country house. You can quickly build up a very good looking application with all the required functionality. Every room in your house is created for specific needs, for instance the kitchen, living room, bedroom or bathroom. The layout of the house allows you to conveniently move between rooms using the corridors and stairs.

You are doing better now and can afford to build a bigger and better house – you would like to have a sauna, a pool, a movie theater and of course a giant aquarium filled with reptiles☺. But changing the design of your house can be quite difficult. If you are able to add the extra facilities the house ends up not looking so nice. It is also less convenient since your additions had to be put in inconvenient places, so that, for instance, to get into the billiard room you have to pass through the main bedroom.

In the end your nice and neat house turns into an awkward and uncomfortable house with a bunch of different functions within it. The same story can happen with application development.

The question is, is it possible to design an application such that it can grow and change according to your needs? Let’s try to figure it out.

Components are building blocks of the application

Components are the primary means of extending application functionality. The process of creating components is a bit different from the creation of applications based on them. The component should not only provide useful functionality but be designed for reuse from the outset.



Reuse of components

To easily reuse components they should be designed with a loose coupling approach. To make this possible, different frameworks typically implement their event models based on the Observer pattern. This allows multiple recipients to subscribe to the same event.

The Observer pattern was originally implemented in Smalltalk. Smalltalk is a user interface framework based on MVC and is now a key part of MVC frameworks. I would like to draw your attention to the fact that the Observer pattern has existed in Java since version 1.0. Let’s have a deeper look into it.


The following UML diagram describes the Observer pattern:

Here is a basic Java implementation

public class ObservableX extends Observable {
  public void setAmount(double amount) {
    this.amount = amount;

  public class ObserverA implements Observer {
  public void public void update(Observable o) {
  // gets updated amount

  public class ObserverB implements Observer {
  public void public void update(Observable o) {
  // gets updated amount

//instantiate concrete observableX
ObservableX observableX = new ObservableX();
//somewhere in code
observableX.addObserver(new ObserverA());
observableX.addObserver(new ObserverB());
//much later


How it works:

Firstly we create an instance of ObservableX class, add the ObserverA and ObserverB instances into the observableX object and then somewhere in the code we set the value for “some amount” using the setAmount method. The functionality of the observable class notifies all the registered observers about the received amount.

The Observer acts as a mediator that maintains the list of recipients. When some event occurs within a component it is sent to all recipients from that list.

Due to the mediator the component isn’t aware of its recipients. And the recipients can subscribe to the events of different components of a particular type.

A class can become a component when it uses events to notify observers about its changes. And this can be achieved by using the Observer pattern.

To use components is easier than to create them

Using components you can quickly create a variety of forms, panels, windows, and other composite elements of the interface. However, to be able to re-use the new composite parts they should be turned into components.

In order to achieve this you do need to determine the external events that the component will generate as well as the mechanism of sending messages. I.e. you need to at least create new event classes and define interfaces or callback methods for receiving those events.

This approach makes the implementation of reusable application components more complex. It is fine if the system consists of a small number of composite elements – up to around ten. But what if the system consists of hundreds of such elements?

Conversely, not following this approach will lead to tight coupling between elements and will reduce the chances of re-use to zero. This, in its turn will lead to code duplication that will make maintenance more complicated in future and will lead to a growing number of bugs in the system.

The problem is compounded by the fact that users of the components often do not know how to define and send new events to their parts. But they can easily use ready-made events provided by the component framework. They know how to receive events but don’t know how to send them.

To solve this problem, let’s consider how to simplify the use of the event model in applications.

Too many Event Listeners

In Java Swing, GWT, JSF and Vaadin the Observer pattern is used for implementation of an event model where multiple users can subscribe to one event. Lists to which Event Listeners are added serve as the implementation. When the relevant event occurs it is sent to all the recipients of that list.

Each component creates its own set of Event Listeners for one or more events. This leads to an increasing number of classes in the application. That, in its turn, makes support and development of the system more complicated.

With annotations Java gained a way to have individual methods subscribe to particular events. As an example consider the implementation of the event model in CDI (Contexts and Dependency Injection) from Java EE 6.

 public class PaymentHandler {
      public void creditPayment(@Observes @Credit PaymentEvent event) {

public class PaymentBean {

    Event<PaymentEvent> creditEvent;

   public String pay() {
     PaymentEvent creditPayload = new PaymentEvent();
            // populate payload ... 

As you can see the PaymentEvent is fired when the pay() method of the PaymentBean object is called. After that the creditPayment () method of the PaymentHandler object receives the paymentEvent.

Another example is in the implementation of the Event Bus in Guava Libraries:

 // Class is typically registered by the container.
class EventBusChangeRecorder {
  @Subscribe public void recordCustomerChange(ChangeEvent e) {
// somewhere during initialization
eventBus.register(new EventBusChangeRecorder());
// much later
public void changeCustomer() {
  ChangeEvent event = getChangeEvent();;

The EventBus registers the object of the EventBusChangeRecorder class. Then calling the changeCustomer() method results in the EventBus receiving the ChangeEvent object and calling the recordCustomerChange () method of the EventBusChangeRecorder object.

Now you don’t need to implement a number of Event Listeners for your components, making the use of events in applications simpler.

The Event Bus usage is convenient when all the components are displayed at the same time on the screen and they use the Event Bus for message exchange, as shown in the picture below.

Here all these elements – the header, left menu, content, right panel – are components.

Subscribed to events – don’t forget to unsubscribe

By replacing Event Listeners with annotations we have made a big step forward in simplifying the use of the event model. But even so, every component in the system needs to be connected with the Event Bus, and then has to subscribe events to it and, at the right time, unsubscribe from it.

It is possible to hit a situation when the same recipient is subscribed several times to the same event, which can lead to a number of repeated notifications. A similar situation can arise when multiple system components subscribe to the same event, which can trigger a series of cascade events.

To be able to control the event model better, it makes sense to move the work with events out to configuration and make the application container responsible for events management. Since particular events are available only on particular conditions, it is reasonable to move the management of their state out to configuration as well.

A sample configuration is shown below:

<?xml version="1.0"?>
<application initial="A">

    <view id="A">
        <on event="next" to="B"/>

    <view id="B">
        <on event="previous" to="A"/>
        <on event="next" to="C"/>

    <view id="C">
        <on event="previous" to="B"/>
        <on event="next" to="D"/>

    <view id="D">
        <on event="previous" to="C"/>
        <on event="finish" to="finish"/>

    <final id="finish" /> 


The transition to the B view will be initiated by the “next” event from the A view. From the B view the user can go back to the A view by the “previous” event or to the C view by the “next” event. From the D view the finish event leads to the “final” state which instructs the application to finish up the workflow within the application.

Finite State Machines are specifically designed for such needs. A state machine is a mathematical model of computation. It is conceived as an abstract machine that can be in one of a finite number of states, but only in one state at a time, known as the current state. An event or condition can trigger a transition to another state. Using this approach you can easily define an active screen and have an event trigger a transition to another screen.

The benefits of using Finite State Machines for configuring the application

In most cases application configuration is defined statically. Configuring the application with dependency injection we define application structure on startup. But we forget that while exploring the application its status can change. Change of state is often hard-coded in the application code which leads to complications in future adjustments and maintenance.

Moving the transitions between states into configuration gives more flexibility. And that’s why when creating composite application elements, such as forms, windows or panels, we don’t need to worry about what state the application should go to. You can do this later, setting the behavior in the configuration.

All the components can communicate using a standardized mechanism for sending events – through the Event Bus. At the same time, the state machine can control the subscription of component events to the Event Bus. This approach turns all components of the application (forms, windows, panels) into reusable components that can be easily managed from the external configuration.

If you are interested you can have a look at some examples of configuration in the Enterprise Sampler.

You can consider state configuration as a road map of a city, and events as cars delivering goods and people to the desired destinations.

I’m sure using this approach it is easy to design and build up not just a small and ready to grow house but a whole city with skyscrapers, broadways and highways.

Some practices to write better C#/.NET code

February 8, 2013 § Leave a comment

I was reading an article on code project and I totally agree with this article below. There are lot of things that makes simple when code is written right


Just re posting in my blog


Some practices to write better C#/.NET code

By Monjurul Habib,


Developers always love to fight about coding standards. But it is very vital to follow coding standards to achieve consistency throughout the project or code. All should be of the same mind that conventions are very influential. I will show some good practices that i have learned during my professional years, those are lower level but very important for all levels.

Quick Test

Let us demonstrate a FizzBuzz example. The FizzBuzz test is to write a program that goes through the numbers 1 to 100. For every multiple of 3, the program should output “Fizz” and for every multiple of 5 it should output “Buzz”. If both above conditions are met it should output “FizzBuzz”. If none of the above conditions are met, it should just output the number.

Example 1:

 Collapse | Copy Code
public void Test()
           for (int i = 1; i < 101; i++)
               string Output = "";
               if (i % 3 == 0) { Output = "Fizz"; }
               if (i % 5 == 0) { Output += "Buzz"; }
               if (Output == "") { Output = i.ToString(); }

What do you think ? Do we need to make the code better?
Example 2:

 Collapse | Copy Code
public void Check()
           for (int i = 1; i <= 100; i++)
               string output = "";
               if (i % 3 == 0) { output = "Fizz"; }
               if (i % 5 == 0) { output += "Buzz"; }
               if (output == "") { output = i.ToString(CultureInfo.InvariantCulture); }

What do you think now ? Do we need to make the code even better?

Ok, let me help you to make it better. Naming thing is one of the hardest job we have as a software developer. Because we spend a lot of time naming things, there are so many things to name properties, methods, classes, files, projects etc. We should spend some energies for naming things because names can be meanings. Adding meaning to code is readability all about.

 Collapse | Copy Code
     public void DoFizzBuzz()
           for (int number = 1; number <= 100; number++)
               var output = GetFizzBuzzOutput(number);

     private static string GetFizzBuzzOutput(int number)
           string output = string.Empty;
           if (number%3 == 0)
               output = "Fizz";
           if (number%5 == 0)
               output += "Buzz";
           if (string.IsNullOrEmpty(output))
               output = number.ToString(CultureInfo.InvariantCulture);
           return output;

What do you think now? Is it better than previous examples ? isn’t it more readable?

What is better Code?

Write code for People First, Computers Second. Readable code doesn’t take any longer to write than confusing code does, at least not in the long run. It’s easier to be sure your code works if you can easily read what you wrote. That should be a sufficient reason to write readable code. But code is also read during reviews. It’s read when you or someone else fixes an error. It’s read when the code is modified. It’s read when someone tries to use part of your code in a similar project.

“What if you just writing code for yourself? Why should you make it readable?”

Because a week or two from now you’re going to be working on another project. What will happen when any other HUMAN needs to fix an error on that project? I can guarantee you that you will also lost within your own horror code.

From my point of view a better should carried out the following characteristics:

  • Code that is easy to write , modify and extend
  • Code that is clean and talks/convey meaning
  • Code that has values and cares about quality

there are many more but above are very import.

How can you improve the Readability?

First You have to read other peoples code and figure out what is good and what is bad within that code. What makes you easy to understand and what makes you feel more complicated. Then apply those things to your own code. Finally you need sometime, some experience and you need some practice to improve the readability of your code. It is very hard but obvious to implement standards in any software company, through methods like Trainings, Peer Code Reviews, Introducing automated code review tools etc. Most popular tools are as follows:

FxCop is a tool that performs static code analysis of .NET code. It provides hundreds of rules that perform various types of analysis.

StyleCop is an open source project that analyzes C# source code to enforce a set of style and consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project. StyleCop has also been integrated into many third-party development tools.

JetBrains ReSharper is a renowned productivity tool that makes Microsoft Visual Studio a much better IDE. Thousands of .NET developers worldwide wonder how they’ve ever lived without ReSharper’s code inspections, automated code refactoring, blazing fast navigation, and coding assistance.

What are Conventions?

You should be able to tell the difference between a property, local variable, method name, class name etc. because they use different capitalization conventions. These type of conventions has values. You will be able to get lots of guidelines and conventions over internet. So find a convention or build your own and stick with it.

The source of the following (Design Guidelines for Developing Class Libraries) was developed by the Microsoft special interest group. I just made some addons.

Capitalization Conventions

Below are some examples of our C# coding standards, naming conventions, and best practices. Use these according to your own needs.

Pascal Casing

The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. You can use Pascal case for identifiers of three or more characters.

Camel Casing

The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized.

Ref. Capitalization Rules for Identifiers

Example of some Naming Conventions Guidelines

You will find enough resources over internet. I am just highlighting some of my favorites among them

C# Coding Conventions
C# Coding Guidelines
C# Coding Standards and Best Programming Practices
C# Coding Standards and Naming Conventions

I am providing some basic level examples below but as I already mentioned, find a good convention that fits for you and stick with it.

DO use PascalCasing for class names and method names.

 Collapse | Copy Code
public class Product
    public void GetActiveProducts()
    public void CalculateProductAdditinalCost()

DO use camelCasing for method arguments and local variables.

 Collapse | Copy Code
public class ProductCategory
  public void Save(ProductCategory productCategory)
       // ...

DO NOT use Abbreviations

 Collapse | Copy Code
// Correct
ProductCategory productCategory;

// Avoid
ProductCategory prodCat;

DO NOT use Underscores in identifiers

 Collapse | Copy Code
// Correct
ProductCategory productCategory;

// Avoid
ProductCategory product_Category;

DO prefix interfaces with the letter I.

 Collapse | Copy Code
public interface IAddress


DO declare all member variables at the top of a class, with static variables at the very top.

 Collapse | Copy Code
public class Product
    public static string BrandName;

    public string Name{get; set;}
    public DateTime DateAvailable {get; set;}

    public Product()
        // ...

DO use singular names for enums. Exception: bit field enums.

 Collapse | Copy Code
public enum Direction

DO NOT suffix enum names with Enum

 Collapse | Copy Code
public enum DirectionEnum

Why we need Conventions?

Conventions offer several specific benefits. They let you take more for granted. By making one global decision rather than many local ones, you can concentrate on the more important characteristics of the code.

  • They help you transfer knowledge across projects
  • They help you learn code more quickly on a new project.
  • They emphasize relationships among related items.

Programmers on large projects sometimes go overboard with conventions. They establish so many standards and guidelines that remembering them becomes a full-time job. The computer doesn’t care whether your code is readable. It’s better at reading binary machine instructions than it is at reading high-level-language statements.
You should write readable code because it helps other people to read your code. Naming thing is one of the hardest job we have as a software developer. Because we spend a lot of time naming things, there are so many things to name properties, methods, classes, files, projects etc. We should spend some energies for naming things because names can be meanings. Adding meaning to code is readability all about.

So it will help you better sleep at night.


Top Rules Developer Should Follow

Try to Avoid Comments

This is topic create some interesting conversations among all level of developers. But I almost never write comments on my code. Most comments i have ever seen is trying to describe the purpose/intentions. But comments are meaningless and C# compilers ignores comments.They have no impact what the code really does.They don’t influence the generated code at all. Most of comments are meaningless noise.

 Collapse | Copy Code
//ensure that we are not exporting
 //deleted products
  if(product.IsDeleted && !product.IsExported )
       ExportProducts = false;

But if name the method like CancelExportForDeletedProducts() instead of comments what will happen? Method names are more affective than comments. Methods execute and they are real.But comment is ok when visual studio will take comments for creating an API documentation and those comments are different, you can use “///” for those comments so that other developers can get intelligence of your API or Library.

I am NOT telling you that avoid comment is a must for all the times. If comment is trying to describe the purpose/intentions then it is wrong. If you look at thickly commented code, you will notice that most of those comments are there because the code is bad. Please read the following books for further detail:

  • Professional Refactoring in C# & ASP.NET” by Danijel Arsenovski
  • Refactoring: Improving the Design of Existing Code” by Martin FowlerKent BeckJohn BrantWilliam Opdykedon Roberts

Avoid Unnecessary Regions in Class

Regions are a feature of VS that allow you to surround blocks of code. It could be a single or multiple methods. The region exists because it is easier to navigate around the large file. The regions are used to hide ugly code or class that have exploded in size . If a class does too many things it also violates the Single Responsibility Principle. So next time whenever you will think for adding a new region to your file take step back and ask that is it possible to separate your region into a separate class.

Keep method Short

The more lines of code in a method the harder it is to understand. Everyone recommends 20-25 lines of code is ok. But I do prefer 1-10 lines for safe. But there is no hard and fast rule for this just make sure that you are not violatingSRP.

Avoid Too Many Parameters

Declare a class instead of too many parameters. Creating a class that puts all these parameters together. This is generally a better design and valuable abstraction.

 Collapse | Copy Code
public void Checkout(string shippingName, string shippingCity, string shippingSate, string shippingZip, string billingName, string billingCity, string billingSate, string billingZip)

 Collapse | Copy Code
public void Checkout(ShippingAddress shippingAddress,BillingAddress billingAddress)


We should introduce class instead of all parameters.

Avoid Complex Expressions

 Collapse | Copy Code
if(product.Price>500 && !product.IsDeleted && !product.IsFeatured && product.IsExported)
             // do something

Complex expression have some meaning behind them it is just hidden by those multiple expressions. We can Encapsulated the complex expression into that object by using a property. That code will be easier to read.

Consider Warnings as Errors

If you notice the code you will find a variable that was declared but never used. Normally if we build the project we will get a warning and we can run our project without any error. But we should remove warning as much as possible. So setup your build to treat warning as Errors like the following steps:


Avoid Multiple Exit Points

This rule is very easy to follow. Developer should try to maintain single exit point and entry point.

 Collapse | Copy Code
               return false;
           else if(product.IsDeleted)
               return false;
           else if(!product.IsFeatured)
               return false;
           else if()
           return true;
 Collapse | Copy Code
       var isValid = true;
               isValid= false;
           else if(product.IsDeleted)
               isValid= false;
           else if(!product.IsFeatured)
               isValid= false;
           return isValid;

You can imagine 4 exit points scattered around 20- 30 lines of code.That makes you more harder to understand and see what is happening inside the method and what will execute and when will execute.

I got too many responses, some agreeing but mostly disagreeing that it was a good  “standard” to enforce. To find out the potentiality I did some unit testing and found that for complex method that have multiple exit points usually have a set of tests for each of those paths. Once work is done, get the heck out of there isn’t always possible because sometime you need to clean up your resources as well.

 Collapse | Copy Code
if( BADFunction() == true)
    // expression
    if( anotherFunction() == true )
     // expression
     return true;
 return false;
 Collapse | Copy Code
  if( !GoodFunction())
    // error.
    return false
     // expression
 if( !GoodFunction2())
    return false;
 // more expression
 return true;

Please read Controlling Loops chapter from the book “Code Complete” by Steve McConnell for further detail clarification on Multiple Exit Points.


An assertion is code that’s used during development—usually a routine or macro—that allows to check itself as it runs.True means everything is operating as expected. False means it has detected an unexpected error in the code.An assertion usually takes two arguments: a boolean expression that describes the assumption that’s supposed to be true and a message to display if it isn’t.

Assertions are especially useful in large, complicated and in high reliability system.

Example: If a system assumes that there will be maximum 100,000 user records, the system might contain an assertion that the number of records is less than or equal to 100,000. So assertion will be silent within that range. If it encounters more than that records,it will loudly “assert” that there is an error in the program.

Checking Loop Endpoints

A single loop usually has three cases of interest: the first case, an arbitrarily selected middle case, and the last case.If you have any special cases that are different from the first or last case, check those too. If the loop contains complex computations, get out your calculator and manually check the calculations.


It is obvious to implement standards in any software company according to organizational behavior, project nature and domain. So I would like to repeat “Find a convention and stick with it.” .

If you think I missed any prominent guideline,please leave that in the comments section. I’ll try to include that in the main post. Coding For Fun.

Creating a simple application using MVC 4.0

November 5, 2012 § Leave a comment

Source : Code Project



In this article, we will understand what is MVC and create a simple application using Model, View and Controller.

Model View Controller: MVC is a software architecture, which separates the logic from the user interface. This is achieved by separating the application into three parts Model, View and Controller. MVC is separation of concern. MVC is also a design pattern.

Model:Represents the logical behavior of data in the application. It represents applications business logic. Model notifies view and controller whenever there is change in state.

View: Provides the user interface of the application. A view is the one which transforms the state of the model into readable HTML.

Controller: Accepts inputs from the user and instructs the view and model to perform the action accordingly.

Advantages of MVC:

  1. Full control over HTML rendered. No renaming of HTML IDs
  2. Provides clean separation of concerns (SoC).
  3. No ViewState (Stateless).
  4. Enables Test Driven Development (TDD).
  5. Easy integration with JavaScript frameworks.
  6. RESTful URLs that enables SEO. Representational state transfer URLs example User/Comment/1, which is user friendly, no URL rewriting required.
  7. Integration on the client side becomes easy like using JavaScript, JQuery, Ajax, JSON….
  8. Supports multiple view engines (aspx, Razor)

Creating a simple application:

Step-1: From file select project and select MVC 4.0 application

Step-2:Select the template and view engine (Razor, ASPX, NHaml, Spark). If want to include test project check the option “Create unit test project”

A solution with following structure is added.

Build and run the application, you can see the home page of the application. By default we have Home, About and Contact section added.

Let’s add our own Controller, Model and View for showing User’s details. Right click on Model and add a class with the name UserModels.cs with the following structure:

Now let’s apply validations on the fields:

  • Required: To make the field value mandatory.
  • StringLength: To set the maximum length of the field.
  • Range: To set the minimum and maximum value.
  • DataType: To set the type supported by the field.

Let’s add some default data to our view. For that we will create a class called user and initialize with some default value.

Now let’s add methods for Adding, Updating and getting list of all users.

Now let’s add view for our model for that we will select strongly-typed view and select our model class. You can see list of scaffold templates available. Since we are creating this view to add a new user we will select Create option.

The moment we click on Add, below is the cshtml created for the view

We can see the view is having all the fields set in the model along with the validations applied on it.

Now let’s add a controller for our view. Right click on controller folder name our controller as User, select Empty MVC controller and Add.

By default our controller contains an Index method. Right click on the index method and add view for this. Index method can be used to show the list of user’s available. So we can select scaffold template type as list.

Once the view is added for Index and UserAdd, we have to define its get and post method in the controller. By default its always get, if we want a post method we have to define [httppost] before the method declaration.

HttpGet: will render the form and HttpPost will post the form data. For example we need to add a new user. First we need the form to add a user, that is get and when we will the form with values we need to post those values, so that it can be saved for further access.

Look at our controller structure, it contains two get methods, one to get the list of users (Index) and other to get theUserAdd form and with the same name it contains its post method.

ActionResult: An action result represents a command that the framework will perform on behalf of the action method. The ActionResult class is the base class for action results. Common return Type:

ContentResult: Can be used to return plain text or user defined content type.

 Collapse | Copy Code
public ContentResult Test() 
    return Content("This is my test data");

JsonResult: Used to return JSON, mainly used for Ajax request.

 Collapse | Copy Code
public JsonResult Test() 
    return Json ("This is my test json data");

PartialViewResult: The PartialViewResult class is inherited from the abstract “ViewResultBase” class and is used to render a partial view.

 Collapse | Copy Code
public PartialViewResult Test() 
    return PartialView("Result");

ViewResult: It renders a specified view.

 Collapse | Copy Code
public ViewResult Test() 
   return View("Result"); 

FileResult: It is used when we want to return the binary content/file as an output.

RedirectToRouteResult:  It is uesd when we want to redirect to another action method.

JavaScriptResult: If we want our action method to return a script that can be executed on the client side we can use this type.

Three new types which are supported from MVC 3

1. HttpNotFound: This returns 404 error on client side. It can be useful in situations where the resource is not available and we want to display 404.

2. RedirectResult:  It can be a temporary or permanent return code 302 depending upon the boolean flag. Can be used to redirect to the given URL

3.  HttpStatusCodeReturn: It can be used when user want’s the choice of error code to be returned from the action method. It can be any code.

Routing with MVC: 
MVC gives great flexibility for adding user friendly URL’s.  Routings are defined under the class RouteConfig. By default one route is already defined.

MVC routing pattern include {controller} and {action} placeholder. For more details on routing please refer this link

This is how our index page will appear with the URL:

And the UserAdd method, here controller is User and Action is UserAdd.

Points of Interest

More keen in learning MVC 4.0 new features. Lets learn to build a simple application then we can move ahead with advanced features.

Doing Arrays – C#

October 22, 2012 § Leave a comment


An array is a collection of same type variables which can be accessed using numeric index. The numeric index is written in square brackets after the array name.


  • Characteristics
  • Single Dimension Array
  • Iterating Through Single Dimension Array
  • 2D Arrays
  • 3D Arrays …
  • Bounds of Multi Dimensional Arrays
  • Jagged Arrays
  • Mixed Arrays

Following is the declaration of a single dimension array:

int[ ] roll = new int[8];


The numeric index is zero based. It goes from 0 to n-1 where n is size of array (total number of elements in array).

On declaration, default value of numeric type arrays is set to 0, and reference types are set to null.

Arrays are stored in continuous memory locations as shown in the figure.

In C#, arrays are objects, and they have certain properties like Length, which can be used by using (.) and property name. All arrays are derived from abstract class arrays so many built-in methods can be called.

//Rank propety Return number of dimensions 
int[ ] single = new int[4] { 1, 2, 3, 4 }; 
int dimension = single.Rank;

Single Dimension Arrays

It is the simplest form of array, it’s kind of a row with n columns where each column is accessed with the zero based index. The above two code examples show single dimension arrays.

In C#, declaration of array is a bit different from C or C++. Here square brackets are placed after type name, then array-name, keyword new and then type with square brackets containing size of array.

Type[ ] arrayname = new Type[size];

The following code initializes a single dimension integer array of size 5. It contains 5 elements which can be accessed byarr[0] to arr[4].

//Integer Array declaration
int[ ] arr = new int[5];

Character type arrays are declared as follows:

//Character type array
char[ ] name = new char[10];

In the same way, string type arrays are declared:

//String array declaration
string[ ] days = new string[7];

There are many ways to assign values to array. Array can be initialized in declaration line by placing the values between curly braces { } in comma separated fashion. Characters are placed in single quotes and strings are placed in double quotes.

//Integer Array Initialization    
int[ ] arr = new int[5] { 1, 2, 3, 4, 5 };  
//Character Array Initialization    
char[ ] name = new char[10] { 'i', ' ', 'a', 'm', ' ', 'f', 'i', 'n', 'e', '.' };  
//String Array Initialization 
string[ ] days = new string[7] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

While initializing the array, size of array may be omitted. Then size of array will be calculated number of elements written in curly braces.

One other way of declaring, initializing array is:

//Integer Array Declaration, Initialization
int[ ] arr;arr = new int[5] { 1, 2, 3, 4, 5 };

Following way of assigning values to array will cause Error.

//Wrong way of writing
int[ ] arr = new int[5];
arr = { 1, 2, 3, 4, 5 };

Iterating Through Single Dimension Array

Since in C#, arrays are objects and they retain certain built in properties. Length property returns total number of elements in array. Right now we are dealing with single dimension, so total number of elements is equal to size of array.

for (int i = 0; i < arr.Length; i++)

Multi Dimensional Arrays

2D Arrays

Arrays can be multidimensional. The most widely used are two dimensional arrays, often Matrices form 2D arrays. In 2D array, 2 zero based index are used to access a particular value in the array.

//Integer 2D Array
int[,] matrix = new int[10, 10];
//Accessing Value
int val = matrix[5, 7];

Value of element stored in 5th Row, 7th Column i.e., 58, will be assigned to variable val. Rows and Columns have zero based index. Total number of values which can be stored in 2D array is equal to product of rows and columns. For the above case, it is 100.

Single dimension array is a single Row with columns >0. 2D arrays have more than one Row, thus form a table.

Accessing the element stored in 3rd row, 4th column in balances table.

To initialize 2D array, each row values are placed in curly braces as in the case of a single dimensional array and then these set of curly braces for all rows are placed in another set of curly braces in the same fashion.

//2D Array Initializtion
int[,] arr_2d = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; 
//Initializing 2Dimensional Array
char[,] day = new char[2, 3] { { 'o', 'n', 'e' }, { 't', 'w', 'o' } };

In the above piece of code, there are 3 rows, 2 columns, thus total number of elements is 2 x 3 = 6. It’s hard to initialize 2D array shown in the 1st figure, where it has 10 rows and 10 columns. Loops can be used to assign values to each location.

//Assigning Values to matrix[10,10] array
for (int i = 0; i < 10; i++)
    for (int j = 0; j < 10; j++)
        matrix[i, j] = i * 10 + j + 1;                    

In case of multidimensional arrays, knowing number of dimensions is sometimes necessary to have more grip over the array. Rank property returns number of dimensions of the array.

//Getting Number of dimensions of array
int dim = matrix.Rank;

The GetUpperBound function returns the upper bound of the array in a particular dimension.

for (int i = 0; i <= matrix.GetUpperBound(0);i++)
    for (int j = 0; j <= matrix.GetUpperBound(1); j++)
        Console.Write(matrix[i, j].ToString() + "\t");

Output of the above piece of code is as follows:

GetLowerBound method gets the lower bound of the array in a particular dimension. The following figure shows the difference between length, upper bound and lower bound.

3D Arrays

We can have more than two dimensions for arrays as well. For three dimensional array, we need three indexes to access each element in array. Example of 3 dimensional array can be a point in space. Consider a block of small bricks, as shown in figure below, to address each small brick, there is one index for row, one for column and one for depth.

//Block code 3D array
int[, ,] block_3d = new int[2, 3, 4];

4D Arrays

Example of 4 dimensional array can be taken as one second in a week, there are 60 seconds in one hour, 60 mins in one hour, 24 hours a day and 7 day a week.

//Week 4D array
int[, , ,] week = new int[7, 24, 60, 60];

Jagged Arrays

Array of arrays are called jagged arrays.

The statement might be confusing but consider the example of saving marks of few students who are studying different number of subjects.

Student-1 marks 65, 60, 76
Student-2 marks 78, 92, 68, 90, 55
Student-3 marks 45, 59, 88, 72

If we use 2 Dimensional array to store the above marks, then an array of 3 rows and 5 columns is needed. The extra info needs to be added at locations for which marks don’t exist.

65 60 76 0 0
78 92 68 90 55
45 53 88 72 0

Jagged arrays come in handy in such situations. Jagged arrays may have different sizes and dimensions. For this situation, we need one single dimension array with three elements, and each of its elements is a single dimension array with length 3, 5, 4 respectively.

//Jagged arrays
int[ ][ ] student = new int[3][ ];

In the above piece of code, two sets of square brackets are used. Now each element of Jagged array needs to be assigned to a single dimension array.

//Declaring Each Element of Jagged Array
student[0] = new int[3];
student[1] = new int[5];
student[2] = new int[4];

Values can also be assigned just like single dimension array by placing after square brackets.

//Initializing Each Element of Jagged Array
student[0] = new int[3] { 65, 60, 76 };
student[1] = new int[5] { 78, 92, 68, 90, 55 };
	student[2] = new int[4] { 45, 59, 88, 72 };

A short way of doing this is:

//Jagged arrays
int[ ][ ] student = new int[3][ ]
{new int[3] { 65, 60, 76 },new int[5] { 78, 92, 68, 90, 55 },
	new int[4] { 45, 59, 88, 72 }};

Jagged arrays are reference type, thus they are initialized to null. To access elements in jagged array in studentexample, 2 indexes are used.

//Accessing elements in Jagged Array
student[2][2] = 80;for (int i = 0; i < student.Length; i++)
    for (int j = 0; j < student[i].Length; j++)

Mixed Arrays

Combination of jagged and multidimensional arrays is known as mixed arrays. In case of multidimensional arrays of different sizes, mixed arrays are used. Consider there are three tables, each with different number or rows and columns.

Table-1 3 rows, 5 columns
Table-2 4 rows, 3 columns
Table-2 6 rows, 4 columns
//Mixed Arrays int [ ][,]mixed=new int[3][ ]
     new int[3,5],
     new int[4,3],
     new int[6,4]

Where Am I?

You are currently browsing the Programs & Algorithms category at Naik Vinay.