Variables in Functions

Aim for variable names to make sense throughout duration of function

Let's take a look at the following BASH function, which at first glance appears to have decent naming:

# Function to rename the current GIT branch
git.branch.rename(){
  git.verify.is_clean
  git.verify.not_on.default_branch

  local new_branch_name="${1:?new branch name is required argument}"

  local current_branch
  current_branch="$(git.current_branch)"

  eai git.checkout.new_branch "${new_branch_name:?}"

  eai git branch -d "${current_branch:?}"
}

However, when we take a closer look we see that current_branch caches the value of the branch right before we switch out of that branch. Hence, current_branch cached value is misleading within this function. And would be better served if it was renamed/refactored to something like starting_branch which is a valid name for duration of the function

git.branch.rename(){
  git.verify.is_clean
  git.verify.not_on.default_branch

  local new_branch_name="${1}"

  local starting_branch
  starting_branch="$(git.current_branch)"

  eai git.checkout.new_branch "${new_branch_name:?}"

  eai git branch -d "${starting_branch:?}"
}

Full function example

Example full function: git.branch.rename
git.branch.rename(){
  # Ensure the repository is in a clean state and not on the default branch.
  git.verify.is_clean
  git.verify.not_on.default_branch

  local new_branch_name="${*:?new-branch-name}"
  new_branch_name="$(strings.to_kebab_case "${new_branch_name:?}")"

  local starting_branch
  starting_branch="$(git.current_branch)"

  # Create and checkout the new branch.
  eai git.checkout.new_branch "${new_branch_name:?}"

  # Retrieve commit hashes for starting branch and new branch.
  local starting_commit new_commit
  starting_commit="$(git rev-parse "${starting_branch:?}")"
  new_commit="$(git rev-parse "${new_branch_name:?}")"

  # Ensure both branches point to the same commit.
  if [ "${starting_commit}" != "${new_commit}" ]; then
    throw "Error: new branch [${new_branch_name}] is not pointing to the same commit as starting branch [${starting_branch}]" >&2
  fi

  # Force-delete the starting branch even if it's not fully merged.
  eai git branch -D "${starting_branch:?}"
}

References


Children
  1. Variable names to be VALID for Entire Duration of Function

Backlinks