mercredi 3 juin 2015

Java Assertions, in comparison/contrast to Unit Tests and Exceptions

Here's my high-level, general question:

Why would one use Assertions as opposed to Unit Tests and Exception Handling?

To clarify my confusion and qualify my concerns, I'll talk a bit about what I know of Java Assertions and my background insofar as is pertinent to this line of questioning.

So, to start, before this week, I honestly didn't even know about the Java framework's assertions, nor their function, so I absolutely admit that I'm likely not getting the whole picture. That being said, I have been a professional in web development, data, and API development for almost a decade now, so I'm not entirely naive.

From what I've read, and discussions I've had, assertions are generally used during development, (almost) always turned off in production, and will check for post conditions and class invariant values; they can be and are used for other things, but these two things seem to be their main contemporary usage. They are built on top of the Java Exceptions, are a subtype of Error, and are thrown when violated. When turned off, they add no runtime overhead.

To me, however, they seem superfluous, especially when considering good Exception handling techniques and good unit testing practices. I fail to see any circumstance where an assertion would alert the programmer to a bug or issue that exception handling or unit testing would not.

Following that line of thought, they seem to me to create code clutter. If they are not meant to be run in production and act as a development aid, then their presence in production code is a bit of an anti-pattern: you have separate source folders for tests and test resources, and you write testable code, rather than code strictly for testing. Whenever I find myself writing code just so I can test, that alerts me to poor design, and I step back and re-architect what I'm doing so that my code is testable. It seems to me that this is an example of that paradigm being violated. Wherever an assertion exists, it could be replaced by a try/catch block or by a set of unit tests - at least, that's the way it seems to me.

Can others add insight to this train of thought? Perhaps you agree - add examples why or expound upon my reasoning. Then again, maybe you think I'm very wrong - state why and provide examples to back up your reasoning, or provide counter-arguments to the way I view things.

Thanks all!


Resources I've consulted, for your reference:

Aucun commentaire:

Enregistrer un commentaire