Only check parameters on public interface methods

This was not obvious but should make some sense. Of course, it can break if you have “friends” or some other weirdness going on in your code. Let’s say that you have a class like this:

If I create an instance of this class, I have a little nice and neat package. The only way to access the data or modify the data in the class is through the public interface, like such:

As long as you verify the data coming into these public function methods that are exposed, the state of the object should be valid. You don’t need to do parameter checking on the internal function methods.

Of course, you may want to do checking on the internal methods simply because you don’t trust your calculations, but in general, the state of the object should always be sane. But you don’t know what’s going to enter the public interface, so you should always check that. Alternatively, you can use “if” statements and “throw” while validating the contract on the public interfaces, but maybe just use “assert”s on the private methods to make sure your code is internally stable while developing. When unit testing, of course, you probably only test the interface.

Leave a Reply

You must be logged in to post a comment.