Skip to main content

Practice Code Structure

Section 1.20 Code Refactoring

Activity 1.20.1.

There is a copy of the following code block in an interactive mode that you can modify and compile. Your task is to improve the code’s style as an expert would view it, while ensuring its behavior remains unchanged. You may run your refactored code to verify that it still passes all test cases.
public class Internship { 
	public static String checkInternshipEligibility(int schoolYear, double GPA, boolean hasWorkExperience) {
		if (schoolYear >= 4) {
			if (GPA >= 3.5) {
		    	if (hasWorkExperience) {
		        	return "Eligible";
		    	} else {
		        	return "You only need some work experience!";
		    	}
			}
		}
		return "Not eligible";
	}
}

Activity 1.20.2.

    Which of the following code blocks is the most similar to your final refactored code for the previous question?
  • public class Internship {
      public static String checkInternshipEligibility(int schoolYear, double GPA, boolean hasWorkExperience) {
        if (schoolYear >= 4 && GPA >= 3.5 && hasWorkExperience) {
          return "Eligible";
        } else {
          return "You only need some work experience!";
        }
        return "Not eligible";
      }
    }
    
  • This code does not compile because the last return statement is unreachable (it never executes). Copy the original code into the interactive section and try refactoring it again.
  • public class Internship {
      public static String checkInternshipEligibility(int schoolYear, double GPA, boolean hasWorkExperience) {
        if (schoolYear >= 4 && GPA >= 3.5 && hasWorkExperience) {
          return "Eligible";
        }
        return "Not eligible";
      }
    }
    
  • The code doesn’t have the same functionality with the original one. Copy the original code into the interactive section and try refactoring it again.
  • public class Internship {
      public static String checkInternshipEligibility(int schoolYear, double GPA, boolean hasWorkExperience) {
        if (schoolYear < 4 || GPA < 3.5) {
          return "Not eligible";
        }
        if (hasWorkExperience) {
          return "Eligible";
        }
        return "You only need some work experience!";
      }
    }
    
  • You did it correctly!
  • public class Internship {
      public static String checkInternshipEligibility(int schoolYear, double GPA, boolean hasWorkExperience) {
        if (schoolYear >= 4 && GPA >= 3.5) {
          if (hasWorkExperience) {
            return "Eligible";
          } else {
            return "You only need some work experience!";
          }
        }
      return "Not eligible";
      }
    }
    
  • This code still has a nested ifs and can be improved further!
You have attempted 1 of 3 activities on this page.