简体   繁体   English

Java中的mutator方法的最佳实践

[英]Best practice for mutator methods in java

I have written a function which sorts ArrayList of custom object Collection.sort. 我编写了一个对自定义对象Collection.sort的ArrayList进行排序的函数。

public List<Student> getStudents(int std) {
    List<Student> students = studentDAO.getStudents(std);
    ......
    sortStudents(students);
    .....
    return students;
}

private void sortStudents(students) {
    Collection.sort(students, new Comparator<Student>(){
        public int compare(Student s1, Student s2) {
            return s1.getDOB().compareTo(s2.getDOB());
        }
    });
}

Is above code is clean? 以上代码干净吗? Is it ok to write such mutators or should use a new object and return it? 可以编写这样的转换器,还是应该使用一个新的对象并返回它?

This depends on the contract of studentDAO.getStudents() method - does it guarantee to always return a new list of results (ie an object that only the caller will have reference to)? 这取决于studentDAO.getStudents()方法的约定-是否保证始终返回新的结果列表(即仅调用方将引用的对象)? If so, then you can safely sort it in place. 如果是这样,那么您可以安全地对其进行排序。 If not, you should make a copy. 如果没有,您应该进行复制。

Another concern is - will it always guarantee that? 另一个问题是-它会一直保证吗? One of many way this can go wrong is if you add some caching - that could easily break this guarantee. 可能会出错的许多方法之一是,如果添加一些缓存,则很容易破坏此保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM