Object-oriented field programming private class field + get / set or public class field?

I am a junior developer (currently doing Java), and I have one question about the correctness of my code, here is an example: I am writing a simple representation of an MMO game in Java, I have 2 classes (character and spell). The Character property has properties (mName, mHealth and mEnergy), the spell class has properties (mSpellName, mSpellCost, mSpellDamage). And in the Spell class there is also a method called execute, here is the code

public void spellExecute(Character caster, Character target) {
caster.mEnergy -= this.spellCost;
target.mHealth -= this.spellDamage
}

This design assumes that the character fields are public and can be accessed directly, but in some examples that I saw that all fields must be private and can only be accessed using get / set methods. My question is: which path is more correct in general? This is important to me because I want to write good code :)

+4
source share
7 answers

Generally, you should use get / set methods because they allow the class to control access through these methods

Any other class that your class uses should only have access to your fields and modify them as you describe.

, ()

class Pump
{
    constant int PRICE_PER_LITRE = 100; //in pence

    private int litresDispensed;
    private bool nozzleUp;
    private int litresAvailable;
    private int price; //in pence

    construct()
    {
        litresDispensed = 0;
        nozzleUp = false;
    }

    startFuelling()
    {
        nozzleUp = true;
    }

    stopFuelling()
    {
        nozzleUp = false;
    }

    takeFuel(int litresTaken)
    {
        if(nozzleUp = true)
        {
            litresAvailable -= litresTaken;
            price += litresTaken * PRICE_PER_LITRE;
        }
        else
        {
            error("You must lift the nozzle before taking fuel!");
        }
    }

    getPrice()
    {
        if(nozzleUp = true)
        {
            error("You can't pay until you've finished fuelling! Please return the nozzle");
        }
        else
        {
            return price;
        }
    }
}

, , .

, , ! .

, get . , , . , : , , , !

get/set, , - , (, , , ): get/set, , .

+2

, , - .

spellExecute , Character:

public void didUseSpell(Spell spell) {
    this.mEnergy -= spell.spellCost;
}

public void wasHitBySpell(Spell spell) {
    this.mHealth -= spell.spellDamage;
}

:

public void spellExecute(Character caster, Character target) {
    caster.didUseSpell(this);
    target.wasHitBySpell(this);
}

, , . getter setter , .

+2

Getters/seters , , . private , set .

+1

Getter setter (Java bean) . . .

  private int id;

    public int getId() {
            return id;
    }

    public void setId(int id) {
           this.id = id;
    }

. , setter .

+1

. , , API.

public class Dummy{
 public int age;
}

new Dummy().age = -1

public class Dummy{
   private int age;
   public void setAge(int age){
      if (age < 0){
       throw new RuntimeException("you are not allowed to do this");
   }
   ......
}

, Hibernate, IBATIS .., . , .

+1

Getters seters - , , ?

, , . - :

public void reduceMentalHealth(int val) {
  if(this.mHealth > val) {
    this.mHealth -= val;
  } else {
    this.mHealth = 0;
}

, . , , : -)

0

.


:

[1] ( "getter" (s) "" setter "(s)).

[2] , ?


[1] ( "getter" (s) "" setter "(s)).

Go, " " a.k.a. "getter (s) setter (s)". , , .

[2] , ?

" " , "" , "private" "protected". " ", "" , "" "" .


[1] ( "getter" (s) "" setter "(s)).

Go, " " a.k.a. "getter (s) setter (s)".

, , .

, , , .

" " .

[2] , ?

" " , "" , "private" "protected".

" ", "" , "" "" .

"" accesors, - , .

:

public class ControlClass {
    // example of non private field (s)
    protected String controlname;

    // ...

    // example of non private field (s)
    protected int width;
    protected int height;

    // ...

    // example of read-only property
    public final String getControlName()
    {
        return this.controlname;
    } // String getControlName(...)

    // ...

    @Override
    public int getWidth()
    {
        return this.width;
    } // int getWidth(...)

    @Override 
    public void setWidth(int newvalue)
    {
        this.width = newvalue;
    } // void setWidth(...)

    @Override
    public int getHeight()
    {
        return this.height;
    } // int getHeight(...)

    @Override 
    public void setHeight(int newvalue)
    {
        this.height = newvalue;
    } // void setHeight(...)

    // ...

    // constructor assigns initial values to properties' fields
    public ControlClass(){
        this.controlname = "control";
        this.height = 0;
        this.width = 0;
    } // ControlClass(...)

    // ...
} // class ControlClass

public class ButtonClass extends ControlClass {
    // ...

    // example of overriden public property with non public field
    @Override
    public int getWidth()
    {
        if (this.width < 5)
          return 5
        else
          return this.width;
    } // int getWidth(...)

    // example of overriden public property with non public field
    @Override 
    public void setWidth(int newvalue)
    {
        if (newvalue < 5)
          throw new ArithmeticException("integer underflow");

        this.width = newvalue;
    } // void setWidth(...)

    // example of overriden public property with non public field
    @Override
    public int getHeight()
    {
        if (this.height < 5)
          return 5
        else
          return this.height;
    } // int getHeight(...)

    // example of overriden public property with non public field
    @Override 
    public void setHeight(int newvalue)
    {
        if (newvalue < 5)
          throw new ArithmeticException("integer underflow");

        this.height = newvalue;
    } // void setHeight(...)

    // ...

    // constructor assigns initial values to properties' fields
    public ControlClass(){
        this.controlname = "ButtonClass";
        this.height = 5;
        this.width = 5;
    } // ButtonClass(...) 

    // ...
} // class ControlClass

"private" , , , , , , "", . .


.

- , "", .

, Object Pascal (a.k.a. "Delphi" ), ECMAScript ( "Javascript" ), ++, #. , Delphi # " ", , Object and Class Oriented Software Application.

Java?

Java ++, , # Delphi, , , , .


.

0

All Articles