在将变量作为参数提供之前声明变量是 Java 中的最佳实践吗

fac*_*eID -2 java variables final

假设这个代码:

public static Dataset<Row> getData(SparkSession sparkSession,
                                             StructType schema, String delimiter, String pathToData) {

    final Dataset<Row> dataset = sparkSession
            .read()
            .option("delimiter", "\\t")
            .csv(pathToData);

    StructType nSchema= newSchema(schema, schema.size(), dataset.columns().length);
 ...
}
Run Code Online (Sandbox Code Playgroud)

在将变量提供给 newSchema 方法之前声明变量并使它们成为 final 是最佳实践吗?

public static Dataset<Row> getData(SparkSession sparkSession,
                                             StructType schema, String delimiter, String pathToData) {

    final Dataset<Row> dataset = sparkSession
            .read()
            .option("delimiter", "\\t")
            .csv(pathToData);

    final int dataSize = dataset.columns().length;
    final int schemaSize = schema.size();

    StructType nSchema = newSchema(schema, schemaSize, dataSize);
 ...
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Tom*_*ine 6

这是一个品味问题。

引入局部变量允许您命名概念。有更简单的陈述。简化内部循环。在不引入新功能的情况下可能删除通用代码。

另一方面。命名很难。如果你把它全部放在一行上,代码会更短。如果代码不依赖于太多局部变量,那么分解代码可能会更容易。

final 对于当地人来说可能是最重要的,除非代码已经一团糟。