Write a common function for invoice calculation.

Write a common function for invoice calculation.

I have an Invoice form. I need to calculate invoice totals every time there is change in some fields (for eg. product, quantity, price). 

Is it possible to write a common function to calculate the totals instead of doing the calculation in every field.