Java变量声明

发布于 2024-10-16 00:05:25 字数 459 浏览 10 评论 0原文

好吧,这可能是基本的,但我想要好的程序员对此的意见。

处理小类文件中的变量的好方法是什么?

我喜欢模块化方法并保留做真正特定事情的方法。 我最终在这些方法之间传递变量。将多个方法中使用的变量作为成员变量是一个好习惯吗?或者将变量传递给方法更好?

例如:

class Test{
    somefunction(int a, int b, int c, int d) {
        doSomething(a, b, c);
        doOneMoreThing(a, c, d);
    }
    void doSomething(int a, int b, int c) { }
    void doOneMoreThing(int a, int c, int d) { }
 }

在上面的例子中,你认为变量应该保留为成员变量吗? 请解释为什么一种方法优于另一种。

Ok, this might be basic, but I want good programmers' opinions on this.

What is a good way to handle variables in a small class file?

I like modularizing methods and keeping methods that do really specific things.
I end up passing variables between those methods. Is it a good practice to make variables used across many methods as member variables? Or is it better to pass the variables to methods?

For example:

class Test{
    somefunction(int a, int b, int c, int d) {
        doSomething(a, b, c);
        doOneMoreThing(a, c, d);
    }
    void doSomething(int a, int b, int c) { }
    void doOneMoreThing(int a, int c, int d) { }
 }

In the above example, do you think the variables should be kept as member variables?
Please explain why one methodology is preferred over the other.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

不必你懂 2024-10-23 00:05:26

如果您不关心对象的状态,那么将变量传递给方法就可以了。在这种情况下,我会在方法上使用 static 修饰符,然后您不必实例化该类,并且可以像这样调用该方法:

Test.doSomething(1, 2, 3);

If you don't care about the state of the object, then passing the variables to the method is fine. In that case, I would use a static modifier on the method, then you don't have to instansiate the class and you can call the method like so:

Test.doSomething(1, 2, 3);
╄→承喏 2024-10-23 00:05:26
  • 实例变量:它们的值对于类的每个实例都是唯一的。当一个对象在堆中分配时,其中每个实例变量值都有一个槽。因此,实例变量在对象创建时创建,在对象销毁时销毁。
  • 类变量:类变量使用 static 关键字/修饰符声明。无论类实例化多少次,类变量都只有一份副本。它们存储在静态存储器中。
  • 局部变量:只能在声明它们的方法中访问。当进入一个方法时,一个区域被压入调用堆栈。该区域包含每个局部变量和参数的槽。当调用该方法时,参数槽被初始化为参数值。当方法退出时,该区域将从堆栈中弹出,并且内存可供下一个调用的方法使用。

如果要重用这些变量,则可以将它们声明为类变量。如果不是,那么它们应该是在各自方法中定义的局部变量。

  • Instance Variables: Their values are unique to each instance of a class. When an object is allocated in the heap, there is a slot in it for each instance variable value. Therefore an instance variable is created when an object is created and destroyed when the object is destroyed.
  • Class Variable: The Class variables are declared with a static keyword/modifier.There is only one copy of class variable no matter how many times the class is instantiated. They are stored in static memory.
  • Local variables: Only accessible within the method they are declared. When a method is entered, an area is pushed onto the call stack. This area contains slots for each local variable and parameter. When the method is called, the parameter slots are initialized to the parameter values. When the method exits, this area is popped off the stack and the memory becomes available for the next called method.

If you are going to reuse the variables, then you can declare them as class variables. If not, then they should be local variables defined in their respective methods.

咿呀咿呀哟 2024-10-23 00:05:26

首先, Somefunction(... } 是一个语法错误。其次,方法名称应该以小写字母开头,类名称应该以大写字母开头。第三,我们不知道什么是最好的方式是不知道这些方法的作用、用途以及参数来自哪里

First of all Somefunction(... } is a syntax error. Second, method names should start with lower case letters, and class names should start with upper case. Third, we have no idea what the best way is without knowing what these methods do, what they're used for, and where their parameters come from

不气馁 2024-10-23 00:05:26

取决于您需要更改代码的频率(或者您应该在设计时考虑更改代码的频率)。如果签名发生变化,您必须在很多地方进行更改。这意味着即使您重构签名,也需要测试更多代码。我会在创建成员变量和封装方面犯错误。

