If the class has no fields, could the methods be static?
posted 4 years ago
@Norm Radder: making the method static wouldn't help. More often than not I need to pass an instance of the interface to a library class. For example where myFilter is the class I am discussing here, and myDirectory is an instance of File. I must instantiate the class to pass it to the listFiles() method. But it seems weird to keep creating new instances of this class. Of course, creating the class is trivial since it has no constructor (uses Object's no arg constructor) and no state variables (not even final ones). It seems that once it loaded the first time every instance should use that same instance of the class.
It feels like String in a way.
It would generally be considered bad form to do this.
In that code alpha and beta are the same value, but they are different instances of the same value. It would be confusing to write it that way.
@Salil Wadnerkar: I am not sure how this helps testing, but I am genuinely interested in finding out, if you have the time or can point me in the correct direction. If I instantiate the class from inside the function, I have no way to inject a mock. Right? (sorry if that doesn't make sense - I am not familiar with testing terminology). Also, wouldn't I test the FileFilter implementation by itself? And then the test the file that uses my implementation separately? Assuming the client is code is something I maintain, why would I want to inject a broken version of the filter?
posted 4 years ago
Hi Derik, I was talking about classes that use this class as a dependency. This is a bad example because most probably the classes rely on interface FileFilter and not your implementation of FileFilter. But, if for some reason they do, then mocking your implementation will be difficult if the logic is in static methods (though mocking frameworks like PowerMock can mock static methods also).
Apart from difficulties in testing, dependency injection becomes difficult with static methods. For example, if you are using Spring to initialize your application, you cannot inject object of your class as a dependency into other objects.
These are all generic points and most probably not applicable in your case, but something to bear in mind. This has better explanation: