The linked \"duplicate\" question is an iffy match at best, because it\'s asking
ID: 645719 • Letter: T
Question
The linked "duplicate" question is an iffy match at best, because it's asking
is pattern X OK (YES/NO)
and I'm clearly already in the NO camp, and subsequently asking
what is pattern X called
what steps can be taken to fix pattern X
(neither of which are addressed by the linked question).
I recently did a code review on a block of code that looked something like this:
public class MyClass
{
private ISomething mySomething;
// ...Other variables omitted for brevity
public MyClass() { mySomething = new Something(); }
/// <summary>
/// Constructor - ONLY USE THIS FOR UNIT TESTING
/// </summary>
public MyClass(ISomething something) { mySomething = something; }
public void MyMethod()
{
// Gets called by the framework, and changes the internal state of the class by using mySomething...
}
// Other methods...
}
I'm concerned specifically with the overloaded constructor. It was added purely to test this class, and will make its way into production code.
Is there a name for this pattern/anti-pattern, and what can be done to solve it?
For clarification, the implementation of Something was added specifically for the purpose of being able to add an overloaded constructor to MyClass. It's used nowhere else. Its existence is an instance of the very issue I'm concerned about.
ISomething is very tightly coupled to MyClass. It needn't have been extracted. Implementation and interface might as well look like:
public interface ISomething
{
string GetClassName();
}
public class Something : ISomething
{
public string GetClassName() { return "MyClass"; }
}
That means that MyClass.MyMethod()'s body could just be replaced with return "MyClass";
However, the interface abuse/premature optimization seems like a separate issue and not in the spirit of the original question (i.e. consider it a given that the class/interface is structured like so and leave it as a separate [but valid] concern).
Explanation / Answer
For methods of a class which are solely for testing purposes, I have seen the name maintenance hatch in the past. And similar to real maintenance hatches in physical machines, those methods sometimes have their purpose. For example, if you are going to make some legacy code testable when it has grown too big after some years of evolving, maintenance hatches can be of great value.
But I also agree to the other answers here, such methods should be an exception, and when you keep classes and components small, with well designed interfaces, you seldom need them.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.