Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP - best approach for adding property to class

We develop an HR application written in Java and mapped with Hibernate; one of the feature is the phase of recruiting.

The Candidate class is modeled like this:

public class Candidate  {
    private String id;
    private Integer candidateCode;
    private GregorianCalendar birthDate;
    private String italianFiscalCode; //unique code for italian people 
}

Since we developed for a market only till now the code is very dependent on a particular legislation, look at the fiscalCode class property.

The request is that we generalize this concept to be able to expand to other markets, where for example the unique identifier can be different, can be composed of several strings or be absent at all.

First thing that popped in my mind:

1 - Simply rename the field as countryIdentifier and add other fields if needed for particular countries.

private String countryIdentifier; //general unique code
private Integer greekAddedCode;   

This means refactoring the code where needed (all the placed where the old italianFiscalCode gets used), renaming a DBMS column (and adding others eventually) and modifying all the queries that use that field.

This looks like a poor implementation to me

2 - Subclass Candidate creating ItalianCandidate and GreekCandidate and move the particular field in the subclasses.

The problem is that the Candidate class is already subclassed by HeavyCandidate that has the sole function to optimize the Hibernate mapping since we move all the "heavy" properties (many-to-ones and sets) in the heavy class (this is an approach that we follow with all our beans).

In this situation what is the most correct approach?

like image 373
frankieta Avatar asked Nov 20 '16 21:11

frankieta


1 Answers

I would create an interface Identifier (not sure about the name) that is implemented by classes like GreekIdentifier and ItalianIdentifier. Then I'd add a field to Candidate:

Identifier identifier;

The implementation of GreekIdentifier would then look something like this:

public class GreekIdentifier implements Identifier {
    String countryIdentifier;
    int addedCode;

    //constructor, getters, setters ...
    //actual behaviour, Indentifier @Overrides ...
}

If countryIdentifier is really something that all Identifiers have, you can even move it up to an (abstract) base class.

like image 111
Todd Sewell Avatar answered Nov 13 '22 05:11

Todd Sewell