Coding Style – Is It Good Practice to Use Functions to Centralize Common Code?

coding-style

I run across this problem a lot. For example, I currently write a read function and a write function, and they both check if buf is a NULL pointer and that the mode variable is within certain boundaries.

This is code duplication. This can be solved by moving it into its own function. But should I? This will be a pretty anemic function (doesn't do much), rather localized (so not general purpose), and doesn't stand well on its own (can't figure out what you need it for unless you see where it is used). Another option is to use a macro, but I want to talk about functions in this post.

So, should you use a function for something like this?
What are the pros and cons?

Best Answer

This is a great use of functions.

This will be a pretty anemic function (doesn't do much)...

That's good. Functions should only do one thing.

rather localized...

In an OO language, make it private.

(so not general purpose)

If it handles more than one case, it is general purpose. Moreover, generalising isn't the only use of functions. They are indeed there to (1) save you writing the same code more than once, but also (2) to break code up into smaller chunks to make it more readable. It this case it is achieving both (1) and (2). However, even if your function was being called from just one place, it might still help with (2).

and doesn't stand well on its own (can't figure out what you need it for unless you see where it is used).

Come up with a good name for it, and it stands fine on its own. "ValidateFileParameters" or something. Now stands fine on its own.