DEV Community

Cover image for The 48-Hour Technical Take-Home Test: Avoiding the Singleton Trap Without Over-Engineering
Toàn Lương Bảo
Toàn Lương Bảo

Posted on Originally published at toanlb.dev on

The 48-Hour Technical Take-Home Test: Avoiding the Singleton Trap Without Over-Engineering

The 48-Hour Technical Take-Home Test: Avoiding the Singleton Trap Without Over-Engineering

When assigned a 48-hour technical take-home assessment requiring an Aquarium Simulator demo, candidates are faced with two core challenges: allowing players to purchase fish using local currency and ensuring a flock of hundreds of fish swims smoothly at 60 FPS without frame drops. Under extreme time constraints, a pragmatic developer's natural reflex is to prioritize visual execution: writing a static CurrencyManager.Instance Singleton to quickly access data from anywhere, reserving the remaining hours to tune C# Job System, Burst Compiler, and Object Pooling.

This exact trade-off was highlighted by reader @anh của mits under our analysis video on Singleton architecture and technical game assessments:

"During a game take-home test requiring an aquarium simulator, I used a Singleton for local currency data and got rejected. Besides Singleton, Dependency Injection is the obvious path, but for a 2-day demo, would implementing Zenject overcomplicate things? They didn't say. For a 2-day aquarium demo (buying fish, smooth swimming without lag), I opted for a Singleton and spent the remaining time optimizing Jobs. After asking why I failed, they sent a public Git repository. Basically, for large-scale projects, Singletons introduce major architectural issues."

It is easy to understand the frustration behind this outcome. Spending two sleepless nights delivering a silky-smooth demo only to be rejected over a few lines of currency management code feels demoralizing. Were the reviewers being overly pedantic, or was introducing a massive third-party DI framework like Zenject really the only acceptable route? Let us examine the reviewer's perspective, identify the hidden architectural flaws, and discover a pragmatic middle ground using Pure C# Dependency Injection that requires zero third-party dependencies while remaining 100% testable.


1. The Reviewer's Perspective: Why Static Singletons Get Flagged

In a timed technical assessment, reviewers do not merely check whether features function on screen. Anyone can drag components onto an Inspector and bridge state using global static variables. The primary objective of the test is to evaluate how candidates structure code when a project scales in a collaborative production environment.

Consider an aquarium shop interface component named FishShop responsible for handling player purchase interactions. If this component couples directly to a global Singleton:

flowchart LR
    subgraph AntiPattern["Coupled Approach"]
        direction TB
        A["FishShop Component"] -->|"Calls static instance"| B["CurrencyManager.Instance"]
        B -->|"Direct disk access"| C["PlayerPrefs / Local Storage"]
    end
    subgraph ReviewerPain["Reviewer Assessment Flags"]
        direction TB
        D["Hidden Dependency"] --> E["Eliminates Automated Unit Testing"]
        E --> F["State Mutation & SRP Violations"]
    end
    AntiPattern -.->|"Reviewer Detects"| ReviewerPain

When reviewers inspect the shop logic and see the following pattern:

// Convenient initial approach that leads to test rejection
public class CurrencyManager : MonoBehaviour
{
    public static CurrencyManager Instance { get; private set; }
    public int CurrentGold { get; set; }
    public void DeductGold(int amount) => CurrentGold -= amount;
}

public class FishShop : MonoBehaviour
{
    private void SpawnFish() => Debug.Log("Fish spawned");

