Improving Code Reusability in Angular Projects

https://medium.com/@eugeniyoz/improving-code-reusability-in-angular-projects-b169d4a1c786

In this article, you’ll find recommendations on how to make your Angular components and services more reusable, maintainable, and scalable.

Pure Functions

The most effective way to make your code reusable is to move as much code as possible to pure functions.

Such functions have no side effects, have no state, and don’t mutate their arguments. Every time we call a pure function with the same arguments, it will return the same result.

Let’s refactor a component’s method into a pure function:

export class ExampleComponent {
@Input() items: Item[];
@Input() users: User[];

@Output() connected = new EventEmitter<Item>();

private readonly errEmptyItemMsg = 'Item data can not be empty';

//...

protected addConnection(toItem: Item) {
if (!toItem.data) {
this.displayError(this.errEmptyItemMsg);
return;
}

let hasNewConnection = false;

for (const user of this.users) {
if (!user.itemRefs.includes(toItem.id)) {
user.itemRefs.push(toItem.id);
hasNewConnection = true;
}
}

if (hasNewConnection) {
this.connected.emit(toItem);
}
}

private displayError(errMsg: string) {
// ...
}
}

Method addConnection() validates toItem, then adds a new item ID to every user. It can display an error and emit an event.

Let’s imagine that this method has not 18 lines, but 180, with complex validation rules. And suddenly, we need exactly this logic, with exactly the same validation (or a new data construction) in a completely different module of our application. Do not look at the “Copy” and “Paste” menu items in your editor — if validation logic is changed in one place, it should be modified in every other place.

Even if we were to swear to update this code in every place on every change, it’s still tightly coupled to our component. So, we simply cannot copy this code to any other place without also copying dependent parts of the component. You can easily spot this by looking for the usages of this.:

this.displayError()
this.errEmptyItemMsg
this.users
this.connected

We can split addConnection() into two methods: validation and linking.

export class ExampleComponent {
//...
@Output() usersChange = new EventEmitter<User[]>();

protected addConnection(toItem: Item) {
if (!isItemConnectable(toItem)) {
this.displayError(this.errEmptyItemMsg);
return;
}

const { users, hasNewConnection } = addItemToUsers(toItem, this.users);

if (hasNewConnection) {
this.connected.emit(toItem);
this.usersChange.emit(users);
}
}

// ...
}

export function isItemConnectable(item: Item): boolean {
// here we have 100 lines of validation...
// ...
// ... very complex logic here ...
// ...
// ... not like this :)
return !!item.data;
}

export function addItemToUsers(item: Item, users: User[]): {
hasNewConnection: boolean,
users: User[],
} {
let hasNewConnection = false;
const updatedUsers = [] as User[];
for (const user of users) {
if (!user.itemRefs.includes(item.id)) {
updatedUsers.push({ ...user, itemRefs: [...user.itemRefs, item.id] });
hasNewConnection = true;
} else {
updatedUsers.push(user);
}
}
return {
users: updatedUsers,
hasNewConnection
};
}

Because the new functions should be pure, they cannot modify their arguments. So, in addItemToUsers(), we had to create a new array of users and make a shallow copy for the users we want to connect, instead of mutating them directly.

// before
if (!user.itemRefs.includes(toItem.id)) {
user.itemRefs.push(toItem.id);
}

// after
if (!user.itemRefs.includes(item.id)) {
updatedUsers.push({ ...user, itemRefs: [...user.itemRefs, item.id] });
} else {
updatedUsers.push(user);
}

this.usersChange.emit(users);

This way, we actually fixed quite a nasty bug of data de-synchronization, described in more detail in this article. Now we will emit a new array of users every time a new connection is created, so the parent component will have the correct data. Bingo!

Now we can reuse our super complex logic in other places — the new functions have no dependencies, all they need are their arguments.

When refactoring your code into pure functions, require as little information in arguments as possible. If your function requires product: HugeProductDataStructure and in its code it uses product just for product.id and product.price, then it is much better to define arguments like productId and productPrice, rather than requiring a structure that might be difficult to fetch in some places of your code. But don’t over-explode your list of arguments ;)

Component State Management

Some methods just can not avoid using this because they have to modify the state of your component. You can still make such code reusable, by moving this logic into a separate file, called “local store”.

A local store might be represented as a class or as a function (see examples in NgRx SignalStore docs).

