L
L
Lev Aleksandrov2021-07-02 15:48:02
OOP
Lev Aleksandrov, 2021-07-02 15:48:02

Do all fields of a class need to be encapsulated?

Hello.
The question is actually all in the title.
Let's say there is a Player class (pseudocode):

class Player {
    string name;
    int cash;
    int level;
}

Should I create set and get functions like .getCash(), setName(), etc. for each field, even if no further action is taken?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
HemulGM, 2021-07-02
@h3ckphy

What for?

I
Ilya, 2021-07-02
@sarapinit

Depends on how the class will be used.
One of the purposes of encapsulation is to reduce the likelihood that a class/module/function will be misused. In the extreme case, the class api should only allow correct usage. But the language does not always allow this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question