Member-only story
Effective Java! Prefer Annotations to Naming Patterns
Historically library creators would use specific naming paterns to signify where functionality should be extended and as a signal for how we would like the library to interact with our code. A great example of this is prior to JUnit 4 in order to signify that a particular method was a test method; it would be prefixed by the word test
. This method was not without its issues. For example a spelling mistake could lead to silent failures. If you named your method tsetSuperImportantStuff
JUnit wouldn't throw any errors and happily just ignore your test. If you weren't paying close attention you wouldn't notice either. With this system there is no way to indicate where a particular naming pattern is valid. For example if a user thought if they called their class TestAllTheThings
it would pick up the whole class there is no way for the library to indicate to the user that this is not how to use this pattern. The final issue we are going to highlight is that there is no simple way to pass parameters to the consumer of the pattern. Imagine trying to pass an expected exception type? Something like testRunTimeExceptionThrownIsUsefulTest
. Parsing out the exception type would be extremely error prone and leads to tests with not ideal names.
So what is the alternative? Annotations, that is what we can replace these patterns with. JUnit also decided to do this with the release of version 4. Let’s pretend we are making the simplest test runner possible. We would want to start with something to signify what methods should be tested.