    public void BuyGuppyFish()
    {
        if (CurrencyManager.Instance != null && CurrencyManager.Instance.CurrentGold >= 50)
        {
            CurrencyManager.Instance.DeductGold(50);
            SpawnFish();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Three critical architectural issues immediately surface:

  1. Hidden Dependency: Looking at the FishShop class signature, constructors, or serialized fields, reviewers cannot determine what external services it requires. The dependency on CurrencyManager is concealed inside method bodies. Reusing FishShop in another scene or mini-game without CurrencyManager causes an immediate NullReferenceException.
  2. Untestable Business Logic: This is the primary reason candidates fail. Verifying whether fish purchasing behaves properly when balance is exactly 50, greater than 50, or under 50 requires entering Unity Play Mode, instantiating GameObjects, and clicking buttons. Reviewers cannot run automated NUnit tests in milliseconds to verify edge cases.
  3. Violating the Single Responsibility Principle: A MonoBehaviour Singleton often manages in-memory state, disk serialization, and scene persistence across scene loads simultaneously. When a single class shoulders multiple responsibilities, any change to persistence risks breaking transactional purchase logic.

2. The Over-Engineering Trap: Should You Pull in Zenject for a 48-Hour Demo?

Upon learning that Singletons are an architectural anti-pattern, developers frequently swing to the opposite extreme: installing third-party DI containers such as Zenject or Extenject into a 48-hour prototype.

However, this introduces another pitfall: Over-engineering.

  • Disproportionate Setup Overhead: Candidates spend valuable hours creating SceneContext, ProjectContext, authoring MonoInstaller classes, and writing container bindings.
  • Bloating Minimal Projects: Introducing thousands of lines of external framework code into a two-feature prototype violates the YAGNI principle (You Aren't Gonna Need It). Experienced leads often interpret this as dogmatic over-tooling rather than pragmatic problem solving.
  • Runtime Binding Failures: Container configuration errors in reflection-based systems only manifest at runtime during scene initialization, consuming debugging time that should be spent refining gameplay and simulation loops.

The optimal solution lies in Just-Enough Architecture: Pure C# Dependency Injection combined with a minimal Composition Root.


3. Pragmatic Solution: Pure C# Dependency Injection & Decoupling

In the aquarium simulator, we separate the system into three decoupled layers:

  1. Domain & Business Logic: Manages balances and spending rules as a pure C# class, completely independent of MonoBehaviour and UnityEngine.
  2. Presentation & Coordination: Handles purchase triggers, validates balances through an interface, and signals fish creation.
  3. Simulation Layer: Executes smooth fish movement using Object Pooling or the C# Job System.

Before inspecting the implementation, let us review the custom types designed for this architecture:

  • Interface ICurrencyWallet: An abstract contract representing player funds.
  • Interface ICurrencyStorage: An abstract contract for persisting currency locally.
  • Class CurrencyWallet: A pure C# wallet implementation preventing negative balances and firing balance change events.
  • Class FishShopPresenter: A presenter coordinating transactions via Constructor Injection.
  • Class AquariumCompositionRoot: A single MonoBehaviour responsible solely for instantiating services and wiring dependencies during startup.
  • Class FishSpawner: A simulation component handling fish entity pooling and movement.
flowchart LR
    subgraph CompositionRoot["AquariumCompositionRoot"]
        direction TB
        CR_Awake["1. Awake() Initialization"] --> CR_Wallet["2. new CurrencyWallet(gold)"]
        CR_Wallet --> CR_Shop["3. new FishShopPresenter(wallet)"]
    end

    subgraph Domain["Pure C# Domain Layer"]
        direction TB
        Interface["ICurrencyWallet (Interface)"]
        Wallet["CurrencyWallet (Pure C#)"]
        Storage["ICurrencyStorage (Persistence)"]
        Wallet -.->|"Implements"| Interface
    end

    subgraph Presentation["Presentation & Simulation Layer"]
        direction TB
        Shop["FishShopPresenter (Purchase Logic)"]
        Spawner["FishSpawner (Simulation / Pooling)"]
    end

    CR_Wallet ==>|"Instantiates"| Wallet
    CR_Shop ==>|"Injects Interface"| Shop
    Shop -->|"Verify & Spend"| Interface
    Shop -->|"Trigger Spawn"| Spawner

Implementing Local Persistence and Pure C# Constructor Injection

In our aquarium game, players start with an initial balance. When purchasing a fish, the system ensures valid deductions, produces zero GC allocations during updates, and persists balances without relying on static globals:

using System;

// 1. Separate Persistence: Contract for local save/load
public interface ICurrencyStorage
{
    int LoadBalance(int defaultBalance);
    void SaveBalance(int balance);
}

// 2. Abstract contract for in-memory wallet operations
public interface ICurrencyWallet
{
    int Balance { get; }
    bool TrySpend(int amount);
    void Add(int amount);
    event Action<int> OnBalanceChanged;
}

// Pure C# business logic - No MonoBehaviour, receives Storage via Constructor
public class CurrencyWallet : ICurrencyWallet
{
    private readonly ICurrencyStorage _storage;
    public int Balance { get; private set; }
    public event Action<int> OnBalanceChanged;

    public CurrencyWallet(int defaultBalance, ICurrencyStorage storage = null)
    {
        _storage = storage;
        int initialAmount = _storage != null ? _storage.LoadBalance(defaultBalance) : defaultBalance;
        Balance = Math.Max(0, initialAmount);
    }

    public void Add(int amount)
    {
        if (amount <= 0) return;
        Balance += amount;
        _storage?.SaveBalance(Balance);
        OnBalanceChanged?.Invoke(Balance);
    }

    public bool TrySpend(int amount)
    {
        if (amount <= 0 || Balance < amount)
        {
            return false;
        }

        Balance -= amount;
        _storage?.SaveBalance(Balance);
        OnBalanceChanged?.Invoke(Balance);
        return true;
    }
}

// Purchase logic receives ICurrencyWallet via Constructor Injection
public class FishShopPresenter
{
    private readonly ICurrencyWallet _wallet;
    private readonly Action<string> _onFishSpawned;

    public FishShopPresenter(ICurrencyWallet wallet, Action<string> onFishSpawned)
    {
        _wallet = wallet ?? throw new ArgumentNullException(nameof(wallet));
        _onFishSpawned = onFishSpawned;
    }

    public bool TryPurchaseFish(string fishId, int cost)
    {
        if (string.IsNullOrEmpty(fishId) || cost <= 0)
        {
            return false;
        }

        if (!_wallet.TrySpend(cost))
        {
            return false;
        }

        // Trigger fish instantiation only after verified deduction
        _onFishSpawned?.Invoke(fishId);
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Composition Root: The Single Scene Wiring Point

Instead of pulling in DI containers, a single MonoBehaviour script serves as the scene's Composition Root:

using UnityEngine;

// Basic PlayerPrefs implementation for local storage
public class PlayerPrefsCurrencyStorage : ICurrencyStorage
{
    private const string PrefKey = "PLAYER_GOLD_DATA";

    public int LoadBalance(int defaultBalance) => PlayerPrefs.GetInt(PrefKey, defaultBalance);
    public void SaveBalance(int balance) => PlayerPrefs.SetInt(PrefKey, balance);
}

// Component coordinating fish simulation
public class FishSpawner : MonoBehaviour
{
    public void SpawnFish(string fishId)
    {
        // Spawns entity into the tank using an object pool
        Debug.Log($"FishSpawner: Spawned fish {fishId} into aquarium.");
    }
}

// Single scene wiring point - Zero third-party frameworks needed
public class AquariumCompositionRoot : MonoBehaviour
{
    [SerializeField] private int _startingGold = 100;
    [SerializeField] private FishSpawner _spawner;

    private ICurrencyWallet _wallet;
    private FishShopPresenter _shopPresenter;

    private void Awake()
    {
        // 1. Instantiate Storage and Pure C# Domain Wallet
        var storage = new PlayerPrefsCurrencyStorage();
        _wallet = new CurrencyWallet(_startingGold, storage);

        // 2. Wire dependencies into the presenter via constructor
        _shopPresenter = new FishShopPresenter(_wallet, OnFishSpawnedCallback);

        Debug.Log($"Aquarium initialized with balance: {_wallet.Balance}");
    }

    private void OnFishSpawnedCallback(string fishId)
    {
        if (_spawner != null)
        {
            _spawner.SpawnFish(fishId);
        }
    }

    // Clean API entry point for UI buttons
    public void OnBuyGuppyClicked()
    {
        _shopPresenter.TryPurchaseFish("guppy_fish", 30);
    }
}
Enter fullscreen mode Exit fullscreen mode

Practical Notes: Thread-Safety and Event Lifecycle Management

When deploying this architecture in real-world games, two critical production constraints must be observed:

  1. Thread-Safety Constraints with C# Job System:

    If the fish simulation runs inside worker threads via the C# Job System, never invoke CurrencyWallet.Add() directly from inside an IJob. Invoking methods from background threads causes data races on the Balance state. More critically, invoking OnBalanceChanged?.Invoke() from a worker thread triggers UI updates that crash Unity Engine, as UGUI APIs are strictly restricted to the Main Thread.

    Production Pattern: Worker threads append reward events into a thread-safe NativeQueue<int>. Once jobs finish on the Main Thread (jobHandle.Complete()), the game loop drains the queue and safely invokes _wallet.Add().

  2. Event Unsubscription to Prevent Memory Leaks:

    Any UI view that subscribes to _wallet.OnBalanceChanged += UpdateDisplay; must unsubscribe (_wallet.OnBalanceChanged -= UpdateDisplay;) inside OnDisable() or OnDestroy(). Omitting this creates strong references in multicast delegates that prevent garbage collection when scenes reload, leading to zombie object memory leaks.


Verification: Fast, Isolated Unit Testing Without Play Mode

The decisive advantage of Dependency Injection over global Singletons is testability.

Below is a complete NUnit test suite verifying both layers:

  1. Direct testing of CurrencyWallet (validating arithmetic and event notifications).
  2. Direct testing of FishShopPresenter with a clean mock stub (avoiding duplicated production logic).
using NUnit.Framework;

[TestFixture]
public class AquariumDomainUnitTests
{
    // -------------------------------------------------------------
    // LAYER 1: DIRECT DOMAIN WALLET TESTS
    // -------------------------------------------------------------
    [Test]
    public void CurrencyWallet_NegativeInitialBalance_ClampsToZero()
    {
        var wallet = new CurrencyWallet(-100);
        Assert.AreEqual(0, wallet.Balance);
    }

    [Test]
    public void CurrencyWallet_AddPositiveAmount_IncreasesBalanceAndFiresEvent()
    {
        var wallet = new CurrencyWallet(50);
        int eventValue = -1;
        wallet.OnBalanceChanged += val => eventValue = val;

        wallet.Add(30);

        Assert.AreEqual(80, wallet.Balance);
        Assert.AreEqual(80, eventValue);
    }

    [Test]
    public void CurrencyWallet_TrySpend_SufficientFunds_DeductsAndReturnsTrue()
    {
        var wallet = new CurrencyWallet(100);
        int eventValue = -1;
        wallet.OnBalanceChanged += val => eventValue = val;

        bool success = wallet.TrySpend(40);

        Assert.IsTrue(success);
        Assert.AreEqual(60, wallet.Balance);
        Assert.AreEqual(60, eventValue);
    }

    [Test]
    public void CurrencyWallet_TrySpend_InsufficientFunds_FailsAndBalanceUnchanged()
    {
        var wallet = new CurrencyWallet(20);
        bool success = wallet.TrySpend(50);

        Assert.IsFalse(success);
        Assert.AreEqual(20, wallet.Balance);
    }

    // -------------------------------------------------------------
    // LAYER 2: PRESENTER TESTS WITH CLEAN STUB
    // -------------------------------------------------------------
    private class StubWallet : ICurrencyWallet
    {
        public int Balance { get; set; } = 100;
        public bool SpendReturnValue { get; set; } = true;
        public int LastSpendAmountRequested { get; private set; }
        public event System.Action<int> OnBalanceChanged;

        public bool TrySpend(int amount)
        {
            LastSpendAmountRequested = amount;
            return SpendReturnValue;
        }

        public void Add(int amount) => Balance += amount;
    }

    [Test]
    public void PurchaseFish_WhenWalletAllows_InvokesSpawnCallbackAndReturnsTrue()
    {
        var stubWallet = new StubWallet { SpendReturnValue = true };
        string spawnedFishId = null;
        var presenter = new FishShopPresenter(stubWallet, id => spawnedFishId = id);

        bool success = presenter.TryPurchaseFish("guppy_01", 40);

        Assert.IsTrue(success);
        Assert.AreEqual(40, stubWallet.LastSpendAmountRequested);
        Assert.AreEqual("guppy_01", spawnedFishId);
    }

    [Test]
    public void PurchaseFish_WhenWalletRejects_DoesNotSpawnAndReturnsFalse()
    {
        var stubWallet = new StubWallet { SpendReturnValue = false };
        string spawnedFishId = null;
        var presenter = new FishShopPresenter(stubWallet, id => spawnedFishId = id);

        bool success = presenter.TryPurchaseFish("guppy_01", 50);

        Assert.IsFalse(success);
        Assert.IsNull(spawnedFishId);
    }

    [Test]
    public void PurchaseFish_InvalidInput_ReturnsFalseImmediately()
    {
        var stubWallet = new StubWallet { SpendReturnValue = true };
        var presenter = new FishShopPresenter(stubWallet, null);

        Assert.IsFalse(presenter.TryPurchaseFish(null, 50));
        Assert.IsFalse(presenter.TryPurchaseFish("", 50));
        Assert.IsFalse(presenter.TryPurchaseFish("guppy_01", 0));
        Assert.IsFalse(presenter.TryPurchaseFish("guppy_01", -10));
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Architectural Trade-offs: Comparing Dependency Management Strategies

No architectural pattern is universally superior. The choice depends on project scale, delivery deadlines, and testability requirements:

Comparison Metric Static Singleton (Instance) Reflection DI (Zenject / Extenject) Zero-Reflection DI (VContainer) Pure C# Dependency Injection ScriptableObject Architecture
Setup Speed (48h) Immediate, accessible anywhere Slow, requires Context & Installer setup Faster than Zenject, pure C# bindings Fast, requires only an Interface & Constructor Fast, configure assets via Editor
External Dependency 0% (Standard Unity API) High (Heavy package, heavy reflection) Moderate (Optimized package for IL2CPP) 0% (Standard C# language features) 0% (Built-in Unity Engine)
Automated Unit Testing Fragile, requires Unity Play Mode Straightforward via container mocks Straightforward via container mocks Clean, runs in milliseconds via NUnit Clean in EditMode with CreateInstance<T>()
Coupling Level Tight global coupling Loose coupling via interfaces Loose coupling via interfaces Loose coupling via constructor Decoupled via ScriptableObject channels
Scalability in Large Codebases Poor (High risk of race conditions) Good for large scale, but slower builds Excellent, optimized for mobile & IL2CPP Prone to Constructor Hell if services > 20 Strong for data, needs strict asset governance
Suitability for 48h Tests Poor (High risk of architectural rejection) Low (Often flagged as over-engineering) Viable (If already proficient with it) Optimal (Clean, lean, testable) Strong (Demonstrates native Unity depth)

5. Summary and Key Takeaways for Technical Take-Home Tests

Reflecting on reader @anh của mits's experience with the aquarium simulator assessment, three key lessons emerge:

  1. Understand What Reviewers Evaluate: A smooth 60 FPS demo is the baseline requirement; clean, decoupled, and testable code is what earns recommendation. Reviewers look for evidence that a developer can contribute to multi-developer codebases without accumulating technical debt.
  2. Avoid the False Dichotomy: Rejecting Singletons does not obligate you to adopt heavy DI frameworks. Pure C# Dependency Injection paired with a single Composition Root adds barely 20 lines of code while completely decoupling systems.
  3. Include Unit Tests: Rather than submitting only a build or a .unitypackage, include a dedicated test folder with automated NUnit tests covering core business rules. This demonstrates professional engineering habits that set your submission apart.

The complete source code for this Aquarium Simulator demo with automated NUnit EditMode tests is available on GitHub: github.com/toan-lb/unity-aquarium-demo. You can clone and inspect it directly in Unity 6 or Unity 2022 LTS.

Top comments (0)