An Introduction to the Nx Workspace

Learn how to create and maintain flexible angular applications with Nrwl Extensions

Angular development is great. It offers a great way to break problems into small, easily managed parts. With the Angular CLI, more power is at our fingertips. Narwhal Technologies Inc has created even more power by providing extensions to the Angular CLI. In this article, I will describe how to leverage the Nrwl Extensions to create and maintain flexible angular apps.

To learn how to install Nrwl, visit their getting started guide: https://nrwl.io/nx/guide-getting-started

Make sure to install Angular and Nrwl globally using npm. Here is a list of versions I used for this article:

node: 8.15.0
npm: 5.0.0
"@angular/cli": "~7.1.0"
"@nrwl/schematics": "7.4.0"

Creating an Nx Workspace

The Nx Workspace is a collection of Angular applications and libraries. When creating the workspace there will be a number of options available during generation. To start, run the following command:

create-nx-workspace <workspace-name>

This will begin the process of generating the workspace with the provided name.

After a few initial packages are installed, a prompt will display to choose the stylesheet format:

Stylesheet format prompt
stylesheet format prompt

Use the arrow keys to choose between CSS, SCSS, SASS, LESS, and Stylus. After the desired format is highlighted, press Enter.

The next prompt to display is the NPM scope. This will allow applications to reference libraries using an npm scope. For example, given a library called ‘my-lib’ and the npm scope is ‘my’, an application can import the library with the following statement:

import { MyLibModule } from '@my/my-lib';

To learn more about npm scopes check out their documentation: https://docs.npmjs.com/about-scopes

After specifying an NPM scope, press Enter. A third prompt will appear to specify which package manager to use:

NPM scope and package manager prompts
npm scope and package manager prompts

Use the arrow keys to choose between npm and Yarn. After the desired format is highlighted, press Enter.

Now that the generation process has everything it needs, it will continue to create the folder structure, files, and configuration:

Completed Nx Workspace generation
completed Nx Workspace generation

Project Structure

There are two important folders available after the workspace generation.

FolderDescription
/appsContains a collection of applications in the workspace.
/libsContains a collection of libraries in the workspace.

Adding Applications

Before adding an application with the CLI be sure to navigate into the workspace folder. In our example, the folder is ‘my-platform-workspace’. Then use the Angular CLI to generate the app:

PS C:\NoRepo\NxWorkspace> cd my-platform-workspace
PS C:\NoRepo\NxWorkspace\my-platform-workspace> ng g app <app name>

Tip

When using Visual Studio Code, open the Nx Workspace folder. This will default the command window to the necessary directory by default when using the built-in support called Terminals.

After adding the application, a number of prompts will display and the app generation will proceed:

Adding an application
adding an application

Running the application can be done using the Angular CLI as usual:

PS C:\NoRepo\NxWorkspace\my-platform-workspace> ng serve my-first-app

When the app is done building, go to http://localhost:4200 from a browser and see the default view:

Default app built with Nrwl Nx
default app built with Nrwl Nx

Adding a Library

Adding a library is as easy as adding an application with the following command:

ng g lib <library name>

Generally, a module should be created for libraries so they an be easily imported by applications. Once the library is created, components can be added to the library. Make sure to export any library components or other Angular objects (providers, pipes, etc) that need to be used by applications.

The Dependency Graph

Looking at package.json, there are a number of scripts that have been added. One that is nice to have is to generate and view a dependency graph of all of the applications and libraries in the workspace. A dependency graph can be generated using the following command:

npm run dep-graph

For example, I’ve added my-lib and my-lib2 to the my-first-app. This is the resulting dependency graph:

Sample dependency graph
sample dependency graph

Here we can see that the my-first-app-e2e (end-to-end) test application is dependent on the my-first-app application. The application is dependent on the libraries my-lib and my-lib2. This is a very simple example. This gains more value as more applications share more libraries.

It is also possible to get the JSON version of the dependency graph which can be used in various creative ways to help automate your workflow. This is all thanks to Nrwl Extensions and the power of Nx Workspaces.

Handle Arguments in a PowerShell Script

Learn ways to handle arguments sent to a PowerShell script

So far, I haven’t used Powershell often in my work. I do know its a powerful tool and one that has saved me a lot of headaches when I have used it. One thing I recently found to be quite helpful is the ability to leverage the arguments sent to a PowerShell script file.

Here is the sample script that will be referenced throughout this article:

