Proper code design for Android / Java

Code Design Considerations

I have a class, say Area, that has a private instance variable called schools. In the constructor, AreaI initialize all my schools because it is a process of time. There Areais an instance method that states that groups participate in schools where a list of students is transmitted. I group these students into my schools and return the result.

Is it too much responsibility for this class Areathat it has to maintain a list of schools, and also does the grouping? But my main question is related to Android: I have some snippets that should use this class. They use the number of schools, a list of schools, and also group them. I do not want to instantiate this Areaevery time I open a new fragment. Where and how should I create them in a fragment or elsewhere? I can’t make it a single, because it Areacan change and, in turn, he needs to reinstall himself. I can’t call setSchoolson it as a single thing. Any ideas? Is there a design pattern that I can execute?

+4
source share
1 answer

My thought would be to have a class that handles the creation of areas (maybe your Application class).

In this case, the application can basically be held on the area map in some form of Area identifier. If you find an area that does not exist yet, you can create it at this point and save it on the map for other fragments that will be used later.

As regards the sorting of students, this is apparently not the task of the Area. Perhaps using something like that StudentManagerwould make more sense.

Here is how I imagine it (in a simplified form):

class Student {
  String name;
}

class School {
  List<Student> students;

  boolean contains(Student) {
    return students.contains(student);
  }
}

class Area {
  List<School> schools;
}

class StudentManager {
  Map<School, Set<Student>> sortIntoSchools(Collection<Student> unsortedStudents) {
    Map<School, Set<Student>> result = new HashMap<>(); // Should use a decorated map here
    for(Student student : unsortedStudents) {
     for(Area area : areas) {
      for(School school : area.schools) {
        if(school.contains(student)){
          result.get(school).add(student);
        }
       }
      }
    }
  }
}

I'm sure you can improve the sorting of StudentManager classes, but this separation makes some sense to me ...

0
source

Source: https://habr.com/ru/post/1536689/


All Articles