“What have you learned from maintaining your own code?” is a pretty decent question to ask candidate programmers. Many people we interview have never stayed longer in a job than 2-3 years. That's enough to build something of size, but often leave without seeing whether it'll stand the test of time.
I've been with my current company for seven years now. It's enough to let me see how my earlier ideas played out in practice. And boy, have I been wrong at times. Several of the components I wrote are now part of our technical debt and when I do a technical introduction for newcomers, on several items I repeat “that one's my fault”. What I thought will ease maintenance and development, either doesn't anymore or never did. It's been seven years of excellent education, and one that I was being paid for.
There are a lot of good reasons to change employers. Abusive work environments and dead-end, repetitive, I'd-rather-die-boring positions top that list, and if you're in one of these places, you cannot leave too soon. But my approach was always that once I agree with my employer to a set of conditions, including fair pay, humane work environment and, importantly, lots of space to grow, I become committed to that relationship for as long as these conditions are upheld.
On the other hand, some of my colleagues left, lured by offers “too good to refuse”, presenting massively interesting challenges to tackle. Modern technologies, booming industries, novel approaches. Often sweetened with better pay. I cannot blame them and I cannot say myself what I would've done if presented with such an offer.
One can certainly also make the argument, that others’ work is just as good a source of learning, as one's own. That going to a different place, working with different people will expose one to other, often better approaches. Of course. I'm just afraid of this turning into a cargo-cult spiral, where you acquire new ways of working without taking the time to understand them—why they succeed and where they fail—before moving on to the next big thing.
It's complicated. There's no good number or even range of years one “should” spend in a single place. Not without considering the context of this time—the company, the people, the work and alternative opportunities. And in a world of abundant opportunities, such as the one we have now in IT, it's crazy difficult to decide whether and when to make a move.