📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is the Null Object pattern? Explain how NullLogger, Stream.Null, Array.Empty and Task.CompletedTask apply it in .NET, how it compares with nullable reference types and null checks, and when a null object hides real errors instead of preventing them.

Null Object intent (a do-nothing implementation instead of null), framework examples (NullLogger<T>.Instance, NullLoggerFactory, Stream.Null, TextWriter.Null, Array.Empty<T>, Enumerable.Empty<T>, Task.CompletedTask, CancellationToken.None), returning empty collections, optional dependencies in DI, comparison with nullable reference types and the Maybe/Result approach, and when a null object masks failures.

Junior Theory Beginner dependency-injection design-patterns logging null-object nullable-reference-types

🎯 Key points

  • Null Object: an implementation of an interface that does nothing safely, used instead of null so callers don't need null checks
  • Framework examples: NullLogger<T>.Instance, NullLoggerFactory, Stream.Null, TextWriter.Null, Array.Empty<T>(), Enumerable.Empty<T>(), Task.CompletedTask, CancellationToken.None
  • Return empty collections, not null: callers can foreach and Count without checks; Array.Empty<T>() is a cached instance, no allocation
  • Null objects are usually stateless singletons (a static Instance), so they cost nothing to share
  • Nullable reference types make 'might be null' visible at compile time; Null Object removes null where 'do nothing' is genuinely correct behaviour
  • Use it for optional collaborators (logging, metrics, notifications in development) registered in DI
  • It hides errors when 'doing nothing' is wrong: a NullLogger left in production, a no-op payment gateway, an empty list returned when the database call failed
  • If absence needs handling, make it explicit: nullable return, TryGet pattern, or a Result type

⏱ 30-second answer

Null Object replaces null with an object that implements the same interface and does nothing safely, so callers don't need null checks.

.NET uses it widely: NullLogger<T>.Instance, Stream.Null, TextWriter.Null, Array.Empty<T>(), Enumerable.Empty<T>(), Task.CompletedTask and CancellationToken.None. Returning an empty collection instead of null is the everyday form.

Nullable reference types solve a different problem: they make "this might be null" visible at compile time so you handle it. Null Object is for when "do nothing" is genuinely the correct behaviour, like an optional logger.

The danger is when doing nothing is wrong: a NullLogger left in production, or an empty list returned because the database call failed. Then the null object hides an error instead of preventing one.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Null Object is a simple idea: instead of passing or returning null and making every caller check for it, you pass an object that implements the same interface and does nothing. If a class takes an ILogger and the caller doesn't care about logs, you give it NullLogger<T>.Instance. Every Log call is a no-op, and the class never needs if (_logger != null). The object is stateless, so one shared static instance is enough.

.NET is full of these. NullLogger and NullLoggerFactory are what I use in unit tests. Stream.Null and TextWriter.Null swallow writes and return nothing on reads. Array.Empty<T>() and Enumerable.Empty<T>() are the null objects of collections: a method that returns 'no orders' should return an empty list, not null, so callers can just foreach. Task.CompletedTask is the null object for 'async work that has nothing to do', and CancellationToken.None is a token that never cancels. In application code I use it for optional collaborators: in local development I register a NullEmailSender so the app runs without SMTP.

How it relates to nullable reference types: they're complementary. Nullable reference types make 'this might be missing' explicit, so the compiler forces me to handle it. Null Object is for cases where 'missing' should behave exactly like 'present but doing nothing'. The mistake I see is using it where doing nothing is wrong. A NullLogger that ends up registered in production means you have no logs during an incident. A repository that catches an exception and returns an empty list tells the UI there are no orders when the database is actually down. A null object is right when doing nothing is a correct answer; when absence is a problem, make it visible instead."


Framework null objects

