Functions are the heart of reusable code. The principle is always the same; in order to avoid duplicate code that is difficult to maintain, it is desirable to introduce a function.
Functions are blocks of reusable code that are generic enough that they can be used multiple times, and specific enough that they serve a distinct purpose. Making use of functions will greatly help you when writing unit tests for your code. Instead of having to cover all instances of the duplicated code, you can test your function separately from the calls to it.