Skip to content

banned_usage

v1.0.0WarningConfigurableArchitecture

Flags uses of a member you ban — one method, getter or constructor of a type rather than the whole type. The common need is DateTime.now() and Random() in code that should take an injected clock or seed.

DateTime.now() is a hidden input: a type that calls it cannot be tested at a chosen moment. Banning it inside the domain layer while leaving it available in the composition root puts the constraint where it belongs — the code that decides when may know the time; the code that decides what may not.

This rule is in no preset and reports nothing until you add banned:. Every example below shows the configuration that produces it.

analysis_options.yaml
many_lints:
rules:
banned_usage:
banned:
- deny: ['DateTime.now', 'Random.new']
in: ['lib/domain/**']
message: 'Inject a clock or seed so this stays testable.'

Members are written Type.member, matched on the type that declares the member. The unnamed constructor is spelled new. A member of an extension, static or instance, is written Extension.member: deny: ['Doubling.twice'] reports 3.twice for extension Doubling on int.

Every way of referring to a banned member is reported once:

  • calls and constructor invocations: DateTime.now(), Random(), Random.new()
  • tear-offs: DateTime.now and Random.new passed as a value, Box<int>.of
  • reads and writes of a getter, setter or field: Clock.current, Clock.instance = clock
  • dot shorthands: .now(), .new(), .current
  • import prefixes: core.DateTime.now(), math.Random.new
  • unqualified uses inside the declaring class: now() in a static method of Clock
  • constructor redirection: super.system(), this.system(), factory Clock.fixed() = Clock.system;

A doc comment reference such as [DateTime.now] and a show/hide combinator name the member without using it, so they are not reported. A local function, local variable or parameter that shares the member’s name is not the member and is never reported.

- deny: ['DateTime.now']
in: ['lib/domain/**']
message: 'Inject a clock so this stays testable.'
// Don't — in lib/domain/session.dart
class Session {
const Session(this.expiresAt);
final DateTime expiresAt;
// LINT: cannot be tested without waiting for real time to pass.
bool get isExpired => DateTime.now().isAfter(expiresAt);
}
// Do — in lib/domain/session.dart
abstract class Clock {
DateTime now();
}
class Session {
const Session({required this.expiresAt, required Clock clock})
: _clock = clock;
final DateTime expiresAt;
final Clock _clock;
bool get isExpired => _clock.now().isAfter(expiresAt);
}

Passing DateTime.now as a value hands out the same hidden input as calling it, and .now() is the same constructor under a shorthand. Both are reported:

- deny: ['DateTime.now']
message: 'Inject a clock so this stays testable.'
// Don't
class Session {
Session({DateTime Function()? now}) : _now = now ?? DateTime.now; // LINT
final DateTime Function() _now;
}
DateTime startedAt() => .now(); // LINT
// Do
abstract class Clock {
DateTime now();
}
class Session {
Session({required Clock clock}) : _clock = clock;
final Clock _clock;
}

Ban the unnamed constructor, keep the named one

Section titled “Ban the unnamed constructor, keep the named one”

Type.new names the unnamed constructor, so Random() is reported while Random.secure() is left alone:

- deny: ['Random.new']
message: 'Pass a seeded Random so failures reproduce.'
// Don't
int roll() => Random().nextInt(6); // LINT
// Do
int roll(Random random) => random.nextInt(6);

The declaring type is what matches, so an Iterable.first entry also catches a List receiver — a subclass cannot slip past:

- deny: ['Iterable.first']
message: 'first throws on empty; use firstOrNull and handle the null.'
// Don't
int? firstScore(List<int> scores) => scores.first; // LINT
// Do
int? firstScore(List<int> scores) => scores.firstOrNull;

Writing List.first instead would report nothing here: first is declared on Iterable, not on List.

Only instance members reach subtypes this way. Constructors and static members are not inherited, so deny: ['Random.new', 'DateTime.now'] does not report FixedRandom(4) for class FixedRandom implements Random, or a subclass’s own FakeTime.now() constructor.

A bare member name, with no Type. prefix, bans it wherever it appears:

