Friday, 9 June 2023

What is signals in Anglaur 16?Example

Angular has introduced a new feature called signals, which provides a way for code to notify templates and other code when data changes. This enhancement improves Angular's change detection mechanism, leading to better performance and more reactive code.

As Angular v16 is released on May 2023 and developers can try out this powerful feature. 
Let's try to understand what exactly are Signals,

Signals in Angular 16

To understand the motivation behind signals, let's consider a simple example without signals. Suppose we have code that performs basic math operations:

typescript
let x = 7; let y = 2; let z = x + y; console.log(z);

In this case, the value of z is 9. After a few lines of code, we changed the value of x 

typescript
let x = 7; let y = 2; let z = x + y; console.log(z); x = 10; console.log(z);

If we log the z value now what is it going to log out on the console? Of course, it will log out 9 only. In this case, the value of z is because it is assigned the value when the expression is first evaluated. The variable z does not react to changes in x or y.

With signals, we can make our variables reactive. For instance, the above example using signals would look like this:

typescript
const x = signal(7); const y = signal(2); const z = computed(() => x() + y()); console.log(z()); // 9 x.set(10); console.log(z()); // 12 (x + y)

In the code above, x and y are defined as signals with initial values of 7 and 2, respectively. The z signal is computed based on the values of x and y. Whenever x or y signals change, the computed z signal automatically recalculates its value. This approach makes the code reactive.

Computed signals recalculate whenever any of their dependent signals change. When a signal is bound in a template, Angular's change detection automatically updates the view when the signal changes, ensuring that the user sees the updated values.

So why do we need signals? Here are a few reasons:
  1. Signals provide more reactivity in our code.
  2. Using signals allows for finer control over change detection, leading to improved performance.

Now, let's go deeper into what signals are and how to use them.

A signal can be thought of as a value with a change notification. It is a special type of variable that holds a value and notifies when the value changes. Metaphorically, a signal can be seen as a box that contains the value and glows when the value changes. To read the value of a signal, we use parentheses: x().


Key characteristics of signals include:
  • A signal is a variable with a change notification.
  • Signals are reactive and referred to as "reactive primitives."
  • Signals always have a value.
  • Signals are synchronous and not a replacement for RxJS and Observables for asynchronous operations.
Signals can be used in various contexts, including components, directives, services, templates, and other parts of the code.

Also, Read:

Happy Coding Happy Learning !!!

Thursday, 8 June 2023

Best ideas from Clean Code by Robert C. Martin - with Typescript examples

"Clean Code" by Robert C. Martin is a highly influential book that has revolutionized the way software developers approach code quality. It offers a collection of principles, techniques, and best practices for writing clean, readable, and maintainable code. In this article, we will explore some of the essential ideas from "Clean Code" and demonstrate their application using practical examples in TypeScript. By incorporating these concepts into your TypeScript projects, you can significantly enhance code quality and developer productivity.

Clean Code by Robert C. Martin

1. Descriptive and Meaningful Naming: One of the fundamental principles of clean code is to use meaningful and descriptive names for variables, functions, classes, and other code entities. Clear and expressive names make code self-explanatory and improve its understandability. 

Let's see an example in TypeScript:

typescript
// Poor naming const a = 5; function calc(x: number, y: number) { // ... } // Improved naming const age = 5; function calculateSum(firstNumber: number, secondNumber: number) { // ... }

2. Focused Functions and Methods: Functions and methods should have a single responsibility and be focused on performing one task well. Following the Single Responsibility Principle (SRP) enhances code readability, testability, and reusability. 

Here's an example:

typescript
// Function with multiple responsibilities function processData(data: any) { // ... // Process data // ... // Update UI // ... } // Separating concerns into multiple functions function processData(data: any) { process(data); updateUI(); }

3. Clear and Concise Comments: Code should be self-explanatory, but when necessary, comments can provide additional context or clarify complex logic. However, avoid excessive comments that add no value and focus on writing expressive code. 

Here's an example:

typescript
// Redundant comment const total = calculateSum(5, 10); // Calculate the sum of two numbers // Self-explanatory code const sum = calculateSum(5, 10);

4. Effective Error Handling: Proper error handling is essential for building robust code. Use try-catch blocks to capture and handle exceptions, and provide meaningful error messages or use custom exception classes. 

Consider the following example:

typescript
// Ignoring errors try { // Code that may throw an error } catch (e) {} // Handling errors appropriately try { // Code that may throw an error } catch (e) { // Handle the error or rethrow it }

5. Thorough Unit Testing: Clean code emphasizes the importance of comprehensive unit testing to ensure code correctness. Write tests that cover various scenarios and edge cases, aiming for high test coverage. This allows you to refactor code with confidence and detect regressions early on. 

Consider the following example:

typescript
// Incomplete or missing unit tests function calculateSum(a: number, b: number): number { return a + b; } // Comprehensive unit tests function calculateSum(a: number, b: number): number { return a + b; } test('calculateSum should return the correct sum', () => { expect(calculateSum(2, 3)).toBe(5); });

Conclusion: 
The concepts presented in "Clean Code" by Robert C. Martin provide invaluable guidance for developers striving to write maintainable and high-quality code. By applying these principles and techniques with practical examples in TypeScript, you can significantly enhance the readability, maintainability, and overall quality of your codebase. Embrace these principles as part of your coding practices to create.

Also, Read:

Seven front-end development trends in 2023-2024

With the increasing prevalence of apps in the digital landscape , the role of front-end developers remains essential. While apps aim to ove...

Popular Posts