Depends on how often you have to change your code (or you should think about how often you're going to change it when you design it). If the signature changes you have to change it in a lot of places. That means more code to test even when you refactor the signature. I would err on the side of creating member variables and encapsulating.

不打扰别人 2024-10-23 00:05:25

您是否需要在方法调用之间保留变量并重用它们的值?如果是这样,他们就应该是班级成员。 (至少在某些类别中 - 不一定是这个类别。)

否则,这在某种程度上是一个品味问题。一个重要因素是,局部变量不会向对象添加状态,但如果同时使用,这会很有用。将所有变量保持在本地甚至可以使您的类不可变,这通常使其自动成为线程安全的。但即使在单线程环境中,不可变类也更容易理解和维护。

OTOH 传递大量参数可能会很尴尬。您可以考虑引入参数对象来缓解此问题。

Do you need to keep the variables around between method calls, and reuse their value? If so, they should be class members. (At least in some class - not necessarily this one.)

Otherwise it is somewhat a matter of taste. One important factor is though that local variables don't add state to the object, which can be useful if it is used concurrently. Keeping all variables local may even allow you to make your class immutable, which usually makes it automatically thread-safe. But even in a single-threaded environment an immutable class is easier to understand and maintain.

OTOH passing lots of parameters around can be awkward. You may consider introducing a Parameter Object to alleviate this problem.

抚你发端 2024-10-23 00:05:25

如果我有一些变量最终会传递给一堆私有方法,我通常会将它们移动到私有内部工作类中。

相反,

class Foo {
  public doSomething(...) {
    // some setup
    doSomethingRecursively(a, b, c);
  }

  private void doSomethingRecursively(A a, B b, C c) {
    if (baseCase) { ... }
    doSomethingRecursively(a + 1, b, c);
  }
}

我会将永远不会改变的变量移至工作人员的属性中。

class Foo {
  public doSomething(...) {
    // some setup
    new AppropriatelyNamedHelper(b, c).doSomethingRecursively(a);
  }

  private static final class AppropriatelyNamedHelper {
    final B b;
    final C c;

    AppropriatelyNamedHelper(B b, C c) {
      this.b = b;
      this.c = c;
    }

    void doSomethingRecursively(A a) {
      if (baseCase) { ... }
      doSomethingRecursively(a + 1);
    }
  }
}

这使得审阅者清楚每个范围内哪些内容在该范围内是不变的。

If I have some variables that I would end up passing to a bunch of private methods, I'll often move them into a private inner worker class.

Instead of

class Foo {
  public doSomething(...) {
    // some setup
    doSomethingRecursively(a, b, c);
  }

  private void doSomethingRecursively(A a, B b, C c) {
    if (baseCase) { ... }
    doSomethingRecursively(a + 1, b, c);
  }
}

I'll move the variables that never difference into properties on a worker.

class Foo {
  public doSomething(...) {
    // some setup
    new AppropriatelyNamedHelper(b, c).doSomethingRecursively(a);
  }

  private static final class AppropriatelyNamedHelper {
    final B b;
    final C c;

    AppropriatelyNamedHelper(B b, C c) {
      this.b = b;
      this.c = c;
    }

    void doSomethingRecursively(A a) {
      if (baseCase) { ... }
      doSomethingRecursively(a + 1);
    }
  }
}

This makes it clear to a reviewer what in each scope is invariant within that scope.

南七夏 2024-10-23 00:05:25

成员变量应该存在来维护类中的某种状态。如果你的类维护状态,那么一定要为你需要跟踪的那些东西定义成员变量。如果一个类不维护状态,那么就没有理由让事物成为成员(我不得不调试遗留代码,其中变量不应该成为成员,但在多次调用对象时会导致错误,因为状态是不可预测)。

然而,虽然您可能喜欢“模块化”功能,但请阅读耦合与内聚的关系。在类中具有过多的功能但较少的依赖项与具有很少但高度特定的功能和大量的依赖项之间需要取得平衡。

Member variables should exist to maintain some kind of state in a class. If your class maintains state then definitely define member variables for those things you need to track. If a class does not maintain state then there is no reason to make things members (I have had to debug legacy code where variables should not have been made members but were and it was causing errors when making multiple calls to the object because the state was unpredictable).

However, while you might like "modularizing" functionality, read up on coupling vs. cohesion. There is a balance to be struck between having too much functionality in a class but fewer dependencies and having very little but highly specific functionality and lots of dependencies.

与风相奔跑 2024-10-23 00:05:25

拥有无用的成员变量通常被认为是糟糕的设计。
但是,如果您在许多方法中使用多个变量集,则可以(并且应该)将多个变量集组合到一个新类中。

Having useless member variables is usually regarded to as bad design.
But you can (and should) combine multiple variable sets into a new class if you use that variables in lots of methods.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文