When you create components that have some code quality control like code climate, bithound or something like that. There are plenty errors that you will found on your component, from code duplication to very specific details.
One of those rules is the class complexity.
So I came up with a simple solution but that has some key points to unlock some features (private methods with symbols and using a standard function to attach to the class prototype). It is not something trivial actually but not so hard neither. It consist on some easy to follow steps (on the example code, using the Babel plugin implementation for ES6 and ES5 compatibility):
- Instead of creating a file for your class, create a folder for it.
- Create an index.js inside of it that contains the actual class
- Create some file with the function/functions that you want to have in different files
- Chose one of the alternatives to assign the method to the main class on the index. For example Object.assign(MyClass.prototype, objNewMethods). This is maybe the best option since it bind the functions automatically. UPDATE: It seems like there is a caveat using Object.assign to copy methods… I will work on it soon to check that it happens and then update the article/source code with a better solution.
- If you want to split up symbols (usually used for private methods) you need a separate file to instantiate them and use the same one among different files (for example to call a private method from another file).
That’s basically all! See this repo to take a look at a working source code.
Now you have a class in several files, small and self documented files with functions with reduced complexity.