# ./HandlingArguments.ps1
# Args: 0 - string1; 1 - string2;
$args | ForEach-Object {
$arg = $_;
Write-Host $arg.GetType()
Write-Host $arg
Write-Host $arg[0]
Write-Host $arg[1]
}

I will begin by briefly describing this script. Certainly, the first two lines are just comments providing the name of the script file and some generic information about the args.

Next, is the use of the $args automatic variable. This variable contains an array of the arguments send to the script file. ForEach-Object provides us the ability to iterative over a collection of objects. Each item is an object within the collection and is represented inside the ForEach-Object body (if using a script block) as $_. Of course, I cannot forget about the symbol between $args and ForEach-Object, the | or “pipe” character. This character is used to pipe the input objects ($args array items) to ForEach-Object.

Variations of Argument Passing

There are various ways of passing data to this script. In the following example, we’ll simply pass the string “hello”:

PS> .\HandlingArguments.ps1 "hello"
System.String
hello
h
e

Here, the “hello” string is passed to the script and $args is an array with the string value “hello” as an item.

$_ is the string value “hello”. $_.GetType() gives us the System.String type. $_[0] and $_[1] access characters of the string “hello” (“h” and “e” respectively).

The important part to remember is that $args is an array of items passed to the script. When we iterate over that array we get the item value. In this case, that item value was “hello”.

Next, let’s send “hello” and “world” as two separate arguments to the script file:

PS> .\HandlingArguments.ps1 "hello" "world"
System.String
hello
h
e
System.String
world
w
o

Here, we see that there are now two sets of four outputs. The first mirrors the output when we just sent “hello”. The second is similar to the first but with the string “world” instead. Remember, $args is an array of items passed to the script. In this case, it is an array with two items: “hello” and “world”.

Next, let’s see what happens when we pass an array of strings to the script:

PS> .\HandlingArguments.ps1 ("hello", "world")
System.Object[]
hello world
hello
world

Here, we can see that we are back to just a single set of four outputs. $args is an array of items passed to the script. Since we passed a single array, it is an array consisting of a single item which is an array. $_ is the array containing “hello” and “world” as its items. $_.GetType() gives us the System.Object[] type. $_[0] and $_[1] access items within the array (“hello” and “world” respectively).

This article briefly described some of the ways to leverage the flexibility of Powershell to provide different output without changing the script file by simply changing the arguments passed to it.

The Monolith Component

Learn some useful ways to identify and squash a monolith component

It is more common than ever to have user interfaces made up of components. With so many user interface libraries and frameworks like Angular, React, VueJS, Aurelia and KnockoutJS components are everywhere. Components are the building blocks of a user interface. It is imperative that these blocks are built and organized in a way that supports proper testing, reduces defects and enables the extension requirement innate to ever-changing user experiences. This article will describe a component that counters these goals by challenging both the quality and flexibility of a user interface: The Monolith Component.

The Monolith Component is a byproduct of feature-driven functional decomposition. It is the user interface representation of the god object. The component is feature-packed, contains an excessive amount of code, and often becomes the grandparent of smaller child components. To make the problem worse, the child components could be referencing the grandparent and act as nothing more than a visual proxy to grandparent capabilities.

It isn’t hard to understand why this sort of thing happens. First, an agile team will use sprints to deliver features. Without enough careful consideration and planning of system design, the design and functionality tend to focus on feature-level concerns at a sprint cadence. Second, it’s not always intuitive to design something that is counter to our nature. For example, generally speaking, we first learn how to cook from our parents, and our parents first learned how to cook from their parents, and so on. In a fast-paced environment, a quicker path maybe just to learn from your grandparents. This is a small example of the innate grandparent (monolith) design we exist within. Instead of children components owning their responsibilities, they are implemented in their parents and likewise up the hierarchy to the level of the monolith component.

Applying the grandparent theme to user interface development leads to buggy components that are difficult to maintain, test, and extend. Overall, a monolith component will have too many responsibilities.

Identifying A Monolith Component

There are a few indicators of a monolith component.

#1 Line Count: if you see a component with 1000+ lines of code, you may be looking at a monolith component.

#2 Dependencies: if you see dozens of dependencies or more, you may be looking at a monolith component.

#3 Bugs: if most bug fixes involve looking at the same, single component, you may be looking at a monolith component.

#4 New Features: if new features involve looking at the same, single component, you may be looking at a monolith component.

#5 Responsibility: if it is easier to describe what a component does not do within the context of the page, you may be looking at a monolith component.