- deny: ['toString']
in: ['lib/api/**']
message: 'Serialize through toJson; toString is for debugging.'
// Don't — in lib/api/payload.dart
String encode(Object value) => value.toString(); // LINT
// Do
String encode(Map<String, Object?> json) => jsonEncode(json);

Prefer the qualified form unless you really mean every type — deny: ['now'] catches DateTime.now() and any other member named now.

A top-level declaration has no type to qualify it. Write it with its library, uri#name, using the same # separator as avoid_banned_types:

- deny: ['package:my_app/core/clock.dart#systemClock']
in: ['lib/domain/**']
message: 'Take the clock as a parameter.'
// Don't — in lib/domain/order.dart
Order newOrder() => Order(at: systemClock.now()); // LINT
// Do
Order newOrder(Clock clock) => Order(at: clock.now());

The library is the one that declares the name, not the one you import, so an import prefix or a re-exporting barrel does not hide a use. A member named systemClock on some type, or a systemClock declared in another library, is not matched. A bare deny: ['systemClock'] still works, but it also bans every member with that name.

The same prefix pins a member to the library declaring its type: dart:core#DateTime.now, package:my_app/core/clock.dart#Clock.now. Use it when two packages declare a type with the same name.

except: lifts one entry in the paths it names, using the same globs as in:. The other entries keep applying there:

analysis_options.yaml
many_lints:
rules:
banned_usage:
banned:
- deny: ['Uuid.new']
in: ['lib/**']
except: ['lib/core/ids/uuid_provider.dart']
message: 'Read ids from the injected id source.'
- deny: ['package:my_app/core/clock.dart#systemClock']
in: ['lib/**']
except: ['lib/core/clock.dart', 'lib/main.dart']
message: 'Read the time from the injected clock.'

lib/core/ids/uuid_provider.dart may construct a Uuid, but it still may not read systemClock. lib/main.dart may read systemClock and may not construct a Uuid. An entry with except: and no in: applies everywhere except the named paths.

exclude: (available on every rule) skips paths for the whole rule:

analysis_options.yaml
many_lints:
rules:
banned_usage:
exclude: ['lib/src/cli/output/**']
banned:
- deny: ['print', 'Stdout.write', 'Stdout.writeln', 'Stdout.add']
in: ['lib/**']
message: 'Return the value and let the renderer emit it.'

Writing to stdout is now reported everywhere under lib/ except the one renderer that owns the terminal. Every other entry of the rule is lifted there too, so prefer except: on the entry when a file needs one exception.

Option Type Default Description
banned list of entries [] The entries to enforce. With none, the rule reports nothing

Per entry:

Key Type Required Description
deny string or list one of deny / deny_pattern Members banned by exact match, written Type.member, as a bare member, or with the declaring library: uri#name, uri#Type.member
deny_pattern string or list one of deny / deny_pattern Regular expressions, anchored to the whole value and tried against both Type.member and the bare member
in list of globs no Paths, relative to the package root, where the entry applies. Omit to apply everywhere
except list of globs no Paths, relative to the package root, where the entry does not apply, even inside in. Lifts this entry only
message string no A project-specific explanation appended to the diagnostic

Write the declaring type. Iterable.first catches a List receiver, but List.first catches nothing — the member is declared once, on Iterable. When an entry unexpectedly reports nothing, this is usually why.

A pattern is tested against both spellings. deny_pattern is tried against the qualified Type.member and against the bare member, so DateTime\.now and now both report DateTime.now() — and an unanchored-looking pattern like .* bans every member it reaches. It is not tried against the uri#name spelling: write library-qualified entries under deny.

Uses, not declarations. The rule reports where a member is used. Declaring a method named now is avoid_banned_names’s job.

An implicit super constructor call is not reported. A subclass constructor with no initializer list calls the superclass’s unnamed constructor without naming it, so class SeededRandom extends Random { SeededRandom(); } is not reported for Random.new. Write : super() and it is.

Globs have no negation. in: and except: support *, ** and ? but no ! or {a,b} alternatives. List each path instead.

A malformed entry is skipped silently. An invalid regular expression costs you that pattern and nothing else — a plugin cannot report problems against a YAML file.