Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not using set and get methods in Java when there are many attributes

So I have been learning about OOP. I am currently trying to create simple "Hero Profiles" with HP, Mana, intelligence, strength, agility, armor etc. As you can see, there are a lot of attributes I want to add to Hero objects. But these attributes are declared in private not public (Because I was told that it was best to declare these private) and when I declare them in private I have to form set and get methods to each of these attributes. And it consumes so much time and I feel like it is not practical.

Is there a more practical way? Do coders really type these get and set methods even though there are a dozen of them? All I want to do is create two Hero Profiles with these attributes and then simulate a 1v1 battle between the two.

like image 269
Huzo Avatar asked Feb 05 '26 19:02

Huzo


1 Answers

Whoever told you, that individual attributes of the object should be private was absolutely right!

One of the basic principles of OOP is Encapsulation. Simply put, it means that the internal structure of the object (the "fields") should be hidden. This is the most important aspect of OOP, from which most of the advantages of OOP come from.

Now, accessor methods (setters and getters) violate encapsulation, the same way just making them public does, since you are no longer hiding the internal structure. It is not just about protecting internal fields, it's about hiding them.

Unfortunately accessor methods are a common idiom in Java (and C# too), but if you are serious about learning OOP, you should avoid them at all costs! Later, when you have more experience, you might make exceptions in a few cases, but I would urge you just avoid them for now. Avoid Project Lombok and avoid IDE features to auto-generate stuff.

Here is a brilliant article from Allen Holub on the subject.

Back to your actual question: Yes, you declare your fields private, but you don't define setters/getters for them at all. What we do instead, is think about what responsibilities/features/functions/logic the object should have.

So instead of thinking about the stats, think about what you are using those stats for. An object-oriented Hero might look like this then:

public final class Hero {
    private int hp;
    private int strength;
    private int agility;
    private int armor;
    ...

    public void dealDamageTo(Hero other) {
        other.takeDamage(stength);
    }

    public void takeDamage(int damage) {
        hp = hp - Math.max(0, damage-armor);
    }
    ...
}

Of course, that's only an example, but you probably get the point. There's no need at all to publish the internal fields at all, if your design is right.

like image 128
Robert Bräutigam Avatar answered Feb 09 '26 08:02

Robert Bräutigam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!