Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any advantage of having a method as static?

I am using Webstorm and I wrote a React component, my code looks like:

async onDrop( banner, e ) {
    banner.classList.remove( 'dragover' );
    e.preventDefault();

    const file = e.dataTransfer.files[ 0 ], reader = new FileReader();
    const { dispatch } = this.props;

    const result = await this.readFile( file, reader );

    banner.style.background = `url( ${ result } ) no-repeat center`;
    dispatch( addLayer( file ) );

    return false;
}


@isImage( 0 )
readFile( file, reader ) {
    reader.readAsDataURL( file );

    return new Promise( function ( resolve, reject ) {
        reader.onload = ( event ) => resolve( event.target.result );
        reader.onerror = reject;
    } );
}


onDragOver( banner ) {
    banner.classList.add( 'dragover' );
    return false;
}

Webstorm's code inspection suggest me that Method can be static for the onDragOver method. My question is:

Are there any real benefit from having the method as static or this suggestion is somehow useless?

like image 640
Avraam Mavridis Avatar asked Jan 27 '16 14:01

Avraam Mavridis


People also ask

What is the advantage of a static method?

static elements are accessible from any context (i.e. anywhere in your script), so you can access these methods without needing to pass an instance of the class from object to object.

Is static method better?

They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.

What is advantage of making method static in Java?

The most important reason why static keywords are heavily used in Java is to efficiently manage memory. Generally, if you want to access variables or methods inside a class, you first need to create an instance or object of that class.


1 Answers

Yes, you don't need an instance of the object when invoking a static function. All you need is a reference to the constructor:

class Foo {
  static bar() { console.log("foo"); }
}

Foo.bar(); // outputs "foo" to console

No need for a new Foo() anywhere.

By convention, instance methods should be used when you actually need state (either to read state, or to write state) from an instance.

The inspection will tell you that when you have a prototype/class method that does not have a this in it (and thus doesn't need an instance).

like image 118
Madara's Ghost Avatar answered Oct 23 '22 21:10

Madara's Ghost