Factory Pattern

What is the Factory Method Pattern?

Wikipedia describes it as:

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.


The Factory Pattern moves and abstracts implementation details of similar classes or even a single class or struct that has many ways to implement or instantiate it and doesn’t require the user of that object to know about all the dependencies or how to construct it.

If the requirements for creating an object changed, and you were manually creating that object all over your application, you would have to update all usages of it if there was ever a change. Instead, leave that work up to the class that is building the object for you. Define a separate operation/method for creating the object/s.

This also enables us to create subclasses that can redefine how an object is created or even which subtype to instantiate.

Creating an object often requires complex processes not appropriate to include within a composing object. The object’s creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object’s concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.


Let’s look at a simple example where we have a struct similar to .NETs TimeSpan object. It is just going to hold a number of ticks, but we may want to build up this Duration wrapper from several different lengths or units.

Examples are in C#.

public struct MyDuration {
  private readonly long ticks;
  public long Ticks { get { return ticks; } }

  // public MyDuration(long ticks) {
  //   this.ticks = ticks;
  // }

  private MyDuration(long ticks) {
    this.ticks = ticks;
  }

  public static MyDuration FromTicks(long ticks) {
    return new MyDuration(ticks);
  }

  public static MyDuration FromMilliseconds(long milliseconds) {
    return new MyDuration(milliseconds * 10000);
  }

  public static MyDuration FromSeconds(long seconds) {
    return new MyDuration(seconds * 10000 * 1000);
  }
}

public void main() {
  MyDuration duration = MyDuration.FromSeconds(5);
  // duration.Ticks == 50000000
}

You will also notice that I used a private constructor. Mixing the Factory Pattern with a traditional constructor can be confusing.

new MyDuration(5) //What does that mean?

Instead, use a private constructor, and use the same pattern for all use cases.

C#6 allows us to use named parameters, but I still like to lean towards consistency.

new MyDuration(ticks: 5)

Reminder, Pluralsight has many courses on different design patterns in many different languages and implementations, and they have a FREE trial!

Start a 10-day free trial at Pluralsight

Singleton Pattern

What is the Singleton Pattern?

Wikipedia describes it as:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.


Sometimes this is because we need shared state across the application, or for efficiency reasons – maybe for I/O operations. There are heavy debates on when or if you should even try to do this, but there are definitely use cases. Be careful when you have data/properties that need to be shared across a system through single instantiation, it may be a code smell. If it is what you need, here are some implementation details.

The biggest problems you are going to run into while implementing this pattern is thread safety. Let’s look a very straightforward, basic implementation of the Singleton.

Reminder, Pluralsight has many courses on different design patterns in many different languages and implementations, and they have a FREE trial!

Start a 10-day free trial at Pluralsight

Examples are in C#.

 public class Singleton {
  private static Singleton instance;
  private Singleton() {
    // Things that must only happen once
  }
  public static Singleton Instance() {
    if (instance == null)
    {
      instance = new Singleton()
    }
    return instance;
  }
  public void DoSomething() {
    // Must be thread safe
  }
}

We may run into threading issues where two threads try to access the constructor at the same time.


We could do some craziness like doing explicit thread locking and double checking.

 public class Singleton {
  private static Singleton instance;
  private static readonly object mutex = new object();
  private Singleton() {
    // Things that must only happen once
  }
  public static Singleton Instance() {
    if (instance == null) {
      lock (mutex) {
        if (instance == null)
        {
          instance = new Singleton()
        }
      }
    }
    return instance;
  }
  public void DoSomething() {
    // Must be thread safe
  }
}

Unless your class is very IO heavy or doing other heavy lifting, you probably won’t run into huge performance costs by thread locking, but it still isn’t very pretty, and can cause it’s own problems.


By understanding the mechanics of static classes and their static constructor, we can understand that .NET does a pretty good job of only letting one thread inside of a static constructor at a time, so an empty static constructor solves a lot of our problems and even forces a certain level of laziness in instantiation, but isn’t perfect.

static Singleton() {}

