Java – Correct code design for Android/Java

Correct code design for Android/Java… here is a solution to the problem.

Correct code design for Android/Java

Code design issues

I have a class Area, which has a private instance variable called schools. In Area's constructor, I initialized all my schools because it was a time-consuming process. There is an instance method in Area that represents a grouping by the school that passes the list of students. I group these students into their schools and pass back the results.

Is it too much responsibility for the Area class to maintain both a list of schools and a grouping? But my main question is Android-related:
I have multiple fragments that need to use this class. They utilize the number of schools, the list of schools, and group them. I don’t want to instantiate this Area every time I open a new fragment. Where and how should I instantiate them in fragment or elsewhere? I can’t make it a singleton because area can be changed and in turn it needs to reinstantiate itself. I can’t call setSchools all at once. Any ideas? Are there design patterns I can follow?


The idea is to have a class to handle the creation of zones (probably your application class).

The application can then basically save the zone map to some form of region ID. If you find an area that doesn’t already exist, you can create it at this point and store it in Map for later use by other fragments.

Regarding the sorting of students, this does not seem to be a regional job.
Maybe it would make more sense to use something like StudentManager.

This is what I imagine (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) {

I’m sure you can improve the StudentManager class ordering, but this separation makes some sense to me….

Related Problems and Solutions