Home

Refactoring Haiku

Before:

  // Get a list of user ids from foo company
  const userData = await database.client.db('main').collection('users').find(
    { email: /@foo/ },
    {
      projection: {
        id: true,
      },
    },
  ).toArray();

  const usersJSON = userData.map(user => user.id);

After:

const get_ids_of_users_from_company_foo = async () => {
  return await get_ids_of_users_with_given_email_regex(/@foo/)
  
  async function get_ids_of_users_with_given_email_regex(email_regex) {
  	return (await database.client.db('main').collection('users').find(
    { email: email_regex },
    {
      projection: {
        id: true,
      },
    },
  ).toArray()).map(user => user.id); 
  }
}
const user_ids = await get_ids_of_users_from_company_foo()

The business logic is clearer in the refactoring. A user is part of organisation foo because he has an email that contains '@foo'.

Clarity helps a lot in finding bugs. For example, the code above will match users with emails having @foo and @foobar. These are probably different companies so our code potentially contains a bug.