B
B
Ben L2021-06-26 07:51:02
OOP
Ben L, 2021-06-26 07:51:02

Is it bad practice to change an object indirectly?

Is it bad to do that?

class Position {
    private x: number;
    private y: number;
    
    constructor(x: number, y: number) {
        this.to(x, y);
    }
    
    public to(x: number, y: number): void {
        this.x = x;
        this.y = y;
    }

    // ...
}

class Character {
    private name: string;
    private position: Position;
    
    constructor(name: string, position: Position) {
        this.name = name;
        this.position = position;
    }
    
    // ...
}

const p = new Position(0, 0);
const character = new Character('Darth Vader', p);
p.to(10, 10);


It turns out I change characterwithout doing anything with it. Is it worth it to do so or not? Does it violate any principle?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DollyPapper, 2021-06-26
@DollyPapper

Violate the principle of encapsulation at least. Make a composition so that the initial position of the character is passed to the constructor, and a method to change this position for the character itself. Now you have p
not a character property, but a separated property in scope, although logically it is a character property.

R
rPman, 2021-06-26
@rPman

I agree with DollyPapper 's answer , but formally it is possible to do this.
For example, if you teach the Position object to report actions on itself to its owners by creating an abstract class CanHavePosition with a virtual method doMoving that must be implemented in the Character class (which you inherit from CanHavePosition) and called on each Position::to movement (decoration methods may be different, for example, on the contrary, in the Character constructor, the init method of Position will be called with a callback that will be called inside Position::to), then such a design as you will be justified.
Of course, there is no need to do this all the time, and there is no need to strictly follow the guidelines, although they are 'written in blood and scraps of shit code', you can always find a situation where over engineering is not needed.
Ultimately, all the syntactic sugar and features of the language are designed to make things easier for developers and reduce the chances of them making mistakes in the code, and you can always find a limit when you don’t have to do work for the sake of work, but do everything for the result.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question