Home > Software design >  Suggest how to write this more compact
Suggest how to write this more compact

Time:06-11

Many equal properties names in this code. Is it possible to make it a lot compact ?

constructor(product) {
    this.session = SessionBuilder.create();
    this.id = product.id;
    this.name = product.name;
    this.root = product.root;
    this.pics = product.pics;
    this.sizes = product.sizes;
    this.colors = product.colors;
    this.rating = product.rating;
    this.feedbacks = product.feedbacks;
}

I found only one solution with getters.

constructor(product) {
    this.session = SessionBuilder.create();
    this.product = product;
}

get id() {
    return this.product.id;
}

get name() {
    return this.product.name;
}

...

But i don't really like it. It looks better (for me), but code would be a lot more... Can someone suggest a better solution?

CodePudding user response:

You could use a table-driven approach to safely copy only a known set of properties without having to name the properties more than once:

const propNames = ["id", "name", "root", "pics", "sizes", "colors", "rating", "feedbacks"];

class Whatever {
    
    constructor(product) {
        this.session = SessionBuilder.create();
        for (let prop of propNames) {
            this[prop] = product[prop];
        }
    }
    ...
}

If you just want to copy all properties from the product variable, you can use Object.assign():

class Whatever {
    
    constructor(product) {
        this.session = SessionBuilder.create();
        Object.assign(this, product);
    }
    ...
}

But, this is less safe as people could put anything in the product object, including things that might even override your own methods or properties besides the once you intended.


You can see solutions using object destructuring assignment here in this question: Is it possible to destructure onto an existing object?, but I didn't see any solutions there that are simpler than these.

  • Related