Masturbation is not ideal; but often times it is a tool that can be used to keep you out of sinful situations. If you know you might find yourself in a situation where you will be tempted by lust, better to plan ahead and commit the lesser sin ahead of time.