Null object Replaces Behaviour
NullLogger<T>.Instance, NullLoggerFactory.Instance A real logger Ignores all log calls; IsEnabled returns false
Stream.Null A real stream Writes discarded, reads return 0 bytes
TextWriter.Null, TextReader.Null Console or file writers Discards output, reads nothing
Array.Empty<T>(), Enumerable.Empty<T>() null collections Empty, cached, no allocation
Task.CompletedTask, ValueTask default A pending task Already completed
CancellationToken.None A real token Never cancels

Null Object vs alternatives

Approach Use when Example
Null Object Doing nothing is correct Optional logger, metrics, notifications in dev
Empty collection "None" is a valid result GetOrders() returns []
Nullable return (T?) with NRT Absence must be handled by the caller FindCustomer(id) returns Customer?
TryGet pattern Absence is common and cheap to check TryGetValue(key, out var value)
Exception / Result Absence or failure is an error Database unavailable, payment declined

Production example

A notification service registered NullSmsSender when the SMS configuration section was missing, intended for local development. A configuration typo in production meant two-factor codes weren't sent for about 40 minutes, with no errors logged. The fix kept the null object for development only, made production fail at start-up with ValidateOnStart if SMS settings were missing, and added a counter for messages dropped by any null sender.

πŸ” What the interviewer is checking

Checks that the candidate recognises Null Object in .NET, can use it for optional collaborators and empty results, and knows when it masks failures.

Green flags

  • Names several framework null objects.
  • Prefers empty collections over null returns.
  • Distinguishes Null Object from nullable reference types.
  • Gives a clear example of a null object hiding an error.

Red flags

  • Returns fake objects from lookups to avoid null checks.
  • Catches exceptions and returns empty results.
  • Uses null objects for payments or security features.

πŸ“š Learn in depth

1. Structure

Client ──▢ Β«interfaceΒ» INotificationSender
                SendAsync(message)
               β–²                    β–²
      SmtpNotificationSender   NullNotificationSender
      (real work)              (does nothing, returns completed task)

The client never branches on null. Which implementation it gets is decided once, in DI configuration.

2. Why null is the problem it solves

Every null that can flow into a method creates a branch the caller must remember. Missing one gives a NullReferenceException far from where the null came from. A null object removes the branch entirely when the "nothing" case has well-defined behaviour.

3. Collections are the most common case

Framework Design Guidelines say methods returning collections should return empty collections, never null. Array.Empty<T>() returns a cached zero-length array per T, so returning it allocates nothing. In C# 12+, a collection expression [] targeting an array or IEnumerable<T> uses the same cached empty instance where possible.

4. Null objects and nullable reference types

With <Nullable>enable</Nullable>, a parameter typed ILogger (not ILogger?) tells callers they must pass something. Null Object gives them something sensible to pass. Conversely, a return type Customer? tells callers to handle absence; you should not return a fake "null customer" there, because then callers can't tell "found" from "not found", and a fake customer with default values can flow into pricing or emails.

5. Null objects in DI

  • Optional features: register NullEmailSender in development and SmtpEmailSender elsewhere, chosen by environment, not by "is the config present" (which turns typos into silent outages).
  • Library design: accept ILogger<T>? logger = null and fall back to NullLogger<T>.Instance so consumers aren't forced to supply logging.
  • Tests: NullLogger<T>.Instance instead of mocking ILogger.

6. When it hides errors

Null Object is dangerous when the "nothing" behaviour is indistinguishable from success and success matters: security codes, payments, audit logs, data reads. If you use one, make its use observable (log once at start-up which implementation was chosen, count dropped calls) and never select it silently in production.

Try it yourself

  1. Replace ILogger null checks in a class with NullLogger<T>.Instance and delete the branches.
  2. Change a method that returns null for "no results" to return Array.Empty<T>(); check allocations with BenchmarkDotNet.
  3. Register NullEmailSender only when builder.Environment.IsDevelopment() and add ValidateOnStart for SMTP options otherwise.
  4. Write a repository method that swallows a SqlException and returns an empty list; discuss with a colleague what the UI would show during an outage.

