4
\$\begingroup\$

I'm trying to transition myself from my old coding-style (if-else, for.. in) to functional programming. I've tried to update the following code:

Old

class test {
    childrenCount(group) {
        let childCount = 0;
        let excluded = ['html'];
        let iterable = group.children || group;

        for (let key in iterable) {
            let elem = iterable[key];

            if (elem.type === 'group') {
                this.childrenCount(elem);
            }else if (element.properties && excluded.indexOf(elem.properties.type) == -1){
                childCount += 1;
                if(!elem.visibility){
                    childCount -= 1;
                } else if (element.properties.seen && !element.properties.showerror || element.properties.required){
                    childCount -= 1;
                }
            }
        }
        group.childrenCount = childCount;
    }
}

New

class test {
    childrenCount(group){
        group.childrenCount = 0;
        let excluded = ['html'];
        let iterable = group.children || group;

        let countElement = (elem) => {
            if (isCountable(elem))
                return isVisible && isValidAnswer(elem) ? 0 : 1;
            return 0;
        };

        let isValidAnswer = elem => {
            return (elem.properties.seen && !elem.properties.showerror) ||
                   !elem.properties.required;
        };

        let isVisible = elem => {
            return !elem.visibility;
        };

        let isCountable = elem => {
            try{return excluded.indexOf(elem.properties.type) == -1;}
            catch (err) {}
        };

        let isGroup = elem => {
            return elem.type === 'group';
        };

        Object.keys(iterable).forEach(k => {
            let elem = iterable[k];
            if(isGroup(elem))
                this.childrenCount(elem)
            else 
                group.childrenCount += countElement(elem);
        });
    }
}

Now I am thinking: the old code was smaller. It was not as readable, but the new code is significantly bigger.

  • Is my functional programming too excessive?
  • Is it better or worse then my old way of writing functions?
  • Are both methods just plain right or wrong, any advice for improvement?

I feel that the second one is more testable because I could test the individual functions, that's important I think. But on the other hand, if I have enough input-space-partitioning, the first one would be testable too (just less precise).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.