Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions _rules/1125.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,4 @@ rule_category: member-design
title: Don't expose stateful objects through static members
severity: 2
---
A stateful object is an object that contains many properties and lots of behavior behind it. If you expose such an object through a static property or method of some other object, it will be very difficult to refactor or unit test a class that relies on such a stateful object. In general, introducing a construct like that is a great example of violating many of the guidelines of this chapter.

A classic example of this is the `HttpContext.Current` property, part of ASP.NET. Many see the `HttpContext` class as a source of a lot of ugly code.
A classic example of this is the `HttpContext.Current` property, part of classic ASP.NET. Many see this as a source of a lot of ugly code, because it hides an implicit dependency on a global state object. Instead, make dependencies explicit by injecting them through a constructor or method parameter.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need to refer to classic ASP.NET; there are plenty of cases in modern .NET that are still a pain when writing tests:

  • System.Environment.MachineName
  • System.Environment.GetEnvironmentVariable (can't run tests in parallel that depend on it)
  • System.DateTime.UtcNow
  • System.IO.Path.Combine (depends on OS-level directory separator)
  • System.IO.Path.GetInvalidFileNameChars
  • System.IO.File.Exists

The rule title could be changed to:
Don't expose global state through static members