vendredi 14 juin 2019

Correct approach(design pattern) for update fields in java object

I have java class Person:

public class Person {
    private String name;
    private int age;
    private String marriedStatus;
    private Date dob;
    //getters and setters
}

When I get new values for some fields of this object I can update it. But new fields values income in this format: Map<String, String> newValues where key - field number and value - the value of the field. I create this service:

public class UpdateService {
    public Person updateFields(Person targetPerson, Map<String, String> newValues){
        return null;
    }
}

I create a unit test and ask you to help implement this.

public class UpdateServiceTest {

    /*associations between field number and field name
    12 - name (length min: 2, max: 20. First letter must uppercase )
    18 - marriedStatus (only married, divorced, single)
    21  - age (only between 18 and 120)
    14  - dob (some format)
     */

    private Date dob;

    @Before
    public void setUp() {
        dob = new GregorianCalendar(2000, Calendar.NOVEMBER, 20).getTime();
    }

    @Test
    public void returnPersonWithUpdatedFields() {
        UpdateService updateService = new UpdateService();

        Person targetPerson = new Person();
        targetPerson.setName("Name");
        targetPerson.setMarriedStatus("MarriedStatus");
        targetPerson.setAge(20);
        targetPerson.setDob(dob);

        Map<String, String> newValues = new HashMap<String, String>();
        newValues.put("12", "Bill");
        newValues.put("18", "married ");
        newValues.put("21", "25");

        Person person = updateService.updateFields(targetPerson, newValues);

        assertEquals("Bill", person.getName());
        assertEquals("married", person.getMarriedStatus());
        assertEquals(25, person.getAge());
        assertEquals(dob, person.getDob());
    }
}

I need to get the person and update only fields which income in Map<String, String> newValues. And validate it.

Aucun commentaire:

Enregistrer un commentaire