Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason to use static/private static methods in TypeScript?

Tags:

oop

typescript

I'm thinking about but can't find any reason to use static methods (and especially private static) in a TypeScript class. Am I missing something? I'm asking this question because I saw code like this:

class Abc {

  public someMethod() {
     Abc.myMethod();
  }

  private static myMethod() {
     ...
  }
} 

P.S. For those who try to explain me difference between static and non-static methods and what is private method. I know these perfectly well thanks to my many years background in C#. If you read question carefully - it was about using these in TypeScript.

like image 888
andrey.shedko Avatar asked Sep 24 '18 14:09

andrey.shedko


People also ask

Should I use static methods in TypeScript?

When developing class functions that don't rely on an internal state, it's a good idea to turn them into static methods. This can be easily done by adding the keyword static to your function's declaration.

Why do we need static methods TypeScript?

In short, if we say about static methods, the static keyword enables us to use methods of a class without instantiating an object first. In static methods, you can define both static and non-static data members, and you can also use this keyword in static methods.

Does it make sense to have private static method?

You make the method private as it is not designed for widespread usage and you don't want unrelated code calling it. (Debate this point in the comments….) As the method does not access any instance fields, it can be make static, by making it static you make it easier to understand and maybe even a little faster.

Should I use private static?

Private static variables are useful in the same way that private instance variables are useful: they store state which is accessed only by code within the same class. The accessibility (private/public/etc) and the instance/static nature of the variable are entirely orthogonal concepts.


2 Answers

I personally like to use private static methods to indicate a pure function. Then you absolutely know that such a method will never mutate the object's state.

Implementing functional programming whenever possible within the object oriented programming paradigm creates more side-effect free code that ultimately has lower coupling. This leads to code that is less prone to object state bugs, regression bugs, and that is generally easier to understand.

Here's a very simple example:

interface DatabaseFoo {
    size: number;
    color: string;
}

class Foo {
    private static toDatabaseFoo(
        uid: string,
        color: number,
        length: number,
        width: number
    ): DatabaseFoo {
        let convertedData: DatabaseFoo;

        // Perform object specific data cleaning and/or transformations

        return convertedData;
    }

    private color: number;
    private length: number;
    private uid: string;
    private width: number;

    saveToPersistence(): void {
        const databaseFoo = Foo.toDatabaseFoo(
            this.uid,
            this.color,
            this.length,
            this.width
        );
        const jsonFoo = JSON.stringify(databaseFoo);

        // Save to persistence
    }
}
like image 151
Tom Daniel Avatar answered Oct 23 '22 20:10

Tom Daniel


The main difference between a static method/property and a non-static one is that: at the memory level, a portion of the memory will be created for the static fields, which will be shared across all objects in the class. So it works in C # or Java.

For javascript this behavior was implemented In ES6+. But for earlier versions of Ecma Scripts typescript emulates this case.

In your case method myMethod() can be used as a way to hide the complex resource-intensive functionality of the not tied from a specific instance of the class and hidden from the end user.

See this code:

class A {
    protected _p: string;
    constructor() { 
        this._p = "A";
    }
    public someMethod(value: string) {
        A.myMethod(this._p + value);
    }
    private static myMethod(p:string) {
        console.log(p);
    }
} 

class B extends A {
    constructor() { 
        super();
        this._p = "B";
    }
}

var a1 = new A();
a1.someMethod("_1");
var a2 = new A();
a2.someMethod("_2");
var b1 = new B();
b1.someMethod("_1");
like image 25
Codd Wrench Avatar answered Oct 23 '22 20:10

Codd Wrench