Getting Started with the MEAN stack (Mongodb Express Angular Node) – What is MEAN
 

I’ve been helping out some friends with setting up a new site for their endeavors. The basic requirements were

  1. The site needs to be a ‘single page application’ (SPA)
  2. Should be light weight
  3. Should be easy to deploy to one of the many available hosted environments

MEAN stands for the set of technologies used in application development, much like the LAMP (Linux, Apache, MySql and PHP) stack before it. The technologies and frameworks involved in the MEAN stack include Mongodb, Express Js, Angular Js, and Node Js. From a comparative standpoint, I believe that MEAN is popular today, for many of the same reasons that the LAMP stack gained popularity earlier.

Despite their limitations, both development stacks received a strong push from the community, have ubiquitous ‘Hello, World!’ tutorials, are supported on a number of cheap (and sometimes free!) PAAS hosting providers, and required little to no prior experience to get off the ground, giving instant results with minimal effort. They might not be the best dev stacks of their times, but the sheer inertia from their communities has also played a major role in the two being among the most popular web development platforms in the world today.

Why use the MEAN stack

One of the primary advantages of the MEAN stack that the code is written in Javascript, through all layers of the stack. This means that the programmer’s experience with one language (Javascript), is reused for everything, including persistence and server side code (in addition to the usual client side manipulation using a UI framework, which in this case, happens to be AngularJS)

The other big advantage of having javascript at all levels in your dev stack is that objects don’t need to be marshaled and unmarshaled when moving from one layer to another, usually removing the boilerplate code responsible for such conversions. This also helps developers take advantage of Javascript’s loosely typed nature to manipulate data as and when needed. Considering that Mongodb is a document database, and ‘documents’ don’t really *need* to have a fixed schema, this lines up pretty well with Javascript’s the loosely typed nature allowing us to do some really interesting things.

One of the drawbacks that I have personally experienced, however, of the MEAN stack is that developers with prior experience primarily in relational databases tend to continue to think in terms of tables. Relating collections to tables, and documents to records isn’t wrong, conceptually, but the patterns for relational patterns don’t necessarily lend themselves favourably to NoSql databases. Relational databases tend to have long, mature histories with a standardized set of interfaces and features that a developer can reasonably expect to get if he chooses any of the competing options out there.

Sadly, in my experience, NoSql is nothing like that. Different implementations (read databses) have widely differing ideologies on the ‘Right Way’™ of doing things, and they are correct! This is mostly because each implementation seems to be built for a slightly different use case, that needs different trade-offs to make the system function efficiently (for the chosen scenario). This doesn’t mean the databases can’t be used for anything outside their original intended mainline use cases, just that the default settings for the system may not be the best for you. The minor differences in behaviors also means that again, patterns identified for one NoSql database may not be the best for a different one.

While this may change in future as the stack matures and ‘enterprise patterns’ (I hate that term, but it seems apt for this situation) emerge and become ‘common knowledge’ ingrained in a majority of the developers out there, this is not the case today.

Check out the next post on how we got started.

MEAN stack Part 2 – Yeoman and generator-angular-fullstack

Maintaining IEnumerable-Yield Data Pipeline is Hard
 

C# and .Net had IEnumerable and yield since its early versions. And I think its one of the most misunderstood features of C#. This is because of the pattern of deferred/lazy execution implementation.  Before we delve deep into this let us understand the iterator model.

IEnumerable and IEnumerator:

This is the foundation of the C# Iterator pattern and there are a number of detailed articles about this by Eric Lippert. The simple example is here.

There is a basket full of Oranges.

 
public class Basket
{
    private readonly IEnumerable Oranges;

    public Basket(IEnumerable oranges)
    {
        Oranges = oranges;
    }

    public IEnumerable GetOranges()
    {
        return Oranges;
    }
}

public class Orange
{
    public int NumberOfSlices { get; set; }

    public void Peal()
    {
            
    }

    public void Consume()
    {
            
    }
}

And if we have to consume oranges, we will have to peel each one of them. So we can use a simple iterator pattern on them.

var basket = new Basket(new [] { new Orange(), new Orange(), new Orange() });
foreach (var orange in basket.GetOranges())
{
    orange.Peal();
    orange.Consume();
}

