When we need a single instance of an object, of a specific class, to exist in our application, we use the Singleton pattern. Now, the pattern itself is frowned upon in some circles and is seen as an anti-pattern.
Some of the reasons the Singleton is seen as an anti-pattern are:
I want the objects I use in my TypeScript code to let me set multiple properties on them in one go. My objects must have a method setProps
such that when given a properly typed map of properties, the method sets the corresponding properties on the objects.
I have a base class, say BaseObject
, that has the publicsetProps
method. setProps
must take parameters that are compatible with the instance of a class derived from BaseClass. This is achieved with generics. The method will look like the following piece of code:
I constrain the type parameter T
to represent a…
I want to specify validation rules for the objects I am using in my typescript apps in the most ergonomic, hence elegant, manner possible.
github: https://github.com/kanian/ts-decorator-validation,
npm: https://www.npmjs.com/package/ts-decorator-validation
I will use Joi and JavaScript decorators. Here’s a small UML diagram to summarize the approach:
When writing back-end NodeJS APIs in Typescript, I don’t want to worry about the validity of the data my services are consuming or producing. Given I have correctly captured the business rules and the data validity criteria, I want to be able to trust that the data I am working with is always valid.
The basic tool I will use here are Joi and a set of abstractions I will present in coming paragraphs :
Essentially, initializing arrays in javascript can happen in one of four ways:
let myArray = [1,2]
undefined
, as in new Array(arrayLength)
new Array(el1,el2)
// -> [7]
This being known, there eventually comes a time when a learning javascript developer will need to have more control over the initialization of arrays. In the coming sections we will explore common array initialization questions, as well as some solutions for the power javascript developer to-be.
It’s a recurring…
A few weeks ago, I decided to revisit Dependency Injection (DI) in the PHP world and quickly build a simple one. I looked at various article including the one by Mustafa Magdi and that by Andrew Carter, among others. With all the powerful and well know PHP DI containers out there, why go through the trouble? I figured that there must be some lessons to learn.
Before going any further, DI can be defined as:
[A] technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service)…
In a previous article, I describe an approach to a generic PHP Singleton pattern that can be summarized by the following diagram:
Solutions Architect and Coder