Java define class members by a final array

114 views Asked by At

I have an array which contains some definitions which are used in the program:

final String[] names = new String[]{"familyNames", "givenNames", "middleNames", "nickNames", "additionalNames", ..., ..., ..., ...}; // Lots of definitions

And now I need to create a new class with these definitions:

public class Person {
  final private String id;
  final private String familyNames;
  final private String givenNames;
  final private String middleNames;
  final private String nickNames;
  final private String additionalNames;
  ...
  ...
  ...
  ...
  ... // Very long list
}

Is it possible to define this class by that array? Something like:

public class Person {
  final private String id;
  final private .... names...
  public int compareTo(...) {...}
}

This Person class should support sort by multi fields, e.g. first by given name, then by family name, etc.

2

There are 2 answers

2
Juned Ahsan On

To avoid a long list of class member variables, you may use a map of attributes as mentioned here:

Map<String,String> attributesMap = new HashMap<String,String>();

"familyNames", "givenNames", "middleNames", "nickNames", "additionalNames", etc should be used as keys.

3
aquaraga On

You could define it in a class Person by taking the attributesMap in a static factory method.

public class Person {
  final private String id;
  final private Name name;
  ...
  public static Person fromAttributesMap(Map<String, String> attributesMap) {
      Person person = new Person();
      person.id = attributesMap.get("id");
      ...
  }
}

But do keep related attributes together in their own classes. For eg; you could club familyName, givenName, nickName, etc. in a Name class:

class Name {
  final private String familyName;
  final private String givenName;
  final private String middleName;
}

I'm not in full agreement to the map approach. Infact, there is a code smell around the same - it is called "Primitive obsession"

You could also sort a List<Person>, for example by the family name:

public static Comparator<Person> FamilyNameComparator 
                      = new Comparator<Person>() {

    public int compare(Person person1, Person person2) {


      //ascending order
      return person1.getFamilyName().compareTo(person2.getFamilyName());
    }

};

and then calling:

Arrays.sort(persons, Person.FamilyNameComparator);

You could also sort by multiple fields. Take a look at this question on SO.