But the problem is, we need not consume all the oranges from the basket at one go (I am not Hungry ;-).
So how can I get one orange from the basket at a time? or whenever I am Hungry?

Yield:

C# Yield keyword provides an answer to this problem. Slightly changing the Basket class using Yield keyword. (signature of the GetOranges Method not changed)

public class Basket
{
    private readonly Orange[] _oranges;

    public Basket(Orange[] oranges)
    {
        _oranges = oranges;
    }

    public IEnumerable GetOranges()
    {
        for (int i = 0; i < _oranges.Length; i++)
        {
            yield return _oranges[i];
        }
    }
}

Now the basket will provide one Orange at a time. ie when MoveNext() Method of the IEnumerator is called. In other words, we have paused execution of the “for” loop in GetOranges method till the time the next Orange is required.

Or in more technical words, until you Enumerate, the data will not be fetched and once Enumerated, there is no data. It all boils down to “when you Enumerate”.

The Maintenance Problem:

This is tricky for developers who are inheriting an existing code base. A developer might accidentally add an Enumeration before the place where it actually has to. The next time or When the original Enumeration happens, it can not find any new data and the iterator just completes without any looping. This can happen very silently without any exceptions. So care to be taken to see where we are yielding and where we are Enumerating.

“Yield return” is a great feature in C#, but use it with caution.  Let me know your thoughts.

Perspective Designing
 

Recently, I was working with a colleague in refactoring one of our projects. As we added tests, we found few code issues and continued refactoring. Was feeling happy as our unit tests were rearing benefits. However, we know TDD or unit testing does not guarantee clean code. As we progressed, the naming conventions consumed a lot of our time. And eventually, it brought us to a discussion about why specific naming conventions can create a better design. Thought I will share our discussions and practices here.

While we design classes for application, we often think of it as a different subject than ourselves (programmer). When I say different subject, we think of it as a different object and not as a person. When a programmer considers classes/interfaces as personalities and thinks from the perspective of the class, design can change drastically. This is what we call “Perspective designing”. Let’s take an Example:

    public interface ITotalTaxCalculator
    {
        decimal Calculate(IEnumerable products);
    }

    public class TotalTaxCalculator : ITotalTaxCalculator
    {
        public decimal Calculate(IEnumerable products)
        {
            decimal total = 0.0;
            //add total of products etc....
            foreach (var product in products)
        	{
                using(var dbContext = new ProductContext())
                {
                    var productInDb = dbContext.FistOrDefault(prod => prod.Id == product.Id)
                    total += (total * productInDb.taxRate);
                }
        	}
            return total;
        }
    }

In the above example, the name of the class and interface are perfectly fine. But they are impersonal and it’s very hard to think of it as a person and bring in perspective thinking with these names. So we refactored them to ‘ICanCalculateTotalTax’ and  ‘TotalTaxMan’.

public interface ICanCalculateTotalTax
{
    decimal Calculate(IEnumerable products);
}

public class TotalTaxMan : ICanCalculatorTotalTax
{
    public decimal Calculate(IEnumerable products)
    {
        decimal total = 0.0;
        //add total of products etc....
        //blah blah blah..
        total += (total * taxRate);
        return total;
    }
}

These naming conversions have lots of inspiration from in NServiceBus for their class/Interface names. With the new class and interface names, it’s easy to think of them as personalities. However, this does not guarantee good design. So we needed refactoring. Perspective thinking comes in handy especially while we do refactoring When my colleague and I started putting ourselves in the place of each of the classes. We had very reasonable questions which triggered our object-oriented thinking.

Example1:  As ‘ICanCalculateTotalTax’ , why I am having database related behavior?

Example2: As ‘ICanCalculateTax’, why I am having logic to find which language it needs to be presented?

These questions helped us to refactor the code to follow good design principles. When we implement these interfaces/abstract classes, we have clarity on what the class is capable of doing. So we generalized these naming conventions & questioning attitude and derived below two rules to do Perspective designing (think like a class).

  • Give personality to the names of  classes/interfaces (example: ICanCalculateTax)
  • Use the Agile User Stories way of articulating what the class should and should not do. (example: As ‘ICanCalculateTax’, I should be able to provide behavior to calculate tax)

