Method returns this only so that calls can be chained
ID |
dart.maintainability.avoid_returning_this |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Api Design |
Language |
Dart |
Description
Reports a method whose body unconditionally returns this, either as its last statement or as an arrow body. A method holding any conditional return - inside an if, a loop or a switch - is not reported, since it chooses between values rather than chaining.
Rationale
Dart already has an operator for chaining calls on one object - the cascade, .. - and it works on every method, including the ones that return void and the ones written by someone else. A hand-built fluent API duplicates that operator for a single class, and it costs something to do so: the return type says the method produces a value when it does not, so a reader cannot tell a builder step from a method that computes a new object, and every subclass has to keep returning the right type for the chain to survive.
The following code illustrates the pattern detected by this rule:
class QueryBuilder {
String table = '';
int limit = 0;
final List<String> columns = [];
// FLAGGED: Method returns this only so that calls can be chained
QueryBuilder from(String name) {
table = name;
return this;
}
}
Remediation
Return void and let callers chain with the cascade operator - builder..from('t')..take(10) reads the same as the fluent form and needs no support from the class. Keep a real return value only where the method genuinely produces one, such as a builder step that returns a new, differently-typed builder.