At SketchUp I managed a user interface library and the development best practices used by multiple teams on different projects. I was new to Angular so the challenge was keeping feature building moving forward whilst also working out what the best practices should be, what are good patterns for abstraction, and backtracking as necessary taking better approaches once they became apparent. This article describes some of the things I landed on which worked out well, saving coding (and testing) effort and improving developer experience.
One theme runs all the way through: have a set of standards, and apply them very strictly. That needs good discipline in the team, and a good understanding of the reasons for the principles and how they fit together. This required some trial and error with Angular itself as well as watching how the teams naturally worked and what patterns they discovered before deciding on the path forward. Luckily giving ample time for maintenance and improvement was part of the existing development culture at SketchUp, which allowed us to go back and clean up existing code whilst also developing new features at the same time.
The practices come under four main categories:
- Define your entities - a fixed set of kinds of thing in the code, each with strict rules
- The user interface library - one place that knows what everything looks like
- Using Angular effectively - loading, state and templates, with the framework rather than against it
- Code organisation - where code goes, how it's written, and where the types are checked
Define your entities
This was the hardest thing to get right, but also the most important. There's a fixed set of kinds of entity, and each has a very strict set of definitions for how it looks, how it works, and how it interacts with the others. This is the main thing that answers a lot of questions about how any particular task should be done, and it keeps all the developers writing code that's consistent across the whole codebase.
It's a principle I'd apply to a lot of projects, but in Angular in particular the entities turned out to be a small set of 7 or so, with the main ones being:
Each of these had a strict pattern, written up in the coding standards wiki. There are exceptions to these, as there always are, but we managed to hide them inside the common libraries. If there was any dirty code, at least it was in one place, inside the implementation of the user interface library or the charting library, out of the way of normal day-to-day app development. That left the features themselves free to follow the rules pretty strictly, and any special cases would be moved into the libraries and abstracted away.
Immutable data objects
We made data objects immutable all the way through the system. An immutable object has a set of immutable fields coming into its constructor, and it can only contain two other kinds of thing: static functions, which are specific ways of constructing the object, and utility functions, which return updated versions of the object or other calculations based on its contents.
export class ProjectData {
constructor(
readonly id: number,
readonly name: string,
readonly tags: string[],
readonly owner: MemberData,
readonly models: ModelData[],
) {}
static FromName(name: string, owner: MemberData) {
return new ProjectData(0, name, [], owner, []);
}
withName(name: string) {
return new ProjectData(this.id, name, this.tags, this.owner, this.models);
}
get modelCount() {
return this.models.length;
}
}
These objects are also where conversion routines live, and where data that isn't type safe enters TypeScript-land, through a static FromJson function. That's described in The type safety boundary.
Pure components
A component takes its inputs, and its template shows them. Everything it shows is either an input or a pure function of its inputs, it has no lifecycle hooks, and it holds no state of its own: any state belongs to a component in the user interface library, or to the communications library. How strict that can be is in Pure components, almost.
Services
Services are the singletons that Angular injects, and they can be used for a lot of different purposes, but we narrowed it down to two: functions which return request objects destined for the loader pipe in component templates (the functions themselves did not load anything from the backend, merely prepare a request containing the endpoint and type safety details), and pure functions to assist components where the function was used by multiple components (a pure function which is used by a single component can live in the component).
Angular pipes
Pipes turn one value into another inside a template: formatting a date or a price, for example, so the component doesn't need a getter for it. The loading pipes, like httpGet, are the exception that breaks the rules, because they hold a subscription and talk to a service, and they live inside the communications library, out of the way. They're described in Loading.
The user interface library
A lot of the work went into the user interface library, and a lot of the benefit came from it: one place that knows what everything looks like, so the rest of the application doesn't have to.
One global stylesheet
I started with component CSS, where every component has its own stylesheet next to it:
.header { padding: 8px; }
.header h1 { font-size: 20px; margin: 0 0 8px 0; }
.header .buttons button { margin-right: 8px; }
I very quickly realised this wasn't a scalable solution. I got bored of typing (or code reviewing) padding: 8px on each and every component, and it created a lot of work for the designer, because he had to design each and every component and couldn't rely on a standard design system.
The solution was a global stylesheet, combined with wrapping every component including titles and text in Angular components, using a small scattering of classes to override defaults (for example the titles defaulted to left-aligned but class="centre" on the title component would reposition it if needed). The remaining thing which was truly custom for individual components was sizing, which was achieved with simple inline styles because these were one-off properties of the components.
<project-preview style="height: 240px"></project-preview>
This meant the designer didn't have to create pixel-perfect Figma diagrams with all the measurements every time, and didn't have to check thoroughly the end result. Instead he could work at a higher level, with standard components, knowing that he'd get standard spacing, padding and colours everywhere.
It's better for the developers too. A team all writing their own CSS into components is difficult to manage, but CSS is also hard for the developers, and it was one of people's least favourite things to deal with. With it managed in one global place and wrapped up in components, CSS disappeared from individual components which meant a lot less code and fewer files where larger components were split into separate code and markup files.
A component for everything
The templates were rapidly turning into <div> soup. The remedy was to abstract every element, right down to basic titles, subtitles and text, which wrap the plain h1, h2 and p tags. It was a complete abstraction, so developers were always working in the user interface library, with <ui-title>, <ui-subtitle> and <ui-text>, and never with the tags underneath.
This might seem like a large undertaking but in reality there are not that many basic components in the kind of application we were building, so after an initial flurry of adding the necessary components on demand this settled down and became very stable.
Many of these components did little more than put a class on the custom element in the DOM, for the global stylesheet to style:
@Component({
selector: 'ui-subtitle',
template: '<h2><ng-content></ng-content></h2>',
host: { class: 'ui-subtitle' },
})
export class UiSubtitleComponent {}
.ui-subtitle h2 { font-size: 18px; font-weight: 600; margin: 0; }
A component that small made the code highly readable, and it ensured there was only one correct way of doing anything. A subtitle is a <ui-subtitle>, everywhere, and if subtitles need to change, they change in one place.
<ui-title>Riverside house</ui-title>
<ui-subtitle>Models</ui-subtitle>
<ui-text>Four models, last updated three days ago.</ui-text>
Layout & spacing
Something that often catches people out is the spacing between components. If you put some invisible padding on the right of a button, so that the next button is the right distance away from it, you're starting to ask for trouble as you scale the application and reuse components. There'll be some places where you want more space between that button and some other button, and some where there's nothing next to it at all. Before this, the team was constantly chasing padding and spacing issues around the application, to the great frustration of the design team.
So I have a simple rule for this: no component has any invisible padding around its edge. If it has a background, it can have padding inside the background, but the visible edge of the component never tries to push anything away from itself. Instead, parent components impose spacing on their immediate children.
In practice this meant three layout components, <ui-row>, <ui-column> and <ui-grid>. This was before flexbox's gap worked in every browser, so what they did was put padding on each of their immediate children, on the bottom in a column, and then take it off the very last one:
ui-column { display: block; }
ui-column > * { display: block; padding-bottom: 16px; }
ui-column > *:last-child { padding-bottom: 0; }
ui-row { display: flex; align-items: center; }
ui-row > * { padding-right: 8px; }
ui-row > *:last-child { padding-right: 0; }
The padding goes on the child's own custom element, the one Angular puts in the DOM, which is outside anything the child draws. A button's background is inside its <ui-button>, so the padding is invisible space between it and the next one, which is exactly where the row wants it. The grid spaces its children the same way, in both directions.
What a template looks like
The combination of wrapping all the basic HTML tags I needed, the layout components and the global stylesheet made the template for any component look really simple. Here's an example of how one could look:
<ui-column>
<ui-title class="centre">Project settings</ui-title>
<ui-text>Changes are saved as soon as you make them.</ui-text>
<ui-subtitle>Members</ui-subtitle>
<ui-grid>
<project-member-card *ngFor="let member of members" [member]="member"></project-member-card>
</ui-grid>
<ui-row>
<ui-button (click)="invite()">Invite</ui-button>
<ui-button (click)="leave()">Leave project</ui-button>
</ui-row>
</ui-column>
There are no <div>s, no styles and almost no classes, just the components. The only class is the one overriding a default, the centred title, and the global stylesheet has a rule for it:
ui-title.centre h1 { text-align: center; }
Using Angular effectively
With the library in place, the rest is about how the application's own components use Angular: how they load data, what they're allowed to contain, where their state lives, and how much they leave to the template.
Loading
Loading data is one of the common patterns that's best abstracted away completely. One component, <ui-loader>, can wrap any part of the page, and a pipe, httpGet, fetches data straight from the template. While anything inside the loader is loading, the loader hides its content and locks it:
<ui-loader>
<ng-container *ngIf="('/api/projects/' + projectId) | httpGet as project">
<ui-title>{{ project.name }}</ui-title>
<project-model-list [projectId]="projectId"></project-model-list>
</ng-container>
</ui-loader>
The component has no loading flags, no subscriptions and no lifecycle methods, and a child component that loads its own data keeps the loader locked until it's finished too. How the loader and the pipe find each other is in Automatic loading spinners in Angular.
Pure components, almost
This is one I wasn't sure would work out, but it turned out fine, and beneficial: being strict about what components could actually contain.
It became clear that any of the lifecycle hooks, like ngOnChanges and ngOnDestroy, were an anti-pattern, and a sign that something was being done against the grain of the reactive system. ngOnChanges especially: if you're reacting to changes manually, it's a good sign that you're doing something the framework already has a better solution for. Here's a component working out its title whenever its input changes:
export class ProjectHeaderComponent implements OnChanges {
@Input() project: ProjectData;
title: string;
ngOnChanges(changes: SimpleChanges) {
if (changes.project) {
this.title = this.project.name + ' (' + this.project.models.length + ' models)';
}
}
}
The ideal pure component I landed on has a template that only uses the attributes passed into the component, or pure functions of those attributes. Generally these are basic getters:
export class ProjectHeaderComponent {
@Input() project: ProjectData;
get title() {
return this.project.name + ' (' + this.project.models.length + ' models)';
}
}
Angular reads the getter whenever it checks the template, so the title is always right, and there's nothing to keep in step.
Some are pure functions that take arguments from where they're called in the template, and combine them with other pure functions and the component's attributes to produce a value. These can even be interactive, by using the loader pipe inside the template as the argument to the function:
<ui-text>{{ countDone(('/api/projects/' + projectId + '/tasks') | httpGet) }} tasks done</ui-text>
countDone(tasks: ProjectTask[] | undefined) {
return (tasks || []).filter((task) => task.done).length;
}
When the tasks arrive, or change, the pipe returns the new list and the count follows it. The component never knows anything was loaded.
State
I had a separate pattern for components that did genuinely need state. But because I grew an extensive UI library, most of the state was hidden away in there. The currently selected tab in a tabset, for example, belongs to <ui-tabset>, and the component using it never sees it:
<ui-tabset>
<ui-tab title="Members">
<project-members [projectId]="projectId"></project-members>
</ui-tab>
<ui-tab title="Settings">
<project-settings [projectId]="projectId"></project-settings>
</ui-tab>
</ui-tabset>
These applications were generally showing real-time data from the backend, so it was actually the communications module that did most of the state management. It provided the abstraction for setting values on the backend, and it kept track of all of the loader pipes in the application. So when a value was set, it could optimistically send the new value out of every loader pipe showing it, before it had even been set in the backend:
export class ProjectRenameComponent {
@Input() projectId: number;
constructor(private comms: CommsService) {}
get nameUrl() {
return '/api/projects/' + this.projectId + '/name';
}
rename(name: string) {
this.comms.set(this.nameUrl, name);
}
}
<ui-text-input [value]="nameUrl | httpGet" (change)="rename($event)"></ui-text-input>
Every httpGet pipe on that URL, anywhere in the application, shows the new name straight away, and no component had to hold on to it in between.
Lean on the template
It's tempting to make all kinds of data structures in TypeScript and then pass them into components: an object describing a chart, an array of column definitions for a table, a list of things to draw in a 3D view. Each one needs types of its own, and code in the page's component to build it from the data the application already has.
Leaning on the template as much as possible does away with most of that code. Instead of building a structure and passing it in, the page writes it in its template, out of components, the same way as the rest of the page. The component at the top finds its parts with @ContentChildren, and the parts find it through dependency injection. That keeps the whole application declarative: the template says what's on the page, and the page's component has almost nothing in it.
<chart-bar title="Sales">
<chart-bar-item *ngFor="let month of report.months" [label]="month.name" [value]="month.sales"></chart-bar-item>
</chart-bar>
Data objects do get you a long way. A chart can be described by a title, some series and a few options, and for a while that's all it needs. But as soon as we needed tooltips and overlays on the charts, we wanted arbitrary markup in them: a title and a line of text in a tooltip, a button in an overlay. Carrying on with data meant describing titles, text and the other parts of the interface in the chart's options, and that was starting to grow into an abstraction that looked very much like the user interface library itself. With the chart in the template, a tooltip is just more template, made of the components the application already has:
<chart-bar title="Sales">
<chart-bar-item *ngFor="let month of report.months" [label]="month.name" [value]="month.sales">
<chart-tooltip>
<ui-subtitle>{{ month.name }}</ui-subtitle>
<ui-text>{{ month.orders }} orders, {{ month.returns }} returns</ui-text>
</chart-tooltip>
</chart-bar-item>
</chart-bar>
As more went into the templates, whole families of data classes went away. In the more presentational modules, like the charts, they almost entirely disappeared, and the result was more versatile than where we'd started, because anything the user interface library could show could now go inside a chart. Some examples of this:
- DOM as data: a CSV download whose columns, rows and cells are components, shown in the page as a preview and read back to make the file.
- Declarative charts in Angular: bar, pie and line charts made of components, each part drawing itself.
- SVG components in Angular: components that are part of an SVG drawing, which the charts are built on.
- 3D components in Angular with three.js: a 3D scene written in the template, with a component for each thing in it.
The same went for different types of interactive 2D and 3D maps, each written in the template out of components.
Code organisation
With several teams in one codebase, the code needs to look as if one person wrote it, so that anyone can find their way around any part of it and see straight away when something's wrong. These are the rules that made the most difference.
The file system
With developers on different projects using a common system, something that happens unless you are vigilant is duplicated functionality repeated in different places in the codebase. One example kept coming up: lots of different developers made their own date and time classes and abstractions. That was made worse by having definitions of helper classes in the same file as one of the components where they were needed.
The first way to tackle this is to require that every class is defined in its own file, named after the class. The second is a strict standard for the naming of those files and classes. The application was divided into a set of modules, and within each module every class had to start with the name of the module. Each module had a strict directory structure as well which separated out ui, data, services, classes and so on at the top level:
calendar/
classes/
calendar-date.ts CalendarDate
calendar-time-range.ts CalendarTimeRange
data/
calendar-event.ts CalendarEvent
services/
calendar-time-zone.service.ts CalendarTimeZoneService
ui/
calendar-date-picker.component.ts CalendarDatePickerComponent
This made it immediately apparent when something was in the wrong module. If it's about dates or times, it goes in the calendar module, and anywhere else its name gives it away. And before anyone writes a date class, they know exactly where to look to see if there's one already.
Where the code grows
The standard libraries, for the user interface, for communications, and for things like dates and times, were built up on demand as I went along. They grow much more slowly than the application: like the user interface library, after the first flurry it became rare to add anything to them.
So be very aware of, and plan for, which parts of the file system will grow rapidly and which will grow slowly over time. The number of modules grows rapidly as the features come in, because each feature goes in its own module within the application. But the number of standard components, the amount of CSS and the other shared things grow much more slowly:
calendar/ a standard library, grows slowly
comms/ a standard library, grows slowly
ui/ a standard library, grows slowly
members/ a feature
project/ a feature
... a new module for each new feature
You have to manage carefully where it grows. You don't want it growing everywhere all at once: you want it organised so that the parts that grow without limit as features are added are kept in order, and everything else grows in very specific ways.
The type safety boundary
As soon as any data comes in from the outside world, it must immediately be placed into a type safe immutable data object, through a suitable FromJson function. These functions use an assert library, like the one in Composable typechecking in JavaScript:
static FromJson(json: unknown) {
const object = Assert.Object(json);
return new ProjectData(
Assert.Number(object.id),
Assert.String(object.name),
Assert.Array(Assert.String)(object.tags),
MemberData.FromJson(object.owner),
Assert.Array(ModelData.FromJson)(object.models),
);
}
ProjectData's FromJsonThe function first checks that what it was given is actually an object, then constructs the data object, checking one field per line. Each check returns the value if it's the right type and throws if it isn't. The assert library is set up with curried functions, so Assert.Array(Assert.String) is itself a check, and it works recursively: a field that's another data object is checked with that object's own FromJson, directly or inside Assert.Array for a list of them. The result is either a fully type safe object or an exception.
The only reliable way to deal with type safety is to do it right at the boundary. You don't want to be passing values around and then doing the type checking just before they're used, by which point nobody knows where a bad value came from. And because everything was going through the loader pipe, we could build the type checking into the underlying communications library. So that the library knew how to decode a particular endpoint's data, we wrapped requests in a request object, which held the endpoint's URL and a reference to the FromJson function for decoding it:
export class CommsRequest<T> {
constructor(
readonly url: string,
readonly fromJson: (json: unknown) => T,
) {}
}
export function ProjectRequest(projectId: number) {
const url = '/api/projects/' + projectId;
return new CommsRequest(url, ProjectData.FromJson);
}
The communications library itself dealt with failures and retries, and if a request failed permanently, the loader showed the error to the user in that part of the page.
One calculation per line
Looking at the countDone example in Pure components, almost, with the expression (tasks || []).filter((task) => task.done).length, it's clear that expressions like this can become unreadable as they get larger, or at least slow developers down when they have to understand them. And it's not always clear if there are any bugs just by looking. I adopted a style where each separate calculation has to appear on its own line:
countDone(optionalTasks: ProjectTask[] | undefined) {
const tasks = optionalTasks || [];
const taskDone = (task: ProjectTask) => task.done;
const doneTasks = tasks.filter(taskDone);
const doneTaskCount = doneTasks.length;
return doneTaskCount;
}
This is much more readable, and easier to change, especially when an expression might involve multiple chained filters and transformations. It names the intent of each part, which would otherwise be anonymous in the middle of an expression, and it's much easier to parse visually.
Undefined
Something that I was not sure would work, but actually gave us no trouble at all, was settling on just using undefined for values that aren't present, as it's JavaScript's default anyway. This meant that if (value === undefined) was all we needed, rather than if (value === undefined || value === null), or worse, various combinations of if (typeof value === 'undefined') and other ways of checking the value.
We also had to be strict with the check, which was easy with this convention: if (value) can too easily catch values that are falsy but defined, like 0 or an empty string.
Team organisation
None of this works unless everyone is on board. The point is consistent code across all of the teams, and that takes effort, starting with a good set of documentation that's kept up to date. Luckily that isn't too difficult: for the basic user interface components it's mainly additive, a new page for each new component, and the pages for the existing ones rarely change.
Once a standard is in place, though, mistakes are costly. Changing it means getting everyone on board with a new way of working, as well as changing all the code that already follows the old one. But some of it has to be done iteratively anyway, because you can't know it all up front. You only find out how a larger application develops in the framework by building one, and you only find out how the team operates in practice, how they go about coding and the foibles of the developers themselves, by working with them.
In the end the process is about people, and the key thing is developer experience. The purpose of a lot of this is to make the developers' lives easier in the long run, even if in the short term some of it seems like a hassle: wrapping a heading in a component, or moving a helper class out into its own file in the right module.
The result
It was the combination that counted: a global stylesheet, a single design system embodied in the user interface library, the loader and the other abstractions, and the templates defining as much as possible, so that we didn't need lots of little data classes and data passed around. The code ended up much smaller and more readable than where we'd been heading at the start, and a lot of the natural refactors we did along the way were mostly a matter of chopping code out.
See also
- SVG components in Angular - components that are part of an SVG drawing, by attaching them to the group element
- DOM as data - a CSV download whose columns and rows are components, previewed in the page
- Declarative charts in Angular - charts written in the template as components, instead of data objects built first
- 3D components in Angular with three.js - a three.js scene written in the template
- Automatic loading spinners in Angular - how the loader and the httpGet pipe find each other
- Composable typechecking in JavaScript - the assert library behind the
FromJsonfunctions - Type safety at the boundaries - the
FromJsonpattern in full, and why we didn't use a schema library