Skip to content

Latest commit

 

History

History
64 lines (50 loc) · 1.9 KB

File metadata and controls

64 lines (50 loc) · 1.9 KB
title Comparing Data by Value with Data.struct
id data-struct
skillLevel beginner
applicationPatternId core-concepts
summary Use Data.struct to create immutable, structurally-typed objects that can be compared by value, not by reference.
tags
Data.struct
structural-equality
immutable
data-type
effect
rule
description
Use Data.struct to define objects whose equality is based on their contents, enabling safe and predictable comparisons.
related
data-tuple
data-equal
author PaulJPhilp
lessonOrder 4

Comparing Data by Value with Data.struct

Guideline

Use Data.struct to create immutable, structurally-typed objects whose equality is based on their contents, not their reference.
This enables safe, predictable comparisons and is ideal for domain modeling.

Rationale

JavaScript objects are compared by reference, which can lead to subtle bugs when modeling value objects.
Data.struct ensures that two objects with the same contents are considered equal, supporting value-based logic and collections.

Good Example

import { Data, Equal } from "effect";

// Create two structurally equal objects
const user1 = Data.struct({ id: 1, name: "Alice" });
const user2 = Data.struct({ id: 1, name: "Alice" });

// Compare by value, not reference
const areEqual = Equal.equals(user1, user2); // true

// Use in a HashSet or as keys in a Map
import { HashSet } from "effect";
const set = HashSet.make(user1);
console.log(HashSet.has(set, user2)); // true

Explanation:

  • Data.struct creates immutable objects with value-based equality.
  • Use for domain entities, value objects, and when storing objects in sets or as map keys.
  • Avoids bugs from reference-based comparison.

Anti-Pattern

Using plain JavaScript objects for value-based logic, which compares by reference and can lead to incorrect equality checks and collection behavior.