Where do I place the comparisons in Java?

I think of this problem over and over again when creating objects that must validate conditions Should checks be placed before attempting to create an object or in the constructor of the object itself?

To better illustrate this, here is an example: suppose we have a student manager, a professor, who adds student objects to their list When creating a new student object, we must check that his name is up to 20 characters long

class Professor{
    LinkedList<Student> studentsList;

    Professor(){
        studentsList = new LinkedList<Student>();
    }

    public Student addStudent(String studentName){
        // Place 1
        if (studentName.length <= 20)
            studentList.add(new Student(studentName));
        else
             // Do another thing
    }
}

class Student {
    String name;

    Student(String studentName){
        // Place 2
        if (studentName.length <= 20)
            name = studentName);
        else
            // Don't create the object and throw exception 
    }
}

So basically, my question is, if you check in place 1, before trying to create a student, or in place 2, in the student's structure

Solution

Objects are responsible for themselves

Usually in object - oriented programming (OOP), we want objects to be responsible for themselves Business rules regarding their internal country integrity should be handled internally (or delegated to the builder – see below) This idea is officially called encapsulation in OOP

Therefore, in your example, teaching courses should not worry about student class rules, such as the length of student names Student classes should enforce their integrity We want the logic of these integrity rules to be in a single location rather than distributed throughout the application

In fact, a professor class should not instantiate a student object In your example, it is implied that some other party must assign students to professors It may be a tutorial object that tracks the homework and progress of a few students supervised by the professor This tutorial should instantiate student objects or pass student objects received from some other source, such as database service objects

When student objects arrive at the professor, they should be effective Teaching courses should not focus on student effectiveness Professors should only care about their effectiveness

class Professor{
    List< Student > students;
    …
    public void addStudent( Student student ){
        Objects.requireNonNull​( student,"Received NULL rather than a Student object. Message # 68a0ff63-8379-4e4c-850f-e4e06bd8378a." ) ;  // Throw an exception if passed a null object.
        Objects.requireNonNull​( this.students,"Collection of Student objects is NULL. Message # c22d7b22-b450-4122-a4d6-61f92129569a." ) ;  // Throw an exception if the `students` list is not established.
        this.students.add( student ) ;
    }
}

In addition to the idea that the object is responsible for itself, another reason why the professor did not instantiate the student object is to facilitate testing If the student object comes from another source, the source can provide a dummy object using the student class or non interface Not yet completed, disable some functions (such as database access), or replace with forged data designed for test scenarios

Generator mode

If you have multiple properties that need to be validated to instantiate a new object, you may need to use builder pattern You can define an additional class, such as studentbuilder, which has methods to create each part required by students

Typically, these methods return the same studentbuilder object for call - chaining

Different people have different styles for builders One way is to provide a validity check method, perhaps a method to prevent the construction of the problem list of the required object

Some people use words similar to but not accessor method settings to make it clear that when we set properties temporarily on the builder, the real intention is to set properties on another class object

StudentBuilder sb = new StudentBuilder().withFirstName( "Alice" ).withLastName( "Coleman" ).withEmail( "x@y.com" );
if( sb.isValid() ) {
    Student s = sb.build() ;
    …
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>