代码重构优化-不要用过多的if嵌套

不要用过多的if嵌套

重构前:

def project_version(request,group_name,branch_name,project_name):
    if branch_name and group_name and project_name:
     project_name_with_namespace = '%s/%s' %(group_name,project_name)
      project = gl.projects.get(project_name_with_namespace)
      if project:
         branches = []
           branch = project.branches.list()
            if branch:
              branches = []
               branch_name_find = '%s-' %(branch_name)
               for branch_name_in in branch:
                   if (branch_name_in.name.find(branch_name_find) != -1):
                      branches.append(branch_name_in.name.split('-')[1])
                project_branch = '\\n'.join(branches)
             print(project_branch)
               return HttpResponse(project_branch)
         else:
               return HttpResponse("error")
      else:
           return HttpResponse("error")
  else:
       return HttpResponse("error")

重构,把可能返回错误的情况先写出来返回

def project_version(request,group_name,branch_name,project_name):
 if not branch_name or not group_name or not project_name:
       return HttpResponse("error")
  project_name_with_namespace = '%s/%s' %(group_name,project_name)
  project = gl.projects.get(project_name_with_namespace)
  if not project:
     return HttpResponse("error")
  branches = []
   branch = project.branches.list()
    if not branch:
      return HttpResponse("error")
  branches = []
   branch_name_find = '%s-' %(branch_name)
   for branch_name_in in branch:
       if (branch_name_in.name.find(branch_name_find) != -1):
          branches.append(branch_name_in.name.split('-')[1])
    project_branch = '\\n'.join(branches)
 if not project_branch:
      return HttpResponse("error")
  return HttpResponse(project_branch)