By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
World of SoftwareWorld of SoftwareWorld of Software
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Search
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
Reading: Refactoring 038: Reifying Collections for Type Safety | HackerNoon
Share
Sign In
Notification Show More
Font ResizerAa
World of SoftwareWorld of Software
Font ResizerAa
  • Software
  • Mobile
  • Computing
  • Gadget
  • Gaming
  • Videos
Search
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Have an existing account? Sign In
Follow US
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
World of Software > Computing > Refactoring 038: Reifying Collections for Type Safety | HackerNoon
Computing

Refactoring 038: Reifying Collections for Type Safety | HackerNoon

News Room
Last updated: 2026/02/16 at 3:03 PM
News Room Published 16 February 2026
Share
Refactoring 038: Reifying Collections for Type Safety | HackerNoon
SHARE

Give your collections a purpose and a connection to the real world

TL;DR: Wrap primitive collections into dedicated objects to ensure type safety and encapsulate business logic.

Problems Addressed in this Article 😔

  • Type safety violations
  • Logic duplication
  • Primitive obsession
  • Weak encapsulation
  • Strong coupling avoiding collection type changes
  • Hidden business rules

Context 💬

You find yourself passing around generic lists, arrays, or dictionaries as if they were just anemic “bags of data.” like DTOs or Data Clumps.

These primitive structures are convenient to iterate.

But they are also anonymous and lack a voice in the business domain.

When you use a raw array to represent a group of specific entities—like ActiveSubscribers, PendingInvoices, or ValidationErrors, you are essentially forcing every part of your system to re-learn how to handle that collection, leading to scattered logic and “primitive obsession.”

When you reify the collection, you improve the model and create technical implementation into a first-class citizen of your domain model.

This doesn’t just provide a home for validation and filtering; it makes the invisible concepts in your business requirements visible in your code.

Steps 👣

  1. Create a new class to represent the specific collection.
  2. Define a private collection property within this class using the appropriate collection type.
  3. Implement a constructor that accepts only elements of the required type.
  4. Add type-hinted methods to add, remove, or retrieve elements.
  5. Move collection-specific logic (like sorting or filtering) from the outside into this new class.

Sample Code 💻

Before 🚨

<?

/** @var User[] $users */
// this is a static declaration used by many IDEs but not the compiler
// Like many comments it is useless, and possible outdated

function notifyUsers(array $users) {
    foreach ($users as $user) {
        // You have no guarantee $user is actually a User object
        // The comment above is 
        // just a hint for the IDE/Static Analysis
        $user->sendNotification();
    }
}

$users = [new User('Anatoli Bugorski'), new Product('Laser')]; 
// This array is anemic and lacks runtime type enforcement
// There's a Product in the collection and will show a fatal error
// unless it can understand #sendNotification() method

notifyUsers($users);

After 👉

<? 

class UserDirectory {
// 1. Create a new class to represent the specific collection
// This is a real world concept reified  
// 2. Define a private property
private array $elements = [];

    // 3. Implement a constructor that accepts only User types
    public function __construct(User ...$users) {
        $this->elements = $users;
    }

    // 4. Add type-hinted methods to add elements
    public function add(User $user): void {
        $this->elements[] = $user;
    }

    // 5. Move collection-specific logic inside
    public function notifyAll(): void {
        foreach ($this->elements as $user) {
            $user->sendNotification();
        }
    }
}

Type 📝

[X] Manual

Safety Considerations 🛡️

This refactoring is very safe.

You create a new structure and gradually migrate references.

Since you add strict type hints in the new class, the compiler engine catches any incompatible data at runtime, preventing silent failures.

Why is the Code Better? ✨

You transform a generic, “dumb” collection into a specialized object that understands its own rules.

You stop repeating validation logic every time you handle the list.

The code becomes self-documenting because the class name explicitly tells you what the collection contains.

How Does it Improve the Bijection? 🗺️

In the real world, a “List of Users” or a “Staff Directory” is a distinct concept with specific behaviors.

An anonymous array is a technical implementation detail, not a real-world entity.

By reifying the collection, you create a one-to-one correspondence between the business concept and your code.

Limitations ⚠️

You might encounter slight performance overhead when dealing with millions of objects compared to raw arrays.

For most business applications, the safety gains far outweigh the millisecond costs and prevents you from being a premature optimizator.

Remember to avoid hollow specialized business collections that don’t exist in the real world.

