Using Creational Patterns like Factory Method to refactor switch statements in Angular

Made by Itchimonji

Programmers try to avoid switch statements because switches are breaking the rule of the Open-Closed-Principle. Also, continuously extending the switch statement with more clauses leads to a high maintenance effort, as you need to modify the written code every time you extend it. Maybe your working unit-tests will fail after the change. You might need to fix your business logic and your tests every time — what a nightmare…

“The Problem with such duplicate switches is that, whenever you add a clause, you have to find all the switches and update them.” (Martin Fowler, [Refactoring])

Why do we use switch statements?

We use them because switch…


Code examples of object composition & inheritance in Angular

Based on my story Inheritance & Object Composition I want to show you, how you can use some Angular features for reusing code in really nice ways. I prepared some easy examples below.

Inheritance

Inheritance is a very simple principle in Angular. You can combine a base class with a superclass by using the extends term. The superclass inherits fields and methods from the base class.

Subscribing and unsubscribing to an observable in a Redux store is a common repeatable practise. You can DRY, when you separate this logic in a base class.

>>> base.component.tsexport class BaseComponent implements OnInit, OnDestroy…


Behavioral Pattern — Design Patterns Series

A Mediator controls the interaction of different object groups. A real life example is a chat room in which different users write to each other. The chat room or server is the Mediator object that manages users and distributes the messages to different clients.

The pattern helps to loose coupling by preventing explicit referencing of participants. The user in a chat room does not know the direct reference of another user. She/he only knows the server and another user’s id. The responsibility of the Mediator is to forward messages to the correct receiver. …


Behavioral Pattern — Design Patterns Series

Nowadays, a State can be found in a lot of application architectures: Web page state, database state (set of stored data), or stateful sets like MQTT — shortly explained, the entire content of its memory, e.g. all its variables, objects allocated, or open network sockets.

The pattern describes how changing the internal state affects the external behaviour, e.g. class changes.

Real-life examples

  • Screen states of the mobile phone: Lock Screen, Battery Low Screen, Unlocked Screen, …
  • Traffic lights in road traffic
  • Video games: Play, Pause, Load, Connect, …
  • Using the remote control to achieve various states on TV: on, off, mute, colour…


Behavioral Pattern — Design Patterns Series

The Iterator pattern is very helpful when encapsulating an aggregated object and providing sequential access to its elements. Shortly explained, you can not simply manipulate an array by copying, adding, or removing elements without an intermediate layer. In most cases a polymorphic iteration is supported. Additionally, a parallel execution of several traversal operations is possible (iterator monitors its traversal state itself and thus several operations can be executed simultaneously)

You can find this pattern in real life when switching tracks on your MP3 player or when zapping through TV channels. …


Behavioral Pattern — Design Patterns Series

Chain of Responsibility avoids the coupling between sender and receiver of a request. For this, multiple objects can take part in the process. The whole thing can be thought of as a one-time iteration of a given sequence, which can be variable. Objects are chained together and the request is forwarded until it is accepted and processed. Sometimes there is no processing guarantee.

The queue of a technical support system, where you reach different stages (automated attendant, support staff, administrator) is a good real-time example.

Real-life examples

  • Technical support: starting with a recorded message, you are then forwarded to a support employee…


Behavioral Pattern — Design Patterns Series

Strategy is often used when wanting to switch between different algorithms or behaviour at runtime. Decoupling the logic makes this change very simple and elegant, and also allows easy expansion with new algorithms.

At the end there is an emergence of a family of related algorithms. Strategy is one of the best showcase patterns to understand and learn Dependency Inversion. The usage of Object Composition increases the number of objects in this case, but it’s an alternative to creating subclasses for all the algorithms.

Real-life examples

  • Selection of a sorting algorithm (MergeSort, QuickSort, HeapSort, …) at runtime
  • Selection of a browser storage…


Behavioral Pattern — Design Patterns Series

Template Method is known as one of the cleanest inheritance techniques. The pattern is defined by setting the basic structure of an algorithm in an operation and delegating flow steps to subclasses. This allows the subclasses to override certain steps of an algorithm without changing its structure. This leads to high reusability, maintainability, and readability.

Real-life examples

  • Different order types (online shop, in a store) that need a template for the flow of an order process
  • Web pages that process similar things and thus differ minimally
  • Template for house construction (different options for an entrance, roof type, heating type, …)

Meaning

  • Definition of…


Structural Pattern — Design Patterns Series

Often a Proxy controls the access to another object. Intermediate layers that control access to a database are a well-known example. The pattern distinguishes between Remote Proxy, Virtual Proxy, and Protection Proxy. Also known is Smart Reference: This acts as replacement for a simple pointer — by accessing an object additional operations must be performed.

Real-life examples

  • Layers for accessing a database
  • Internet access
  • Guard or security service to protect a person or to pay attention on how the person is treated

Meaning

  • Provision of an upstream proxy object or a placeholder for the purpose of access control of an object

Applicability (suitable if …)

  • There is…


Structural Pattern — Design Patterns Series

Flyweight is also known as Cache and often found in the computer gaming section when sharing various GUI elements in order to save memory. It is defined by sharing fine-grained objects to efficiently deploy and reuse them in a large number.

Sometimes there may be runtime penalties associated with transferring, or locating. But these are offset by memory savings.

Real-life examples

  • Cache
  • Used in computer games when sharing GUI elements
  • For Special Case Objects

Meaning

  • Sharing fine-grained objects to efficiently deploy and reuse them in large numbers

Applicability (suitable if …)

All of the following points apply in one system:

  • Memory requirements are too high due to…

Itchimonji

Full Stack Software Engineer | Trained Mathematical-Technical Software Developer | Writer at CP Massive Creative

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store