For a programmer, getting distracted is bad, bad like "that's baaa-aaaad umkay?", bad like crossing the streams bad, bad, bad, and bad. Distraction == mistakes. Distraction means lost time. Distraction means doing things over because you did something subtly stupid that looked okay on the first glance but contained a really boneheaded bug buried deep inside it. I hate getting distracted. I would really rather work in focused, multi-hour blocks. A block for work, a small block for lunch and exercise, another block of work, a block of family time, and a double block of sleep. Of course, it rarely works that way.
A big part of the reason that I left my last job was distraction. I had six to eight meetings a week, I was getting 20 to 40 emails requiring a response every day (outside of spam and automated messages), and I had to investigate and respond to a couple of customer inquiries every day, all while being expected to design and implement fairly complex software. After the nth month of little progress and lots of frustration I realized it wasn't working out and moved on. I need to feel effective to be comfortable with my work, and to be effective, I need to be able to concentrate on a task for more than 5 minutes without interruption.
One of my favourite techniques is to fight distraction with distraction, that is, I find that while I'm working on something, particularly code, my mind sometimes wanders and sometimes the wandering track takes over. The best way to keep on track is to control the wandering, and for me, what works is music. Particularly music with a regular repetitive beat and few to no lyrics. Helllllloooooooo techno. DnB works too. Trance can get distracting, depends on the set.
Anyways... music doesn't always work. Sometimes you just have to get up. That trip to the bathroom can only wait so long, it doesn't matter how close to fixing that bug in your stream class you are, sometimes you have to get up. Or the phone rings. Or the client wants a status update. Or whatever. When that inevitable interruption does happens, the key to getting back into the groove (for me) is to have a clear entry point, and that's what I love about Test Driven Development (TDD). When I get back to my desk, whether I've been away for five minutes or a week, the first thing I do is run my test suite. Whatever test fails is what I'm going to look at first.
If I'm going to be away for a longer period, like overnight or more, I make sure to craft my next test before I depart, that way, the feature I should be working on is right there waiting for me to finish it when I get back. It's repeatable, it's reliable, and it draws me in mentally, even when I'm tired, frustrated and under-caffeinated. I know this isn't really the goal of TDD, it's just a fringe benefit and it really works for me.