If you have the tendency to be able to reuse the codes with new arguments or parameter, then place your operation in a function.

However, if you are just using that piece of code only one time, then you can just stick it in your command buttons.