Java – should I use dependency injection for good design and testable code?
I have a class representing images: it's called photography
The constructor is as follows:
Photography::Photography(QString originalPath,QString appDirectory) { this.originalPath = originalPath; this.appDirectory = appDirectory; }
This class contains many methods, such as gettitle(), getcaption(), getsize(), ishorizontal(), etc
There is a public method named getthumbnailpath(), as follows:
QString Photography::getThumbnailPath() { if (previewPath == "") { previewPath = appDirectory + "//cache//"+ getHash() +"-thumb.jpg"; } return previewPath; }
This method calls the GetHash () method internally:
QString Photography::getHash() { if (myHash == "") { QCryptographicHash hash(QCryptographicHash::Md5); QByteArray result = hash.hash(originalPath.toUtf8(),QCryptographicHash::Md5); QString hashResult(result.toHex()); myHash = hashResult; } return myHash; }
What I want to know is that if the GetHash () method belongs to photoclass or should be in my own hashgenerator, I should inject it into the photography class
However, I don't want to inject a lot of parameters into the photography constructor, just to make the class testable
In this case, if I can't control the method of generating hash, I will face the test of getthumbnailpath() method. I can't test getthumbnailpath() method
Solution
"However, I don't want to inject many parameters into the photography constructor, just so that the class can be tested."
Testability is the high quality of any code But more importantly, by associating a hash with a hash generator, you can relieve responsibility and make your code easier to maintain
In addition, this now means that you can test hashes independently without photography It is now a unit testable hash, giving a path that does not involve photography, for example