First off, try to understand that - at least in the secular sense - the act itself isn't 'bad'. What's 'bad' is when you become addicted to it, which applies as well to anything else, e.g. drinking, smoking, etc. The addiction is the 'bad' thing.
Whenever you get the urge, try to identify what's causing it. What happened before or after? For before - were you simply bored? Were you watching porn (which naturally got you fired up)? Were you stressed? For after - are you addicted to it because of the pleasure that comes after? Do you feel immense guilt immediately after the pleasure fades?
Once you find out the rationale of your habit, try to prevent yourself by addressing the habit directly. If you do it because you're bored, try to find something else to occupy yourself. If you in it for the pleasure, try to find something else that will equally give you pleasure or satisfaction, but not necessarily in the sexual sense. It could be gaming, or whatever other activity. (This, in fact, helps solve the 'bored issue too, if applicable.)
Of course some amount of determination and willpower would be helpful during this process, especially when starting out. Don't fault yourself too much if you break the cycle along the way, just focus on starting and maintaining the next cycle. And of course, again analyse what made you break the cycle, if it happens.
Ideally you should be able to control yourself such that you do not feel 'trapped' by it, i.e. uncomfortable if you did not do it, etc.
All the best.
Disclaimer: I'm not a psychologist / psychiatrist / doctor / whatever, the above should not be taken as professional advice.