Home

Untangling a large method

Ever had a long method that you needed to refactor?

How do you start on it?

group things into sections.

Example:

const runServer = () => {
  server.get('/foo',Foo)
  cronJob1()  
  server.use(mw1)
  server.get('/foo',Foo)
  cronJob2()
  server.use(mw2)
  server.get('/foo',Foo)
  cronJob3()
}
const runServer = () => {
  const instantiate_routes = () => {
    server.get('/foo',Foo);
    server.get('/foo',Foo);
    server.get('/foo',Foo);
  };
  instantiate_routes();  
    
  const apply_middleware = () => {
    server.use(mw1);
 	server.use(mw2);
  };  
  apply_middleware();  
  const initialize_cron_jobs = () => {
    cronJob1();
    cronJob2();
    cronJob3();
  }
  initialize_cron_jobs()
}

This is a low-risk refactor because () => {} doesn't change the scope of the methods! So please do not use function() {} because that might break stuff.

I think this is better than delimiting the sections with comments