Optimize factory() code