有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在变量和方法名中使用下划线

我对(命名约定)在变量名和方法名中使用下划线_作为起始字母感到困惑。例如_sampleVariable_getUserContext()。谁能澄清一下什么时候使用它吗


共 (5) 个答案

  1. # 1 楼答案

    通常在变量中使用u,将它们表示为类级私有变量

  2. # 2 楼答案

    参见Java Naming Convetions

    Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.

    The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

  3. # 3 楼答案

    通常不应使用,除非在所有大写常量中用作分隔符,这些大写常量通常是最终的(allStars但all_STARS)

    正是因为通常不需要下划线,所以生成的代码中有大量的下划线。它也可以在一些旧代码中找到,这不是继续使用它的原因

  4. # 4 楼答案

    引用罗伯特·C·马丁的《清洁代码》一书

    Sometimes it is useful to warn other programmers about certain consequences.

    范例

    // Don't run unless you
    // have some time to kill.
    public void _testWithReallyBigFile() {
    writeLinesToFile(10000000);
    response.setBody(testFile);
    response.readyToSend(this);
    String responseString = output.toString(); assertSubString("Content-Length: 1000000000", responseString); assertTrue(bytesSent > 1000000000);
    }
    

    Nowadays, of course, we’d turn off the test case by using the @Ignore attribute with an appropriate explanatory string. @Ignore("Takes too long to run"). But back in the days before JUnit 4, putting an underscore in front of the method name was a common convention.

  5. # 5 楼答案

    有时人们使用下划线来表示他们的变量或方法是私有的。我不喜欢这样做。我建议你也使用camelCase