πŸ’» Code

A null object for an optional dependency, registered by environment, and empty collections instead of null.

namespace Notifications;

public sealed record Notification(string To, string Subject, string Body);

public interface INotificationSender
{
    Task SendAsync(Notification notification, CancellationToken ct);
}

public sealed class SmtpNotificationSender(ILogger<SmtpNotificationSender> logger) : INotificationSender
{
    public async Task SendAsync(Notification n, CancellationToken ct)
    {
        // ... real SMTP call ...
        await Task.Delay(10, ct);
        logger.LogInformation("Sent {Subject} to {To}", n.Subject, n.To);
    }
}

// Null Object: same interface, safely does nothing. Stateless, so one shared instance.
public sealed class NullNotificationSender : INotificationSender
{
    public static NullNotificationSender Instance { get; } = new();
    private NullNotificationSender() { }
    public Task SendAsync(Notification notification, CancellationToken ct) => Task.CompletedTask;
}

// Callers never check for null
public sealed class SignupService(INotificationSender sender, ILogger<SignupService>? logger = null)
{
    private readonly ILogger _logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger<SignupService>.Instance;

    public async Task RegisterAsync(string email, CancellationToken ct)
    {
        _logger.LogInformation("Registering {Email}", email);
        await sender.SendAsync(new Notification(email, "Welcome", "Thanks for signing up"), ct);
    }
}
// Program.cs: choose the null object by environment, never by "config is missing"
if (builder.Environment.IsDevelopment())
{
    builder.Services.AddSingleton<INotificationSender>(NullNotificationSender.Instance);
}
else
{
    builder.Services.AddOptions<SmtpOptions>()
        .Bind(builder.Configuration.GetSection("Smtp"))
        .ValidateDataAnnotations()
        .ValidateOnStart();                         // a typo fails the deployment, not 2FA codes
    builder.Services.AddSingleton<INotificationSender, SmtpNotificationSender>();
}

public sealed class SmtpOptions
{
    [System.ComponentModel.DataAnnotations.Required] public string Host { get; set; } = "";
}
namespace Orders;

public sealed record OrderSummary(Guid Id, decimal Total);

public sealed class OrderQueries(OrdersDbContext db)
{
    // Empty collection, never null: callers can foreach and Count safely
    public async Task<IReadOnlyList<OrderSummary>> RecentAsync(Guid customerId, CancellationToken ct)
    {
        var orders = await db.Orders
            .Where(o => o.CustomerId == customerId)
            .OrderByDescending(o => o.PlacedAt)
            .Take(10)
            .Select(o => new OrderSummary(o.Id, o.Total))
            .ToListAsync(ct);
        return orders;                              // [] when there are none
    }

    // Absence that must be handled: nullable return, not a fake "null order"
    public Task<OrderSummary?> FindAsync(Guid id, CancellationToken ct) =>
        db.Orders.Where(o => o.Id == id).Select(o => new OrderSummary(o.Id, o.Total)).SingleOrDefaultAsync(ct);

    // DON'T: hiding a failure behind an empty result
    // catch (SqlException) { return Array.Empty<OrderSummary>(); }   // UI shows "no orders" during an outage
}

// Tests use the framework's null object instead of mocking ILogger
// var service = new SignupService(NullNotificationSender.Instance, NullLogger<SignupService>.Instance);

