How to organize custom code for plugins & themes

You have lots of plugins, and even a theme. You are brave and adventurous – and you write (or copy-paste) lots of snippets to modify their default behavior. Now you have a custom code all over the place and even in your theme functions.php.
Is there a better way to fix that mess?