Search code examples
javavariablesfinal

Is it a best practice in Java to declare variables before give them as parameters


Assuming this code :

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);
 ...
}

Is it a best practice to declare variables and make them final before giving them to newSchema method, like this ?

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);
 ...
}

Thank you


Solution

  • It's a matter of taste.

    Introducing local variables allows you to name concepts. Have simpler statements. Simplify inner loops. Potentially remove common code without introducing new functions.

    On the other hand. Naming is hard. The code will be shorter if you bung it all on one line. It may be easier to factor out code if it is not dependent on too many local variables.

    final for locals is probably over the top, unless the code is already a mess.