⚠ Common mistakes

  • Mistake: Returning null from methods that return collections. Why it is wrong: Every caller must null-check, and one that forgets throws NullReferenceException. Instead: Return an empty collection ([], Array.Empty<T>()).
  • Mistake: Selecting a null object automatically when configuration is missing. Why it is wrong: A typo in production silently disables the feature. Instead: Choose by environment and use ValidateOnStart to fail fast elsewhere.
  • Mistake: Catching an exception and returning an empty list or a null object. Why it is wrong: Callers can't distinguish "nothing found" from "the database is down". Instead: Let the exception propagate or return an explicit failure result.
  • Mistake: Returning a fake "null customer" with default values from a lookup. Why it is wrong: It can flow into pricing, emails or reports as if it were real. Instead: Return Customer? and let nullable reference types force handling.
  • Mistake: Using a null object for critical side effects (payments, audit logs, security codes). Why it is wrong: Doing nothing looks like success. Instead: Require a real implementation, and fail loudly if it's missing.
  • Mistake: Creating a new null object instance per use. Why it is wrong: Wasted allocations for a stateless object. Instead: Expose a static Instance.
  • Mistake: Mocking ILogger in every test just to satisfy the constructor. Why it is wrong: Noise and brittle setups. Instead: NullLogger<T>.Instance, unless the test asserts on logging.

πŸ› Senior insight: trade-offs

I treat Null Object as a statement: "for this collaborator, doing nothing is a correct outcome". That's true for logging in tests, optional telemetry, and empty results. It's false for anything where the absence of an effect is a failure, and there I want nullable types, exceptions or results that make the absence visible.

Option When it fits Cost When not to
Null Object Optional collaborators; no-op is correct Can hide misconfiguration Critical side effects
Empty collection "None" is a valid result None Failures disguised as empty
Nullable return + NRT Caller must handle absence Null checks at call sites When absence is never meaningful
TryGet pattern Hot paths, frequent misses Out parameters Async methods
Result type / exception Absence or failure is an error More ceremony Expected empty results

If a null object is ever selected outside development, I make it observable: log which implementation was registered at start-up and count calls it dropped.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate compares Null Object with nullable reference types Why: Checks enabling nullable reference types in a real codebase
    How to answer

    <Nullable>enable</Nullable> makes reference types non-nullable by default: string? means a value can be null and string means it can't. The compiler then warns when code might dereference null. It's purely compile-time, so nothing changes at run time. In a big codebase I migrate bottom-up: shared libraries and domain types first, because their annotations flow out to everyone else. I go project by project, or file by file with #nullable enable, and give each step a small pull request so feature work carries on. When a project is clean I make its nullable warnings errors with WarningsAsErrors=nullable, so it can't slip back. I use attributes such as [NotNullWhen] where flow analysis needs help and keep ! for real boundaries. I also watch for two things: EF Core migrations, where nullability decides whether columns are required, and public APIs, where annotations are part of the contract.

  2. When: Candidate registers different implementations of one interface by environment Why: Checks the Strategy pattern, of which a null object is a do-nothing variant
    How to answer

    Strategy puts each variant of an algorithm behind one interface, so the code that uses it (the context) calls whichever implementation it was given instead of branching on a mode. A switch that grows with every new discount, carrier or export format becomes a set of small classes, and adding a variant means adding a class, not editing the switch (Open/Closed).

    .NET uses it everywhere: IComparer<T> in List<T>.Sort, IEqualityComparer<T> in Dictionary, StringComparer.OrdinalIgnoreCase, JsonNamingPolicy.

    • In DI, register several implementations and inject IEnumerable<IStrategy>, or use keyed services (.NET 8+), to pick one by key.
    • For one small function with no dependencies, a Func<T, TResult> delegate is a strategy without the ceremony.

    The trade-off: more types and indirection, so a short, stable switch is often clearer.

  3. When: Candidate suggests a no-op Action as an alternative Why: Checks delegates as lightweight no-op callbacks
    How to answer

    Func is a delegate that returns a value, so Func<int, string> takes an int and returns a string. Action returns void, and Predicate<T> is a delegate that takes a T and returns bool. Older APIs like List<T>.FindAll use it, while LINQ uses Func<T, bool>. Even with identical signatures they are different delegate types, so you cannot pass a Func<T, bool> variable as a Predicate<T> without wrapping it. A lambda converts to either. I declare my own delegate only when I need ref or out parameters or a meaningful name.

↩ Usually asked after

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me