Refactoring A Monolith Component

Updating a monolith component can be a daunting task. It should get easier the more it is done. It does get easier if those updates mean breaking up the monolith into a more sane design. The more that is done, the better off the code, and developer, will be. To describe exactly how to refactor one of these components would depend on its implementation details. I will instead attempt to describe some general ideas that have helped me in the past with some simple examples along the way.

Test Test Test

The first step is having confidence that refactoring does not introduce breaking changes. To this end, maintaining tests that prove business value is essential. The presentation and logic shouldn’t change during a refactor. That is to say, the intent should not change. There are multiple ways to accomplish the same thing. Refactoring code is meant to update code so that it does the same thing in a cleaner way. Having tests that make sure the code satisfies business requirements without depending on how it satisfies them, will help avoid introducing bugs while refactoring.

Identify Responsibilities

The second step is knowing what the component does. A monolith component will likely have multiple responsibilities. Being able to list these will help us understand the component and how to split it into multiple components. It can reveal the patterns and domains that shape the component.

Responsibilities that are determined to be unnecessary should be removed:

Example 1: The section of code is disabled due to being wrapped in a comment. This code can’t execute. Remove it. Be careful when looking at comments in HTML. Often libraries and frameworks will give meaning or functionality to HTML comments.

Example 2: A block of HTML never displays because of a visibility condition that is never and can never be true. Assuming this isn’t a bug, the HTML block can be removed. The condition in code may not be necessary either.

We know the component’s responsibilities and we may have removed some that were not needed. Now we look at dependencies.

Understand Dependencies

The third step is knowing the internal and external dependencies of the component. The goal of this step is to answer: what does the component require so that it can perform its responsibilities?

Depending on what kind of dependency injection is used (the application does leverage DI right?) dependencies may be specified in different locations.

Looking at the constructor is a good place to start. The parameters of the constructor define what a component needs in order for an instance to be created.

Next, look at private and public properties. These will likely include the values or objects set in the constructor. They also represent the possible states of a component. Maybe an enum is used to define how to present a particular object in the view. Maybe a boolean is set to determine whether a checkbox should be checked on load. Maybe an object is used to store a server response object. These things can still be considered dependencies in this context – the component needs them to provide its business value.

Look for static members. Static members need a definition, not an instance. What do they offer and how does the component use them? Generally, these are easier to identify and extract to make more reusable.

Finally, look at how the dependencies are used within instance methods. If a non-primitive data type is specified in the constructor, what is the purpose of that dependency? Does it allow a consumer to get data from a server? Does it contain methods to filter a list of a particular data type? Is it the mechanism for triggering an event on a timer? Knowing how the dependencies are used can help when determining what business problem they are solving. This can help us group dependencies by business problems or domains.

Extract Common Ground

The fourth step is knowing the groups of common responsibilities and common dependencies that can be moved into other distinct components.

Find themes such as API calls, orchestration of child components, notification, and other domain logic.

Use a separate class to encapsulate API calls. This enables centralized control over forming requests and normalizing responses.

Use a dedicated component for handling the interaction between child components. Using a dedicated class to share data can help avoid coupling as well.

Use a separate class or component to handle other domain logic:

Example 1: The presentation of a timer is maintained. The timer is triggered, tracked, displayed, stopped and reset within the monolith component.

Example 2: The component allows the user to update the view with new data from the server without using the browser refresh button. After a user triggers a refresh: a server request is formed, the request is sent, a response is received and parsed, it is then sent to areas that need the parsed response and the view is updated appropriately.

Example 3: User input is maintained. A form contains multiple labels and input controls. The user input is validated. When the user input is invalid, a notification is displayed to the user. When a user completes the form, it can be submitted to the server so there are more server requests and responses to handle.

All of the logic and presentation of these examples can be contained in separate classes and components. They will take with them the necessary responsibilities and dependencies of the monolith component – only what they need.

Repeat As Necessary

The fifth step is knowing what is left after extracting the common ground. If we are lucky, this means the monolith component now does only one thing. If not, repeat the previous steps until the component does just one thing. This is assuming that all of the responsibilities of the component will be known and are necessary.

A monolith component is too big. It does too much. It knows too much. It has too many responsibilities. As developers, we are responsible for delegation. If a component does too much, it is our fault. There are many ways to prevent and refactor monolith components. There have been volumes of work describing refactoring methodologies. This article describes some ways that have worked for me when refactoring a monolith component.