For a project I'm working on I have the following requirements:
We have two student types: Domestic and International
public enum StudentType {
Domestic,International
}
Students of both types must have a ID number, First/Last name but only international students require documentation (Passports, drivers licence, etc).
I've decided to create the Student
class
as immutable
, and came up with the following implementation:
public final class Student {
private final String id;
private final String firstname;
private final String lastname;
private final Collection<String> documents;;
private final StudentType typeofStudent;
private Student(String id, String firstname, String lastname, List<String> documents, StudentType typeofStudent)
{
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.documents = Collections.unmodifiableList(new ArrayList<String>(documents));
this.typeofStudent = typeofStudent;
}
public static Student createDomestic(String id, String firstname, String lastname)
{
return new Student(id, firstname, lastname, Collections.emptyList(), StudentType.Domestic);
}
public static Student createInternational(String id, String firstname, String lastname, List<String> documents)
{
return new Student(id, firstname, lastname, documents, StudentType.International);
}
}
I left out constructor validation to keep my code short and concise.
Advantages of the static method approach:
- If the
constructor
waspublic
, I would need to write aprivate
helpermethod
that checks if the student is domestic, the client didn't pass a list of documents. I wouldthrow
anexception
to notify the client if this happened. - My code is shorter because I prohibit the client from passing a
List<String> documents
if the student was domestic. I simply ask for the ID, and first/last name. TheCollections.unmodifiableList();
andStudentType
are set when domestic students are created. In other words, no need for a private helper method. - The client knows exactly what type of student is being created without calling a
getter
/internalmethod
to verify the student type.
Problem:
I came across this SESE page that was talking about the disadvantages of static. I became confused and wanted someone to review my code and tell me if my use of static methods are okay given what was said on that page?
The code and answer on this page provide what I need.
Student
and two child classes calledInternationalStudent
andDomesticStudent
? \$\endgroup\$