Where to allocate resposibilities

Posted: November 2, 2009 in Thoughts on development

I was reviewing code today and one of the things we discussed was if certain data should be parameters to a method or if they should be attributes of the class that held that method.

When I see a method I want every argument used in decisions or in expressions that will eventually make their way to the return value. If there’s no return value the method probably have side effects and if that’s the case I’d probably rewrite the method so for this post let’s stick to a method with return value.

The issue we had was that some of the arguments were actually used to ensure invariants but invariants not ever changing they are known at the time the object is created and should be enforced at the time of creation. If they are violated at the time of creation they are still violated at the time of execution.

The first point worth mentioning is to enforce constraints as early as possible to fail as early A’s possible. If some constraint can be enforced at compile time they should be.

The second point worth mentioning is that every argument given to a method should influence the flow of the method everytime and possibly the result as well. The only exception to influencing the result I can think of is when the result is partly based on things external to the method. E.g. if the method is returning calls to a database.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s