The situation is quite similar to memory leaks. Just do not do chaotic ad-hoc programming. First, define a system, define components and responsibilities, them implement them.
For example, the...