If being lazy is super important to you, you can go the extra mile and create an internal holder for your singleton.

 public class Singleton {
  private static class SingletonHolder {
    internal static readonly Singleton instance = new Singleton();
    // Empty static constructor forces laziness
    static SingletonHolder() {}
  }
  private Singleton() { Console.WriteLine("Instantiate") }
  public static Singleton Instance { get { return SingletonHolder.instance; } };
  // Stateless method
  public void SayHi() {
    Console.WriteLine("Hello");
  }
}

// Example usage
public void main() {
  Singleton.SayHi();
  Console.WriteLine("Before Usage");
  Singleton s = Singleton.Instance;

  /*
    Output:
    Hello
    Before Usage
    Instantiate
  */
}

In this example, simple methods that don’t need access to the internal state that you are trying to share across the application, don’t even need an instance of the class to execute and will not instantiate the class until you actually ask for the instance.


In .NET4 and later, you can use built-in language features to get real lazy implementation.

 public class Singleton {
  private static readonly Lazy lazyInstance =
    new Lazy(() => new Singleton(), isThreadSafe: true)
  private Singleton() {}
  public static Singleton Instance { get { return instance.Value; } };
  public void SayHi() {}
}

CSS – Box Model

All HTML elements can be considered as boxes. In CSS, the term “box model” is used when talking about design and layout.

The CSS box model is essentially a box that wraps each HTML element. It consists of the content itself, its margins, borders, and padding.

This image demonstrates the idea of the box model.
CSS Box Model


Content: The actual content of the box. Includes any text, images or other presentational item.

If the box-sizing property is set to content-box (default), the content area’s size can be explicitly defined with the width, min-width, max-width, height, min-height, and max-height properties.


Padding: Clears an area around the content. Padding is transparent.

The thickness of the padding is determined by the padding-top, padding-right, padding-bottom, padding-left, and shorthand padding properties.

Note: When the content area has a background, it extends into the padding.


Border: A border surrounds the padding and content.

By default the border has a size of 0 — making it invisible — but you can set the thickness, style and color of the border to make it appear.

The thickness of the borders are determined by the border-width and shorthand border properties.

border-top, border-right, border-bottom, border-left: Set the thickness, style and color of one side.

border-width, border-style, border-color: Set the thickness, style, or color individually, but for all four sides.

You can also set one of the three properties of a single side of the border individually, using border-top-width, border-top-style, border-top-color, etc.


Margin: Clears another area outside of the border. Margin is also transparent

Used to separate the element from its neighbors. Determined by the margin-top, margin-right, margin-bottom, margin-left, and shorthand margin properties.

Note: Margins have a specific behavior called margin collapsing: When two boxes touch against one another, the distance between them is the value of the largest of the two touching margins, and not their sum.

Note: Vertical margins, top and bottom, are not accepted by inline-level elements.


You can use this model to define space and border around and between different html elements.

div {
  width: 200px;
  margin: 10px;
  padding: 15px;
  border: 2px solid black;
}

Understanding the size of an HTML element

It is important to remember that when you set the height and width properties with css, you are only setting the size of the content.

To calculate the total size of an element, you need at add padding, borders and margins.

If we needed an element to have a total width of 350px, we would use all of these properties.

div {
  width: 320px;
  margin: 0px;
  padding: 10px;
  border: 5px solid black;
}

320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

CSS Units of Measure

CSS has several units of measurements to express length.

Many CSS properties take a length. Some of these are: padding, margin, width, font-size, border-width etc.
You declare these properties with a number and then a unit to measure by, ie: 20px.

There are two classes of measurements, Relative and Absolute.

Relative measurement units specify a length relative to another property. Relative measurements scare better in different rendering environments.

Examples of Relative measurements:
em – Relative to the font-size of the existing element. Ie: 2em will make it two times the size of the current font. If the font size is 12px, 2em would be 24px.

p { font-size: 2em; }

rem – Relative to the font-size of the root element. rem is new with CSS3. This allows us to do relative sizing with a set base within a HTML element. 1rem by default is 16px.

The main problem with em units is that they are relative to the font size of their own element. As such they can cascade and cause unexpected results. You have to worry a lot more about nesting when using em. rem gives you a starting point for the entire document without worrying about what else modified your elements along the document tree.

