Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are methods with a "method could be static" warning considered bad form in JavaScript/TypeScript?

I have noticed that if I write a method that only acts on local variables of calling methods (does not directly interact with a class variable) then I get a warning that the method can be static.

Sometimes it's nice to abstract a large piece of code into a separate method. Is this somehow consider bad practice in JavaScript/TypeScript?

Since I keep getting these warnings I'm taking a chance that the post police will pounce on me for asking a question that could invite opinions. Let me defend against that by saying that the warnings I'm getting are not opinions. They are definite warnings. That suggests that there exists an answer that is not opinion, at least from the perspective of the people who decided to create those warnings.

EDIT: I was asked to put code here to provide a valid reason as to why I would want to do this. I personally don't think this adds any clarity to question I asked but here's an example of a method that was producing the warning in WebStorm.

//Change object array in *.content objects to values array
//noinspection JSMethodCanBeStatic
transformData(visibleData) {
    const ret: any = {};
    ret.headings = visibleData.headings;
    ret.checkbox = this.checkBox;                                                   //add if the table needs checkboxes
    ret.content = [];
    for (let i = 0; i < visibleData.content.length; i++) {
        ret.content.push(_.values(visibleData.content[i]));
    }
    return ret;
}

The point of this function is to take a clone of the instance, so as not to modify the instance itself, and create a different object, mainly a values only array, which will be used to databind in the template. I did this so my table template could be reusable since columns vary in number.

like image 842
Chris Sharp Avatar asked Aug 14 '26 00:08

Chris Sharp


1 Answers

Code which does not interact with instance should be a free function or at least a static method of a class when you believe it is tightly coupled with class API.

Every additional method you add to API has to be supported. So larger classes require more support than smaller classes. In some languages, like Java, you can't have free function, so you have to attach function to some class, but TypeScript and JS are more flexible, so there is no need to pollute class API.

And you could consider it from the performance optimization point of view.

When JS evaluates class method it looks it up in the object instance, than in the object prototype, than in the parent's prototype, etc. Every lookup eats cpu time, so when you think about performance, free function is your choice.

like image 197
v-andrew Avatar answered Aug 16 '26 13:08

v-andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!