Home > Net >  Typescript Object.assign() VS create new object Efficiency
Typescript Object.assign() VS create new object Efficiency

Time:04-16

I have two ways to implement a method with a constant, but I am not sure which way is better. Can someone consult on it? Thank you!

method 1: put a constant out of the class, which will invoke the constant once only but I need to return a new variable

const X = {a: 0, b: 1, c: 2}
export class A{
   private method a (val: any) { 
       return {...X, ...val}
}}

method 2: put a constant in the method, which will invoke the constant every time calling the method (twice in my case) but does not need to create a new object.

export class A{
   private method a (val: any) { 
       const x = {a: 0, b: 1, c: 2}
       return Object.assign(x, val)
}}

CodePudding user response:

I think there's no silver bullet here, each case may be different, but my suggestion is to pay more attention about the scope of the variable rather than how much time it's called or how many times you create the object. At the first method you are declaring a constant outside the scope of class A, so basically, any class or function at the same scope has access to this variable, in your case it's not that bad because it's a constant, but suppose you have declared a variable with let in such case your problems begin to arise, the reason is that any class or function can reassign this variable with any value, thus causing side effects and bugs in your code, a silly example will clarify the things:

let x = 5

function isEven(value: number) {
    // here i'm overwriting the value of x
    x = 2

    return value % 2 === 0;
}

function destroyTheWorldIfEven(value: number) {
  if(isEven(value)){
      console.log("x is", x)
      console.log("you world has been destroyed")
      return
  }
  
  return console.log("you are safe")
}

// at the first call x is 5
destroyTheWorldIfEven(x)

// but at the second call x is 2 due the reassign in isEven function
destroyTheWorldIfEven(x)

So if you don't need to share the const X among the functions or classes, i don't see any reason to keep it outside the scope of class A, my suggestion is to keep things where they belong to, then:

  1. if const x is only used in one method of class A, keep it within the method.
  2. if const x is used by one or more methods from class A, keep it as a private attribute.
  3. if const x belongs to class A but must be accessed by other classes, keep it as a public attribute but avoid to define a setter method to it.

I will leave some good references for you:

Javascript scope

Javascript hoisting

Javascript closure

SOLID principles

This last one is one of most important in my opinion, mainly when you are using OOP, be sure to read it.

  • Related