Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export class vs functions

In case of utility module, I can have either class with static methods or just export methods. I think the first solution is better, though I saw a lot of implementations with second option. Are there any "nuances" here which I am not considering?

like image 742
someUser Avatar asked Nov 08 '14 10:11

someUser


People also ask

What is export function?

The Export function is an idea used in economic theories to measure exports. The total amount of exports, E, in a nation is mainly affected by two variables, see import, the total foreign absorption and the real exchange rate.

How do I export a class function in React?

Use named exports to export a component in React, e.g. export function Button() {} . The exported component can be imported by using a named import as import {Button} from './another-file. js' . You can use as many named exports as necessary in a file.

What is difference between export and export default?

Exports without a default tag are Named exports. Exports with the default tag are Default exports. Using one over the other can have effects on your code readability, file structure, and component organization. Named and Default exports are not React-centric ideas.

What's the difference between module exports and exports?

When we want to export a single class/variable/function from one module to another module, we use the module. exports way. When we want to export multiple variables/functions from one module to another, we use exports way. 2.


2 Answers

I would argue that a class with static methods is better for the following reasons:

  • If your class name is Utils, all imports will by default import it as Utils too. With exported functions however, they could be imported as Utils yet that would only be a convention , one that likely won't be the case in all the different places.

  • A class named Utils in a file named utils.js with all the utility methods neatly grouped together is aesthetically more pleasant than flat functions defined all over the place.

  • A class could have properties that are used among its methods, for this you'd need @babel/plugin-proposal-class-properties though. Again, much nicer than variables defined all over the place.

like image 142
j4hangir Avatar answered Sep 18 '22 14:09

j4hangir


Exporting methods is safer because you don't give access to class properties. Note also that in javascrpt the concept of class does not have a lot of sense, it's been introduced to make feel more confortable developers with oo languages background. Try to work with Object prototyping instead.

like image 38
matteo Avatar answered Sep 22 '22 14:09

matteo