Task 6: Refactor to DRY the Support Classes
Review the code in the Employer, Location, CoreCompetency, and PositionType classes. What similarities do you see?
There is a fair amount of repetition between the classes. As a good coder, anytime you find yourself adding identical code in multiple locations you should consider how to streamline the process.
DRY = “Don’t Repeat Yourself”.
Create a Base Class
Let’s move all of the repeated code into a separate class. We will then have Employer
, Location
, CoreCompetency
, and PositionType
inherit this common code.
Create a new class called
JobField
in the packageorg.launchcode.techjobs.oo
.Consider the following questions to help you decide what code to put in the
JobField
class:- What fields do ALL FOUR of the classes have in common?
- Which constructors are the same in ALL FOUR classes?
- What getters and setters do ALL of the classes share?
- Which custom methods are identical in ALL of the classes?
In
JobField
, declare each of the common fields.Code the constructors.
Use Generate to create the appropriate getters and setters.
Add in the custom methods.
Finally, to prevent the creation of a
JobField
object, make this class abstract.
Extend JobField into Employer
Now that you have the common code located in the JobField
file, we can modify the other classes to reference this shared code. Let’s begin with Employer.
Modify line 5 to extend the JobField
class into Employer
.
|
|
Next, remove any code in
Employer
that matches code fromJobField
(e.g. theid
,value
, andnextId
fields are shared).Remove any of the getters and setters that are the same.
Remove any of the custom methods that are identical.
The empty constructor is shared, but not the second. Replace the two constructors with the following:
7 8 9
public Employer(String value) { super(value); }
The
extends
andsuper
keywords link theJobField
andEmployer
classes.Rerun your unit tests to verify your refactored code.
Finish DRYing Your Code
Repeat the process above for the Location
, CoreCompetency
, and PositionType
classes.
Rerun your unit tests to verify that your classes and methods still work.
You know you need to do this, but here is the reminder anyway. Save
, commit
, and push
your work to GitHub.