Many languages support typed collections:

  • C# achieves typed collections through reified generics in the CLR, preserving type information at runtime for types like List.
  • C++ achieves typed collections through templates like blueprints instantiated at compile time for each concrete type.
  • Clojure achieves typed collections through optional static typing libraries such as core.typed.
  • Dart achieves typed collections through reified generics with runtime type checks in sound null safety mode.
  • Elixir achieves typed collections through typespecs analyzed by Dialyzer for static verification.
  • Go achieves typed collections through parametric generics introduced in Go 1.18 with type parameters and constraints.
  • Haskell achieves typed collections through parametric polymorphism and type classes resolved at compile time.
  • Java achieves typed collections through generics with type erasure, enforcing type constraints at compile time on classes like List and Map.
  • JavaScript achieves typed collections through TypeScript or Flow, which add static generic typing on top of the dynamic language (see below).
  • Kotlin achieves typed collections through JVM generics with variance annotations and null-safety integrated into the type system.
  • Objective-C achieves typed collections through lightweight generics that provide compile-time checks without full runtime enforcement.
  • PHP achieves typed collections through docblock-based generics enforced by static analyzers like Psalm or PHPStan.
  • Python achieves typed collections through type hints like list[T] and dict[K, V] checked by static analyzers such as mypy.
  • Ruby achieves typed collections through external type systems like Sorbet or RBS layered on top of the dynamic runtime.
  • Rust achieves typed collections through parametric types and trait bounds checked at compile time with monomorphization.
  • Scala achieves typed collections through a powerful generic type system with variance and higher-kinded types.
  • Swift achieves typed collections through generics with value semantics and protocol constraints.
  • TypeScript achieves typed collections through structural typing and generics enforced at compile time and erased at runtime since JavaScript doesn’t support them.

In all the above cases, reifying a real business object (if exists in the MAPPER) gives you a good extra abstraction layer.

Level 🔋

[X] Intermediate

Related Refactorings 🔄

https://maximilianocontieri.com/refactoring-012-reify-associative-arrays?embedable=true

https://hackernoon.com/refactoring-013-eliminating-repeated-code-with-dry-principles?embedable=true

Refactoring with AI 🤖

Ask your AI assistant to: “Identify where I am passing arrays of objects and suggest a Typed Collection class for them.”

You can also provide the base class and ask: “Find a real business object and generate a boilerplate for a type-safe collection for this entity.”

Related Code Smells 💨

  • How to Find the Stinky Parts of Your Code (Part I)
  • How to Find the Stinky Parts of Your Code [Part XXV]
  • How to Find The Stinky Parts of Your Code [Part XIII]
  • How to Find The Stinky Parts of Your Code (Part VIII)
  • How to Find the Stinky Parts of Your Code [Part XXIX]
  • How to Find the Stinky Parts of Your Code [Part XXVII]

Credits 🙏

Image by Markéta Klimešová on Pixabay

Inspired by the “Collection Object” pattern in clean architecture and the ongoing quest for type safety in dynamic languages.


This article is part of the Refactoring Series.

https://maximilianocontieri.com/how-to-improve-your-code-with-easy-refactorings?embedable=true

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Email Print
Share
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Acer confirms price hikes are coming this week Acer confirms price hikes are coming this week
Next Article ADATA SD820 Review: Take Your Speedy SSD Off-Road ADATA SD820 Review: Take Your Speedy SSD Off-Road
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Stay Connected

248.1k Like
69.1k Follow
134k Pin
54.3k Follow

Latest News

You have under 8 hours to save 40% on the Ring Battery Doorbell
You have under 8 hours to save 40% on the Ring Battery Doorbell
News
Miami Exotic Car Rental Services: Guide to Luxury on the Road
Miami Exotic Car Rental Services: Guide to Luxury on the Road
Gadget
Apple Schedules &apos;Special Experience&apos; in New York, London and Shanghai on March 4
Apple Schedules 'Special Experience' in New York, London and Shanghai on March 4
News
Interview: Richard Corbridge, CIO, Segro | Computer Weekly
Interview: Richard Corbridge, CIO, Segro | Computer Weekly
News

You Might also Like

Idea Raised For Nicer DRM Panic Screen Integration On Fedora Linux
Computing

Idea Raised For Nicer DRM Panic Screen Integration On Fedora Linux

2 Min Read
Trapped in a Miser’s Mansion: Two Brothers Plot Their Escape | HackerNoon
Computing

Trapped in a Miser’s Mansion: Two Brothers Plot Their Escape | HackerNoon

33 Min Read
Lutris 0.5.20 Linux Game Manager Brings New Features, Wine Wayland Option
Computing

Lutris 0.5.20 Linux Game Manager Brings New Features, Wine Wayland Option

1 Min Read
Gold, Pride, and a Locked Door: A Son’s Final Goodbye | HackerNoon
Computing

Gold, Pride, and a Locked Door: A Son’s Final Goodbye | HackerNoon

37 Min Read
//

World of Software is your one-stop website for the latest tech news and updates, follow us now to get the news that matters to you.

Quick Link

  • Privacy Policy
  • Terms of use
  • Advertise
  • Contact

Topics

  • Computing
  • Software
  • Press Release
  • Trending

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

World of SoftwareWorld of Software
Follow US
Copyright © All Rights Reserved. World of Software.
Welcome Back!

Sign in to your account

Lost your password?