Here is an example of how we could move logic, responsible for saving users, to a local store:

@Injectable()
export class ExampleStore {
private readonly api = inject(ApiService);

readonly saveUsers = sideEffect<User[]>(_ => _.pipe(
exhaustMap((users) => this.api.saveUsers(users)),
catchError((err) => {
this.displayError(err.msg);
return EMPTY;
})
));
}

@Component({
selector: 'app-example',
// ...
providers: [ExampleStore]
})
export class ExampleComponent {
// ...
private readonly store = inject(ExampleStore);

protected saveUsers() {
this.store.saveUsers(this.users);
}
}

Because of this refactoring, we now can reuse logic, responsible for saving users' data (which often is not as primitive as this example) in other places of our code, simply by injecting the ExampleStore.

You can read more about the benefits that this refactoring brings, and about different kinds of stores, in this article.

In the previous code example, you might notice that saveUsers() has just one line, and some of you may ask, “Maybe we could just call this method directly from the template? Why the extra wrapping?”

The answer here is: it is up to you to decide. Some developers trust their local stores and IDEs, so if the store’s method name or signature changes, the IDE will automatically update it in the template. Other developers say that templates calling only component’s methods look cleaner and more reliable to them. This topic is very subjective, and there cannot be only one correct answer.

Miscellaneous

  • Prefer composition to inheritance. Never extend components (yes, never). In some very rare cases, when you see that only inheritance can be used, it is okay to extend stores. However, never extend components. We might think that we increase code reusability this way, but there are other ways to achieve the same result without inheritance. What we sacrifice when we extend components is maintainability, and that is a very important aspect of the code.
  • Even if ::ng-deep is un-deprecated, try to avoid it. When it’s not possible (and there are such cases), use it with extreme care. To help your future self, use very specific selectors inside ::ng-deep. When you reuse components that use ::ng-deep, and these components have multiple levels of sub-components, things might quickly go out of control if the selectors inside ::ng-deep are not specific enough.
  • When using Observables, avoid nested subscriptions. Additionally, methods of your services that return observables are much more reusable than methods that subscribe. You don’t always need that level of reusability, but sometimes you might want to reuse code that is inside a method that subscribes and unsubscribes. In such cases, just refactor that method into two: one that returns an observable, and the second one that uses that observable.
{
"by": "EugeneOZ",
"descendants": 0,
"id": 40246827,
"score": 1,
"time": 1714738763,
"title": "Improving Code Reusability in Angular Projects",
"type": "story",
"url": "https://medium.com/@eugeniyoz/improving-code-reusability-in-angular-projects-b169d4a1c786"
}
{
"author": "🪄 OZ 🎩",
"date": "2024-11-27T12:19:19.104Z",
"description": "In this article, you’ll find recommendations on how to make your Angular components and services more reusable, maintainable, and scalable.",
"image": "https://miro.medium.com/v2/resize:fit:1200/1*YsD5noSIX8ymdECqSf-WFA.jpeg",
"logo": "https://logo.clearbit.com/medium.com",
"publisher": "Medium",
"title": "Improving Code Reusability in Angular Projects",
"url": "https://medium.com/@eugeniyoz/improving-code-reusability-in-angular-projects-b169d4a1c786"
}
{
"url": "https://medium.com/@eugeniyoz/improving-code-reusability-in-angular-projects-b169d4a1c786",
"title": "Improving Code Reusability in Angular Projects",
"description": "In this article, you’ll find recommendations on how to make your Angular components and services more reusable, maintainable, and scalable.Pure FunctionsThe most effective way to make your code reusable is to...",
"links": [
"https://medium.com/@eugeniyoz/improving-code-reusability-in-angular-projects-b169d4a1c786"
],
"image": "https://miro.medium.com/v2/resize:fit:1200/1*YsD5noSIX8ymdECqSf-WFA.jpeg",
"content": "<div><p>In this article, you’ll find recommendations on how to make your Angular components and services more reusable, maintainable, and scalable.</p><h2 id=\"959f\">Pure Functions</h2><p>The most effective way to make your code reusable is to move as much code as possible to <a href=\"https://en.wikipedia.org/wiki/Pure_function\" target=\"_blank\">pure functions</a>.</p><p>Such functions have no side effects, have no state, and don’t mutate their arguments. Every time we call a pure function with the same arguments, it will return the same result.</p><p>Let’s refactor a component’s method into a pure function:</p><pre><span>export class ExampleComponent {<br /> @Input() items: Item[];<br /> @Input() users: User[];<p> @Output() connected = new EventEmitter&lt;Item&gt;();</p><p> private readonly errEmptyItemMsg = 'Item data can not be empty';</p><p> //...</p><p> protected addConnection(toItem: Item) {<br /> if (!toItem.data) {<br /> this.displayError(this.errEmptyItemMsg);<br /> return;<br /> }</p><p> let hasNewConnection = false;</p><p> for (const user of this.users) {<br /> if (!user.itemRefs.includes(toItem.id)) {<br /> user.itemRefs.push(toItem.id);<br /> hasNewConnection = true;<br /> }<br /> }</p><p> if (hasNewConnection) {<br /> this.connected.emit(toItem);<br /> }<br /> }</p><p> private displayError(errMsg: string) {<br /> // ...<br /> }<br />}</p></span></pre><p>Method <code>addConnection()</code> validates <code>toItem</code>, then adds a new item ID to every user. It can display an error and emit an event.</p><p>Let’s imagine that this method has not 18 lines, but 180, with complex validation rules. And suddenly, we need exactly this logic, with exactly the same validation (or a new data construction) in a completely different module of our application. Do not look at the “Copy” and “Paste” menu items in your editor — if validation logic is changed in one place, it should be modified in every other place.</p><p>Even if we were to swear to update this code in every place on every change, it’s still tightly coupled to our component. So, we simply cannot copy this code to any other place without also copying dependent parts of the component. You can easily spot this by looking for the usages of <code>this.</code>:</p><pre><span>this.displayError()<br />this.errEmptyItemMsg<br />this.users<br />this.connected</span></pre><p>We can split <code>addConnection()</code> into two methods: validation and linking.</p><pre><span>export class ExampleComponent {<br /> //...<br /> @Output() usersChange = new EventEmitter&lt;User[]&gt;();<p> protected addConnection(toItem: Item) {<br /> if (!isItemConnectable(toItem)) {<br /> this.displayError(this.errEmptyItemMsg);<br /> return;<br /> }</p><p> const { users, hasNewConnection } = addItemToUsers(toItem, this.users);</p><p> if (hasNewConnection) {<br /> this.connected.emit(toItem);<br /> this.usersChange.emit(users);<br /> }<br /> }</p><p> // ...<br />}</p><p>export function isItemConnectable(item: Item): boolean {<br /> // here we have 100 lines of validation...<br /> // ...<br /> // ... very complex logic here ...<br /> // ...<br /> // ... not like this :)<br /> return !!item.data;<br />}</p><p>export function addItemToUsers(item: Item, users: User[]): {<br /> hasNewConnection: boolean,<br /> users: User[],<br />} {<br /> let hasNewConnection = false;<br /> const updatedUsers = [] as User[];<br /> for (const user of users) {<br /> if (!user.itemRefs.includes(item.id)) {<br /> updatedUsers.push({ ...user, itemRefs: [...user.itemRefs, item.id] });<br /> hasNewConnection = true;<br /> } else {<br /> updatedUsers.push(user);<br /> }<br /> }<br /> return {<br /> users: updatedUsers,<br /> hasNewConnection<br /> };<br />}</p></span></pre><p>Because the new functions should be pure, they cannot modify their arguments. So, in <code>addItemToUsers()</code>, we had to create a new array of users and make a shallow copy for the users we want to connect, instead of mutating them directly.</p><pre><span>// before<br />if (!user.itemRefs.includes(toItem.id)) {<br /> user.itemRefs.push(toItem.id);<br />}<p>// after<br />if (!user.itemRefs.includes(item.id)) {<br /> updatedUsers.push({ ...user, itemRefs: [...user.itemRefs, item.id] });<br />} else {<br /> updatedUsers.push(user);<br />}</p><p>this.usersChange.emit(users);</p></span></pre><p>This way, we actually fixed quite a nasty bug of data de-synchronization, described in more detail in <a target=\"_blank\" href=\"https://medium.com/@eugeniyoz/angular-inputs-and-single-source-of-truth-75939491f701\">this article</a>. Now we will emit a new array of users every time a new connection is created, so the parent component will have the correct data. Bingo!</p><p>Now we can reuse our super complex logic in other places — the new functions have no dependencies, all they need are their arguments.</p><p>When refactoring your code into pure functions, require as little information in arguments as possible. If your function requires <code>product: HugeProductDataStructure</code> and in its code it uses <code>product</code> just for <code>product.id</code> and <code>product.price</code>, then it is much better to define arguments like <code>productId</code> and <code>productPrice</code>, rather than requiring a structure that might be difficult to fetch in some places of your code. But don’t over-explode your list of arguments ;)</p><h2 id=\"2e7b\">Component State Management</h2><p>Some methods just can not avoid using <code>this</code> because they have to modify the state of your component. You can still make such code reusable, by moving this logic into a separate file, called “local store”.</p><p>A local store might be represented as a class or as a function (see examples in <a href=\"https://ngrx.io/guide/signals/signal-store\" target=\"_blank\">NgRx SignalStore docs</a>).</p><p>Here is an example of how we could move logic, responsible for saving users, to a local store:</p><pre><span>@Injectable()<br />export class ExampleStore {<br /> private readonly api = inject(ApiService);<p> readonly saveUsers = sideEffect&lt;User[]&gt;(_ =&gt; _.pipe(<br /> exhaustMap((users) =&gt; this.api.saveUsers(users)),<br /> catchError((err) =&gt; {<br /> this.displayError(err.msg);<br /> return EMPTY;<br /> })<br /> ));<br />}</p><p>@Component({<br /> selector: 'app-example',<br /> // ...<br /> providers: [ExampleStore]<br />})<br />export class ExampleComponent {<br /> // ...<br /> private readonly store = inject(ExampleStore);</p><p> protected saveUsers() {<br /> this.store.saveUsers(this.users);<br /> }<br />}</p></span></pre><p>Because of this refactoring, we now can reuse logic, responsible for saving users' data (which often is not as primitive as this example) in other places of our code, simply by injecting the <code>ExampleStore</code>.</p><p>You can read more about the benefits that this refactoring brings, and about different kinds of stores, in <a target=\"_blank\" href=\"https://medium.com/@eugeniyoz/application-state-management-with-angular-signals-b9c8b3a3afd7\">this article</a>.</p><p>In the previous code example, you might notice that <code>saveUsers()</code> has just one line, and some of you may ask, “Maybe we could just call this method directly from the template? Why the extra wrapping?”</p><p>The answer here is: it is up to you to decide. Some developers trust their local stores and IDEs, so if the store’s method name or signature changes, the IDE will automatically update it in the template. Other developers say that templates calling only component’s methods look cleaner and more reliable to them. This topic is very subjective, and there cannot be only one correct answer.</p><h2 id=\"17f9\">Miscellaneous</h2><ul><li>Prefer <a href=\"https://en.wikipedia.org/wiki/Composition_over_inheritance\" target=\"_blank\">composition to inheritance</a>. Never extend components (yes, never). In some very rare cases, when you see that only inheritance can be used, it is okay to extend stores. However, never extend components. We might think that we increase code reusability this way, but there are other ways to achieve the same result without inheritance. What we sacrifice when we extend components is <strong>maintainability</strong>, and that is a very important aspect of the code.</li><li>Even if <code>::ng-deep</code> is un-deprecated, try to avoid it. When it’s not possible (and there are such cases), use it with extreme care. To help your future self, use very specific selectors inside <code>::ng-deep</code>. When you reuse components that use <code>::ng-deep</code>, and these components have multiple levels of sub-components, things might quickly go out of control if the selectors inside <code>::ng-deep</code> are not specific enough.</li><li>When using Observables, avoid nested subscriptions. Additionally, methods of your services that return observables are much more reusable than methods that subscribe. You don’t always need that level of reusability, but sometimes you might want to reuse code that is inside a method that subscribes and unsubscribes. In such cases, just refactor that method into two: one that returns an observable, and the second one that uses that observable.</li></ul></div>",
"author": "@eugeniyoz",
"favicon": "https://miro.medium.com/v2/5d8de952517e8160e40ef9841c781cdc14a5db313057fa3c3de41c6f5b494b19",
"source": "medium.com",
"published": "2024-06-12T09:35:24.875Z",
"ttr": 217,
"type": "article"
}