I have a question on the best practice for validating arguments to a method when the arguments are contained within an object. For example, if you have:
public class Student {
public int getStudentId();
public String getStudentName();
public String getStudentSSN();
public double getStudentGpa();
public String getStudentMajor();
// Other student related getters
}
Then, I have a method:
public void printStudentReport(Student student);
In this method, I need to perform logic involving the ID, name, GPA, and major. So, those are the ones required. All the other student getters don’t have to be populated. Is it ok to just first validate the Student object and then those four methods I need? I feel like this is a bit misleading because I am passing this Student object to this method, yet not all fields are required, so its really a half-populated object being sent to this method. Just seems strange to me.
If some of the properties must be populated always for a Student to be valid, you should consider defining a nondefault constructor with the required parameters, and removing any default constructors from the class (and if needed, validating the property values within the getters). This ensures that only valid Student objects can be created.
If the other properties are really optional for Students, it looks perfectly OK to me. Of course, you need to think through the use cases and analyze the domain model carefully, in order to decide which parameters are required and which are optional.