3

I have a single file that has utils methods. Each is exported individually. I am in a situation where one util requires another. I currently define the functions used before they're used. But I came across ES6's cyclic dependency and using that removes the need to meticulously organize the util functions. Is there any reason I should not use that?

Simplified eg: Currently:

  export const safeParsing = (str) =>  { 
    try { return JSON.parse(str); }
    catch (e) { return {}; }
  };

  export const parseToken = (t) => safeParsing(t); 

Using cyclic dep:

import * as self from 'src/jsUtils';

export const parseToken = (t) => self.safeParsing(t);
export const safeParsing = (str) => {...}

Edit: Using cyclic imports also enables me to spyOn (Jest) inner functions. Eg:

 test('parseToken uses safe parsing', () => { ... spyOn safeParsing ... });

Relevant refs:

ES6 modules: Export single class of static methods OR multiple individual methods

https://stackoverflow.com/a/40242291/958598

https://stackoverflow.com/a/35225936/958598

https://stackoverflow.com/a/55193363/958598

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Struggler
  • 672
  • 2
  • 9
  • 22
  • 1
    If you define them as ordinary functions with `function safeParsing() { ...}` rather than assigning them to a `const` variable, then ordering no longer matters because all `function` definitions are hoisted to the top of the scope. So, you can use all functions in any order. If you do `const safeParsing = ...` then you have to very carefully order the declarations because they can't be used until after they are assigned. This is one of the reasons I use the regular named function declarations rather than function expressions (like you show). – jfriend00 May 11 '20 at 01:57
  • 1
    And, you can still do `export function safeParsing() {...}`. Just make your definitions be function declarations, not function expressions. – jfriend00 May 11 '20 at 01:59
  • @jfriend00 thank you for the answer. That works for me. I suggest you add that comment as your answer to this question – Struggler May 29 '20 at 07:52

1 Answers1

0

If you define them as ordinary functions with function safeParsing() { ... } rather than assigning them to a const variable, then ordering no longer matters because all function definitions are hoisted to the top of the scope. So, you can use all functions in any order. If you do const safeParsing = ... then you have to very carefully order the declarations because they can't be used until after they are assigned. This is one of the reasons I use the regular named function declarations rather than function expressions (like you show).

And, you can still do export function safeParsing() {...}. Just make your definitions be function declarations, not function expressions.

jfriend00
  • 683,504
  • 96
  • 985
  • 979