Say I'm writing a handler for an http server.
function handleRequest(req)
const url = new URL(req.url)
if (url.pathname === '/foo') {
// do a thing
}
if (url.pathname === '/bar') {
// do a thing
}
if (url.pathname == '/routes') {
// should print /bar and /foo
}
}
The `/routes` endpoint should print information about the other routes.
The problem I have is that the code to handle the endpoints is the simplest code to do what I want. It is what would come naturally to most developers.
But as requirements change, like to list the routes, I find that I need to refactor everything dramatically just to add one small additional feature of printing out my routes.
For example, the obvious thing most people would do is put all the routes in an array. That is, my routes now become objects. But if I have a more complicated conditional to route match instead of just `url.pathname`, then things start becoming way more complicated.
I find this situation often when coding, and I find it creates so much unnecessary complexity.
Is there a better way to code to prevent having to constantly refactor code?
What I am thinking about at present is code reflection. The simplest way to do what I want here would be to query the code AST for all conditionals in this function, and print them out.