iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📘

TypeScript Coding Techniques #3: Functions (Part 1)

に公開

Introduction

This is the third installment of the series introducing TypeScript coding techniques.

Although I announced the content in the previous post, it has been almost six months since then. I plan to continue posting at a steady pace again.

The intended readers are those who have some programming experience and want to further improve their code quality. It is probably not for beginners.

In this third installment, I will organize what can be done with functions. Although titled "TypeScript," I believe these concepts apply to almost any programming language, not just TypeScript.

What You Can Do with Functions

Abstraction of Processing

By grouping a series of operations into a function and giving it a name, you can describe processing concisely. This makes the overall flow of the logic easier to follow and improves the maintainability of the source code.

const load = async (): Promise<Data> => {
  // 100 lines of complex logic...
};
const modify = (data: Data, modification: Modification): Data => {
  // 100 lines of complex logic...
};
const save = async (data: Data): Promise<void> => {
  // 100 lines of complex logic...
};

const applyModification = async (modification: Modification): Promise<void> => {
  // Abstracting 300 lines of logic into 3 lines
  const data = await load();
  const modifiedData = modify(data, modification);
  await save(modifiedData);
};

Commonization and Reuse of Processing

You can share logic with other processes and make it reusable. This reduces the amount of code written and decreases maintenance costs.

However, on the flip side, modifying a single function can affect multiple processes. Careful code design is necessary for effective commonization and reuse.

const applyModification = async (modification: Modification): Promise<void> => {
  const data = await load();
  const modifiedData = modify(data, modification);
  await save(modifiedData);
};

const reset = async (): Promise<void> => {
  // Save 100 lines by reusing the `save` function
  await save(defaultData);
};

Scope and Hiding

Variables defined inside a function cannot be referenced from outside that function. The range in which a variable can be referenced is called a scope.

Every function has its own function scope, hiding variables declared within it from the outside.

Since internal variables are hidden, there is no need to worry about name collisions with variables in other function scopes.

const load = async (): Promise<Data> => {
  // The local variable `dataAccess` cannot be referenced from outside
  const dataAccess = await Reader.create();
  // ...
  return result;
};
const modify = (data: Data, modification: Modification): Data => {
  // Intermediate data is stored in variables, but only the result is accessible from the outside
    const intermediateData1 = ...;
    const intermediateData2 = ...;
  // ...
  return result;
};
const save = async (data: Data): Promise<void> => {
  // This has the same name as the variable used in `load()`, but a different role
  const dataAccess = await Writer.create();
  // ...
};

const applyModification = async (modification: Modification): Promise<void> => {
  // `dataAccess` and `intermediateData` cannot be accessed directly (they are hidden)
  const data = await load();
  const modifiedData = modify(data, modification);
  await save(modifiedData);
};

Functions that take functions as arguments

In JavaScript, functions can be treated as variables, object properties, or as arguments and return values of other functions. Such values are called "first-class objects."

By taking a function as an argument, part of the behavior can be freely defined later, allowing for more flexible commonization of processing.

This design is also used in built-in features such as Array.prototype.map() and new Promise().

const difference = <T, U>(
  data: readonly T[],
  other: readonly U[],
  // Any comparison function can be passed to equal
  equal: (l: T, r: U) => boolean
): T[] => {
  return data.filter((l) => !other.some((r) => equal(l, r)));
};

const deletedElements = difference(
  before,
  after,
  // Compare by object properties
  (b, a) => b.id === a.id
);

Functions that return functions (Closures)

Since JavaScript functions are first-class objects, they can be returned as the result of another function.

The returned function can reference variables that exist in the original function's scope. This is called a closure.

In object-oriented programming, this functionality is typically achieved using class methods and private fields, but it can be implemented with functions if they are first-class objects.

const createCounter = (
  initialCount = 0
): {
  readonly increment: () => number;
  readonly decrement: () => number;
  readonly reset: () => number;
  get count(): number;
} => {
  let count = initialCount;
  // count can be referenced and updated via the returned function (closure)
  // Directly overwriting the value of count is prohibited (hidden)
  return {
    increment: () => ++count,
    decrement: () => --count,
    reset: () => (count = initialCount),
    get count(): number {
      return count;
    },
  };
};

const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.increment(); // 3
counter.decrement(); // 2
counter.count; // 2
counter.reset(); // 0

Conclusion

In this installment, I introduced what can be done with functions in JavaScript.

In the next post, to understand functions more deeply, I will introduce the "classification of processing."

Discussion