What are the alternatives to public fields?

前端 未结 12 2524
刺人心
刺人心 2021-02-19 15:05

I am programming a game in java, and as the question title suggestions i am using public fields in my classes. (for the time being)

From what i have seen public fields a

12条回答
  •  一向
    一向 (楼主)
    2021-02-19 15:52

    If you have a private field with a method get() and a method set() that don't do anything other than retrieve and assign the value, you should just make the field public, as the field isn't really private, and the getters and setters only hurt performance. If the getters and setters check the value being set or if the value is allowed to retrieve, then go ahead and use getters and setters. e.g. If you have a variable private int width; and someone tries to put in -1 with a setter, and the setter makes sure it isn't negative, then that is a good use. For example:

    private int width;
    public int get(){
        return width;
    }
    public void set(int w){
        if (w < 0) throw new RuntimeException();
        else width = w;
    }
    

    This would be a good use of getters and setters. Otherwise, they hurt your performance if the only thing they do is assign or get the value without anything else.

    So to make a long story short:

    Use getters and setters when doing anything other than retrieving or assigning a value. Else, just use public fields.

    i.e.

    BAD:

    private int width;
    public int get(){
        return width;
    }
    public void set(int w){
        width = w;
    }
    

    GOOD:

    private int width;
    public int get(){
        return width;
    }
    public void set(int w){
        if (w < 0) throw new RuntimeException();
        else width = w;
    }
    

    GOOD if you don't want anything other than getting or setting:

    public int width;
    

提交回复
热议问题