Find code duplication
Domenik Reitzner
Posted on July 10, 2020
This is part three of seven.
jsinspect, services and other shenanigans
If you have ever worked on a project that has been going on for 5 years or longer, you know that multiple people have worked on it. Those who have on-boarded you unto the project don't even know the people anymore who started the project. Code styles and the way of how things are done in the project have changed multiple times.
For that reason there is a lot of code in the project that might just have been duplicated or have similar functionality, but uses different settings. An example would be if you have a swiper in your project, and they only differ in the items they display per slide. Here is an oversimplified example (of something we had in our project multiple times)
Swiper1:
class SwiperDirective {
constructor($element, SwiperGenerator) {
Object.assign(this, {
_$element: $element,
_SwiperGenerator: SwiperGenerator,
});
}
$onInit() {
this._initSwiper();
}
_initSwiper() {
const swiperOptions = {
slidesPerView: 1,
};
this._SwiperGenerator.init(
this._swiperContainer,
swiperOptions)
.then((swiper) => {
this._swiper = swiper;
// do some stuff
});
}
// some important functionality here
}
angular
.module('someModule')
.directive('ddSwiper1', function ddSwiper1() {
return {
scope: true,
controller: SwiperDirective,
controllerAs: 'swiper',
restrict: 'A',
};
});
Swiper2 is pretty much the same, but has different options:
const swiperOptions = {
slidesPerView: 3,
};
One tool that helped with this problem (besides knowing the code base and refactoring) was jsinspect.
It is a nice command line tool with a lot of options, that will automate discovery.
Just install it globally npm install -g jsinspect
and run it on your codebase jsinspect --ignore "test" ./path/to/src
.
After that you can always fine tune with the options that are provided to fine tune the result.
One thing I really recommend, really for any project: KNOW YOUR CODEBASE!
It will help you make better decisions and to not duplicate already existing code.
Coming up next
- uglify you private methods/members at build time
Posted on July 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.