So, here's my experience in another creative process.
I'm an artist. The vast majority of my thinking and planning time happens with a sketchbook or drawing program open in front of me, and me rapidly generating rough sketches and/or story notes. I have learnt over the years that, sure, I can sit there staring off into space trying to work stuff out in my mind's eye all I like, but things go a lot faster if I work it out by creating a rapid feedback loop between what I'm sketching out in front of me, and how I want it to look when it's done.
Sometimes when I am very stoned I can enter a state where I'm holding a nearly complete image of the whole drawing in my mind's eye and "tracing" it onto the paper. It's a pretty cool place to be in. But it's super fragile; interrupt me and I'll lose it, with an incoherent fragment of a drawing. So normally, I don't work like that at all - I'll quickly draw the roughest version possible of the important parts of the drawing, and iterate on that until it's done, or until I decide this approach is not working, and try another one. My ideas are in tangible form as soon as possible.
When I'm writing (I mostly make comics, so I get to draw AND write), it's the same thing. As soon as I have the germ of a baby idea that sounds okay, I pull out paper or Evernote or whatever and write it down.
Interruptions still suck. Interruptions can still take time to recover from. But I don't have to spend a half an hour building up an intricate mental model of what I want to do afterwards from scratch, because I have a pile of roughs and notes that documents the process of getting to where I was.
So my suggestion, from how I practice my craft: As soon as you realize you're getting into complex territory, open up a notebook and start scribbling questions and answers and inspirations to yourself, draw little diagrams (or big ones). And mess up your copy of the code with a ton of comments - what's this section doing, what do I need to investigate further, here's some pseudocode for how I might fix this, etc, etc. Document as much of your thinking as possible, put as much of the headspace you're generating outside of your head as you can so that it's easier to pick up the pieces after an interruption.