Java Instance Variables vs Local Variables

后端 未结 10 2125
庸人自扰
庸人自扰 2020-11-30 01:11

I\'m in my first programming class in high school. We\'re doing our end of the first semester project. This project only involves one class, but many methods. My question is

10条回答
  •  孤街浪徒
    2020-11-30 02:05

    Try not to return more than one value from your methods in first place. If you can't, and in some cases you really can't, then I would recommend encapsulating that in a class. Just in last case I would recommend changing another variable inside your class (an instance variable). The problem with the instance variables approach is that it increases side effects - for example, you call method A in your program and it modifies some instance(s) variable(s). Over time, that leads to increased complexity in your code and maintenance becomes harder and harder.

    When I have to use instance variables, I try to make then final and initialize then in the class constructors, so side effects are minimized. This programming style (minimizing the state changes in your application) should lead to better code that is easier to maintain.

提交回复
热议问题