Skip to content

Commit 4665e9f

Browse files
authored
Update AV1125: Don't expose stateful objects through static members (#353)
1 parent dbcf0c2 commit 4665e9f

1 file changed

Lines changed: 5 additions & 3 deletions

File tree

_rules/1125.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
---
22
rule_id: 1125
33
rule_category: member-design
4-
title: Don't expose stateful objects through static members
4+
title: Don't hide dependencies behind static members
55
severity: 2
66
---
7-
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.
7+
A well-known example is `HttpContext.Current` from classic ASP.NET. But modern .NET still has plenty of cases where static members expose global or environment-dependent state, such as `Environment.MachineName`, `DateTime.UtcNow`, `Environment.GetEnvironmentVariable`, and `File.Exists`. These are problematic because:
8+
- They hide implicit dependencies, making code harder to understand.
9+
- They make unit testing difficult, especially running tests in parallel.
810

9-
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.
11+
Instead, make dependencies explicit by injecting them through a constructor or method parameter, or by injecting an abstraction (e.g., `TimeProvider` instead of calling `DateTime.UtcNow` directly).

0 commit comments

Comments
 (0)