dimanche 22 novembre 2020

Better Approach than If

I have some Optional parameters in my application and I have to mount command with these parameters, so, now I'm using IF

class MergeBuilder(mergeBuilderConfig: MergeBuilderConfig) {

  def makeMergeCommand(): DeltaMergeBuilder = {

    val mergeSintax = mergeBuilderConfig.primaryKey
      .map(column => s"destination.$column = updates.$column")
      .mkString(" and ") + (if (!mergeBuilderConfig.partitionFilter.isEmpty) {
                              " and " + mergeBuilderConfig.partitionFilter
                            } else {
                              ""
                            })

    val mergeCommand =
      mergeBuilderConfig.deltaTable.alias("destination").merge(mergeBuilderConfig.sparkDf.alias("updates"), mergeSintax)

    if (mergeBuilderConfig.operationType == "upsert" && mergeBuilderConfig.setExpression.isEmpty) {
      mergeCommand
        .whenMatched(condition = mergeBuilderConfig.updateCondition.get)
        .updateAll(
        )
        .whenNotMatched()
        .insertAll()
    } else if (mergeBuilderConfig.operationType == "upsert" && !mergeBuilderConfig.setExpression.isEmpty) {
      mergeCommand
        .whenMatched(condition = mergeBuilderConfig.updateCondition.toString)
        .updateExpr(set = mergeBuilderConfig.setExpression.get)
    } else {
      mergeCommand.whenNotMatched().insertAll()
    }
  }
}

I will have more command Options, Do you have any idea how to avoid these Ifs?

Aucun commentaire:

Enregistrer un commentaire