body {  font-size: 14px; }
div { font-size: 1.2em; // calculated at 14px * 1.2, or 16.8px }

<body>
  <div>
    Test <!-- 14 * 1.2 = 16.8px -->
    <div>
      Test <!-- 16.8 * 1.2 = 20.16px -->
      <div>
        Test <!-- 20.16 * 1.2 = 24.192px -->
      </div>
    </div>
  </div>
</body>

Another way to size things relatively is to increase or decrease their size by percentage. A length set in percentage is based on the length of same property of the parent element. For example, if an element renders at 450px width, a child element with a width set to 50% will render at 225px

p { line-height: 120%; }

The most common way to set lengths absolutely is with screen pixels. You can set length properties with the px notation. Pixel size is slightly dependent on the resolution of the device. For screen displays, it traditionally represents one device pixel (dot). However, for printers and high-resolution screens, one CSS pixel implies multiple device pixels, so that the number of pixels per inch stays around 96.

p { width: 400px; }

Command Query Responsibility Segregation

Remember to Start your Free Trial today! for Pluralsight to learn more about all of these topics!

Start a 10-day free trial at Pluralsight

What is CQRS?

The first thing to mention is that CQRS is just a pattern. It is not an architecture or style or framework. It is simply a pattern to follow for scaling large systems. It is built upon the more simple principle of Command Query Separation, “A method should either change the state of an object, or return a result, but not both”

Command Query Separation makes reasoning about objects easier and is broadly applicable.

CQRS is much more specific and not broadly applicable.

The problem that CQRS solves is Blocking the User when Locking the Data

This is commonly seen when you have a large set of people acting on a small set of data.

A good example would be when users would be trying to pick seats for an air plane. Many people may want the same seats. Only one person will end up with the seat and the others will have to try again. This is even worse when someone is trying to reserve seats for a family and wants several seats together. They will become blocked several times before they are able to get seats they may like.

Locking the data is necessary, you must ensure that only one person gets a seat. But, blocking the user in that process is not necessary.

One option would be to introduce a ticketing agent that takes everyone’s requests and assigns the seats and then lets the passengers know of their assignment. The users could then query the status of the seat assignments. But, what they can’t do is change the seating assignments. They can’t affect the seating assignment object directly. For that, they’ll need to go back to the ticket agent. This is not preferred either. There is no immediate feedback.


The first step is to separate out your commands/updates from your queries. You should never return information from a command. If you need to track any kind of status of a transaction, the caller should generate the identifier so that he can call back or query for that status at a later time. Don’t wait for the command to have to fully complete while the user is waiting and blocked.

This improves the situation programmatically by not creating any read locks on data when a user intends to update the same data that is being read by another. It avoids either user from becoming the victim of a deadlock.

It now becomes important to have a queue of messages to process. These can be processed in the order they were received or in a priority and never create any locks. At this point you can have a separate service that queries for the status of that transaction for completion. You can see my post about service bus implementation HERE.

The trade off you are making is Eventual Consistency for Availability. You are making the user experience better and never blocking with the small drawback of potentially stale data.

The CAP Theorem says you can only ever choose 2 of 3 for:

  • Consistency – never receive old data
  • Availability – reasonable response without an error
  • Partition Tolerance – unavoidable because you can’t control the network

Some things you will want to make sure you keep in mind are:

  • Persisting these messages in case of network problems/latency
  • Guarantees of messages being processed
  • Guarantees that messages won’t be duplicated

The next big benefit of CQRS is now that you have your commands separated from your queries, you can have different data models for each side. You don’t need large Data Transfer Objects that know about all the related data, know how to modify it, getters and setters, business logic etc.

Instead, you can have different models for different parts of the system. Depending who is asking for the data and what they need to do with it, they can query in different ways and only for the data that they need (say to display some of the data on a web page), and have their own model to do so. Since they don’t need to keep track of modifying this data, they don’t need all the extra cruft, extra data, all the rules etc. They can just ask for exactly what they want.

The commands can also be cut down in size to know how to modify the part of the data that it cares about.

This allows you to structure your applications in a way that they only care about the parts they are dealing with. You can have more specific commands and queries for specific data, that doesn’t necessarily represent the structure while in the database.

This also allows you to scale your architecture and hardware separately and independently of each other. If you need to support millions of queries, but only a handful of commands, you don’t need to scale them together. You get distinct optimization and huge scalability potential.

Some side effects of implementing this pattern is usually a simplified design, hassle free enhancements, and opens yourself up for some other event based architectures and design patterns.

ES6 Rest/Spread Operator Usage

We all know that the javascript (...) rest/spread operator has made our lives easier with ES6. I wanted to show you how it is used and a couple of ways that you can use it.

Cory House and others have some fantastic courses on @Pluralsight about the great new features of ES6
Start your Free Trial today!

Start a 10-day free trial at Pluralsight

Rest parameters to functions

Functions have the magic arguments variable, but it is not very clean, and it’s not actually an array member. So you can’t use the array functions on it like map, slice etc.


  function concat () {
    return Array.prototype.slice.call(arguments).join(' ')
  }
  var result = concat('this', 'is', 'hard')
  console.log(result)
  // 'this is hard'

Instead, we can provide a named parameter prefixed by ... that will spread the parameters that come in into an array.


  function concat (...words) {
    return words.join(' ')
  }
  var result = concat('this', 'is', 'better')
  console.log(result)
  // 'this is better'

You can also have specific named parameters, followed by an arbitrary number of additional parameters that are spread.


  function multiply(multiplier, ...numbers) {
    return numbers.map(element => {
      return multiplier * element;
    });
  }

  var arr = multiply(2, 1, 2, 3);
  console.log(arr); // [2, 4, 6]

You can break down your arrays or objects into individual properties if the function you’re calling wants individual parameters, without using apply. Or even, mix and match.


  console.log(1, 2, 3); // '1 2 3'

  console.log.apply(console, [1, 2, 3]); // '1 2 3'

  console.log(...[1, 2, 3]); // '1 2 3'

  console.log(1, ...[2, 3, 4], 5) // '1 2 3 4 5'

Another very good bonus is that it can be used on anything that is an iterable. So if you’re working with nodes/dom elements that aren’t arrays, but are still a list of things you want to work with, you can spread them into a real array that you can work with.


  [...document.querySelectorAll('div')]
  // [<div>, <div>, <div>]

Composition and Destructuring of objects

We can easily grab properties from one object and add them to another.


  const one = { a: 1, b: 2 };
  const two = { c: 3, d: 4 };
  const three = { ...one, ...two };

  // three = { a: 1, b: 2, c: 3, d: 4 };

  // Then pull off a specific property
  const { d, ...thing } = three;

  // thing = { a: 1, b: 2, c: 3 };

  // assign that specific value to another variable
  let otherVar;
  const { d: otherVar, ...thing } = three;
  // otherVar = 4

Adding properties with dynamic/unknown property names. Maybe a React reducer handling a dictionary with keys? We can use [] with a string to give a named property key for an object. The spread operator also is convenient in React reducers where you don’t want to mutate the previous state coming in, rather composing a new state based off the old state. ... will create a copy of an old object/array. Be careful, as spreading arrays of objects will still keep a reference, so it isn’t a copy per se.


  // state = { 1: 'hello', 2: 'welcome' }
  // action = { type: 'add', id: 3, payload: 'goodbye' }
  reducer(state, action) {
    switch(action.type) {
      case: 'add':
        return { ...state, [action.id]: action.payload };
        // returns a new object { 1: 'hello', 2: 'welcome', 3: 'goodbye' }
        // All accomplished on one line!
    }
  }

How about pulling a dynamically named property off of an object?


  // state = { 1: 'hello', 2: 'welcome', 3: 'goodbye' }
  // action = { type: 'remove', id: '2' }
  reducer(state, action) {
    switch(action.type) {
      case: 'remove':
        const {[action.id]: _, ...rest } = state;
        return rest;
        // returns a new object { 1: 'hello', 3: 'goodbye' }
        // We assigned the destructured property to a 'throw-away'
        // variable _
        // Unfortunately, we can't just pull off dynamically
        // named properties, yet.
        // We have to assign them to a throw-away
    }
  }

Service Bus Applications using Fubu Transportation

In today’s world it is more and more useful to have a system architecture where your system is distributed, for many different reasons. Splitting up your software into separate services can have a lot of benefits. Today we’re going to talk about one of the ways to overcome some of the problem that comes from splitting up your system, particularly over a network.

Your systems are going to need to be able to talk to each other over the network. You’re going to need ways to connect these services so they know how to talk to each other. They need to know how to ask for information or tell another what they know or what they need done. We’ll do this through a ‘messaging’ system. You’re going to need to handle dropped messages and other problems imminent with work over the wire.

Our company uses an OSS product called Fubu Transportation. It has changed names a few times, been pushed inside the main framework, pulled back out etc. But its job is to coordinating messages sent between different parts of the system.

First, you need some sort of Transport system. Fubu Transportation uses Lightning Queues. The transport is in charge of queuing up the messages and making sure they arrive where they are supposed to. It uses LightningDB for this. You can just use local storage, or you can hook it up to a database, generally a document Database. This allows it to be persistent and store the messages in case the receiver is unavailable or the service goes down before it is ready, or even schedule messages to be delivered at a later time.

The first thing you’ll do is set up a settings class that will house your channels. It needs the transport, port and a queue name.


public class TransportSettings
{
  public Uri Pinger { get; set; } =
    "lq.tcp://localhost:2342".ToUri();
  public Uri Ponger { get; set; } =
    "lq.tcp://localhost:2343".ToUri();
}

You certainly could use your choice of extracting this out into some type of settings convention and using configuration for these values.

Next you will configure the channels using FubuTransportRegistry<T> where T is your Settings class you defined above. There is a fluent interface off of a Channel() method to describe what each channel does and how.


public class PingApp : FubuTransportRegistry<TransportSettings>
{
  public PingApp()
  {
    // Configuring PingApp to send PingMessage's
    // to the PongApp
    Channel(x => x.Ponger)
      .AcceptsMessage<PingMessage>();

    // Listen for incoming messages from "Pinger"
    Channel(x => x.Pinger)
      .ReadIncoming();
  }
}

public class PongApp : FubuTransportRegistry<TransportSettings>
{
  // Listen for incoming messages from "Ponger"
  public PongApp()
  {
    Channel(x => x.Ponger)
      .ReadIncoming();
  }
}

Accepting incoming messages

Options off of Channel():
Listens on a specific channel for incoming messages.
.ReadIncoming()

Accept a specific message type
.AcceptsMessage<PingMessage>()

Specific message like this.
.AcceptsMessage(typeof(PongMessage))

Accept messages by some sort of naming convention
.AcceptsMessages(type => type.Name.EndsWith("Message"))

Specify a type within an assembly and accept those types
.AcceptsMessagesInAssemblyContainingType<PingMessage>()

Assembly by name
.AcceptsMessagesInAssembly("MyMessageLibrary")

Accept by namespace
.AcceptsMessagesInNamespace("MyMessageLibrary")

Namespace containing type
.AcceptsMessagesInNamespaceContainingType<PingMessage>()


Message Persistence:

This ignores any persistence and just delivers the message
quickly without persisting it
.DeliveryFastWithoutGuarantee()

Default, but explicitly says you want to persist messages for safe delivery
.DeliveryGuaranteed()

Fubu Transportation has some continual messaging that it does to coordinate activities like setting up subscriptions, and health checks. You should set up a control channel for this.


public ControlChannelApp()
{
  Channel(x => x.Control)
    .UseAsControlChannel()
    .DeliveryFastWithoutGuarantee();
}

Message Consumers

Next we’ll look at how to handle or consume these messages.

We will create consumer methods. FT discovers these by just being a public method on a public class that has a single parameter of the message type that is handles.


public class SimpleConsumer
{
  public void Consume(PingMessage message)
  {
    Console.WriteLine("I handle PingMessage");
  }
}

Fubu Transportation supports the idea of what we call Cascading Messages.
This is a behavior of being able to create reply messages and/or sending another message after one message is processed, all by convention without explicitly setting up more service bus code to send another message. This is done by changing the return type.


public class CascadingConsumer
{
  public MyResponse Consume(MyMessage message)
  {
    return new MyResponse();
  }
}

When FT executes this consume method, it “knows” that it needs to then send out another message of type MyResponse, with what ever delivery rules apply to its type. FT keeps track of this delivery as one transaction. It will not send the next message until the first message has been fully executed. This also helps with unit testing a lot, because you can check the state of objects within the consume method without having to re-mock the entire bus call here.

You can also use the .Request<T> method instead of a standard .Send() to tell the handler that you’re the one that wants the message back, instead of using the existing routing rules.


public Task<MyResponse> GatherResponse()
{
  return _bus.Request<MyResponse>(new MyMessage());
}

Can be handled by


public MyResponse Consume(MyMessage message)
{
  return new MyResponse();
}

You can also set up conditional responses to send different messages depending on conditions in the consumer. Just set the return type to object, and when the message is returned, it will pick up the configuration for its type and be delivered to where it belongs.


public class ConditionalResponseConsumer
{
  public object Consume(DirectionRequest request)
  {
    switch (request.Direction)
    {
      case "North":
        return new GoNorth();
      case "South":
        return new GoSouth();
    }

    return null;
  }
}

You can also schedule messages for a later time or date.
Note, persistent storage is a good idea here.


public DelayedResponse Consume(DirectionRequest request)
{
  // Process GoWest in 5 minutes
  return new DelayedResponse(new GoWest(), TimeSpan.FromMinutes(5));
}

You can also return multiple cascading messages by setting the return type to IEnumerable<object>


public IEnumerable<object> Consume(MyMessage message)
{
  // Go North now
  yield return new GoNorth();

  // Go West in an hour
  yield return new DelayedResponse(new GoWest(), TimeSpan.FromHours(1));
}

Dynamic Subscriptions

In your application’s Transport Settings file you should be setting up different channels for incoming and outgoing messages to separate concerns.


public class NodeSettings
{
    // This uri points to a different
    // application
    public Uri OtherApp { get; set; }

    // This uri should be the shared
    // channel that all nodes in the
    // application cluster are reading
    public Uri Receiving { get; set; }
}

Now you’ll configure a local subscription for each individual node of the application and a global subscription if you have the same service being load balanced on several servers.


public class LocalApp : FubuTransportRegistry<NodeSettings>
{
  public LocalApp()
  {
    // Explicitly set the logical descriptive
    // name of this application. The default is
    // derived from the name of the class
    NodeName = "MyApplication";

    // Incoming messages
    Channel(x => x.Receiving)
      .ReadIncoming();

    // Local subscription to only this node
    SubscribeLocally()
      .ToSource(x => x.OtherApp)
      .ToMessage<OtherAppMessage1>();

    // Global subscription to the all the
    // running nodes in this clustered application
    SubscribeAt(x => x.Receiving)
      .ToSource(x => x.OtherApp)
      .ToMessage<OtherAppMessage2>()
      .ToMessage<OtherAppMessage3>();
  }
}

FT uses subscription persistence to store information about the list of active applications, nodes, and subscriptions. It has built in message types for SubscriptionsChanged, SubscriptionRequested, and SubscriptionsRemoved that it uses to coordinate subscriptions across running nodes and applications.

When a FT service bus application is initialized, it:

  • Loads the same information about any other nodes in the logical application cluster from the subscription storage
  • Loads the list of previously persisted message subscriptions
  • Sends out SubscriptionRequested messages to request dynamic subscriptions

  • Sagas

    FT supports the idea of Sagas, which are basically long lived message processes.

    Think of a state machine. There is a main Saga Object that has all the logic for transitioning between different states and what should happen when that happens. Then there are individual saga states that get run through the system.These objects are durably stored. Events are published through messages that include the current state and what event happened. It gets passed through the state machine and it updates the object accordingly and then emits a completed message so the rest of the application can react accordingly as well.