software engineer



Partial class approach for ES5/ES6

August 10, 2015
2 min read

Source code

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 you have a giant class. You may need or want to split it up into different files. Of course, you can do some hacks with the javascript language to get that done. Of course, you can take a different design solution and make smaller classes. Of course, you can do a lot of things, but what I’m trying to show here is an approach to get something like the partial class declaration from OOP languages like C#. Keeping files simple and small. You need to cover some features like private methods, public ones, properties, bind problems ( so you can use “this” on every method), etc. And at the same time you should produce self documented code.

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.

Copyright by nicosommi 🐱