1
\$\begingroup\$

There is a file created with the project paths in a dictionary.

Example:

export const URL = {
 DASHBOARD: '/dashboard',
 SETTINGS: '/settings',
 PROFILE: '/profile',
 PRODUCTS: '/products/'
};

And in the file where the routes are used, the urls are imported. A coworker and I are debating about two ways to write the code.

One of us says that it is more readable import file and do destructuring.

import { URL } from './urls.constants';

export default function ROUTES() {
    
  const { DASHBOARD, SETTINGS, PROFILE, PRODUCTS, etc.. } = URL;

  return (
   ...
   <Route path={DASHBOARD} />
   <Route path={SETTINGS} />
   <Route path={PROFILE} />
   <Route path={PRODUCTS } />
   ...
 );

The other one of us says that is equal or more readable use the dictionary or enum.

import { URL } from './urls.constants';

export default function ROUTES() {

return (
  ...
  <Route path={URL.DASHBOARD} />
  <Route path={URL.SETTINGS} />
  <Route path={URL.PROFILE} />
  <Route path={URL.PRODUCTS } />
  ...
);

We know that both options are correct, but what is the best option regarding readability and clean code?

\$\endgroup\$
1
  • \$\begingroup\$ This is a nitpicky point, but of these two options, the 2nd is clearly better. \$\endgroup\$
    – Jonah
    Mar 27, 2022 at 5:36

1 Answer 1

1
\$\begingroup\$

Personally, I think that this comes down to developer preference, although, preference aside, you should be programming in a style that adheres to your company/team's style guide (if one exists).

However, I do think that there's an another solution in there, but it depends upon an assumption that you haven't explicitly declared:

Assuming that every URL in your URL dictionary needs to be registered via the <Route> element, could you not combine Object.entries() and .map() to dynamically generate the routes?

import { URL } from './urls.constants';

export default function ROUTES() {
  return (
    ...
    {Object.entries(URL).map(([name, path]) => <Route key={name} path={path} />)}
    ...
  );
}

Again, this solution depends upon an assumption that I've made on your scenario. But hopefully, either way, it gives you something to think about!

\$\endgroup\$
1
  • \$\begingroup\$ Yes, that is another solution! and best solution. I think hat this comes down to developer preference but I prefer to avoid duplicating the code. And I think that using desrtucturing it duplicate code \$\endgroup\$
    – Javier
    Mar 25, 2022 at 10:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.