I think, “Perspective designing” can make classes more object-oriented and best practice like SOLID principles automatically fall in line. Let me know your thoughts.

Language of the Developers
 

There are lots of people who tell me that they need to understand specific design patterns (factory, observer, chain of responsibility etc). And after we spend quite some time discussing the topic they brought up, I ask them why they wanted to understand the original topic. The answers were quite surprising to me. Most of them said, “Design patterns are the trend now”. Some of them said, “I want to write good code”. Some of the candidly accepted “I was asked about this in an interview”.

Well, Design patterns are the new trend in the software industry and are being asked in most of the senior level technical interviews. For me, these reasons don’t qualify to take steps to understand design patterns. But the answer “I want to write good code” was quite interesting. Since a person wants to write good code, he/she is finding ways to improve it by applying patterns. Of course, Design patterns are good to understand and it saves time to know about how to solve a requirement/problem. If we take a step back and see if we really need to understand Design patterns to write good software, the answer is a big NO. Good software’s have emerged even before GoF patterns were documented. So why do we need to understand Design patterns?

When we write the code required to solve the problems, when we write optimal code, when we write code which is readable, testable and maintainable, we would have already applied the correct strategies/principles to solve the problem. But we should realize that when we write code we create a document not only for the compiler but also for other developers to read. How can we explain our code to another developer in a short time? We need a language !! Christopher Alexander (father of design patterns) calls this as the Pattern Language. A language that professional designers can use to communicate designs. He defines what are patterns with respect to this language.

The elements of this language are entities called patterns. Each pattern describes a problem that occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice. — Christopher Alexander

In Software terms, Design patterns are the constructs of a language, professional software developers can use to communicate their design. Until a developer needs to communicate their design/code, they need not know Design patterns! But developers communicate mostly with code. When the code communicates, patterns in the code will help the reader to quickly understand it.

A Developer is an Author
 

When I started this blog, I was skeptical if I can be an author. But what appeared more important to me is spreading knowledge, my thoughts So I continued blogging. After writing few articles what I realize is that writing a blog is not much different from my favorite profession (writing code).

Few similarities between coding and authoring.

  1. Both require deep knowledge of the subject (Domain)
  2. Both require good use of vocabulary
  3. Both require good organizing and formatting
  4. Both require analytic and logical skills
  5. Focus on the reader

If someone is a good writer, he/she can be a good programmer as well. I want to simply put it like this…

Programmer = Author + Technical Knowledge

Most of us(developers/testers)  are focused on attaining higher levels in Technology and unfortunately less in Authoring skills. This is because we think that there is a magical box (called compiler) which will convert our code to machine language and after that, there is no use of our code. This is not true!. When we write code, we are already an author, we are already creating an article/document/story.  And apart from the compiler, there are other readers for your code(Other developers and testers !).  And when they read, they expect to read it like an article. I know this is not a new concept, people like Robert C Martin,  Martin Fowler have spoken/wrote about this long time back. I am just re-emphasizing it from a different perspective.

Let us consider how a small snippet from the novel “A Stone for Danny Fisher” by Harold Robbins.

Harold Robbins

If you observe the paragraphs, each one has a unique purpose. Beautiful short paragraphs doing only one thing at a time (Single Responsibility). This makes it easy for the reader to understand the subject.

Learning: Single Responsibility

Also, observe that the order of paragraphs tells a story. The first paragraph sets the stage for the court, the second one describes the start of the court etc.

Learning: Order the methods in the order, they are being called. Tell the story of your code.

There are lots of quotations in the above snippet. They represent the words of the character. This helps the fast skimmer to skip the unnecessary things and just read the important words.

Learning: Characterize your code, give personality to your classes.

Observe that almost all the sentences are in active voice. They represent the voice of a person. It’s more assertive and stronger.

Learning: Method names should be assertive.

There are lots of similarities between good code and a good novel. We just need to read between the lines to understand them! Besides, each author is different and have their own style of writing and so will be the choices made by developers. These styles will have long-term implications on the success of the project.