0

My colleague has created a class that has itself as a static attribute.

public class GroupProject {

    public static GroupProject staticGroupProject;

    private String groupId;

    public void setGroupId(String id) {
        if (groupId != null) {
            groupId = id;
        }
    }
}

public class GroupProjectUtils {

    public void startGroupProject() {
        GroupProject.staticGroupProject = new GroupProject();
    }

    public void stopGroupProject() {
        GroupProject.staticGroupProject = null;
    }

    public void setIdentification(String identification) {
        GroupProject.staticGroupProject.setGroupId(identification);
    }
}
  1. How to reason about this code in OOP terms?
  2. Does it actually function like a top-level static class?
  3. Is doing this generally speaking a good or a bad practice?

EDIT: Thank you for your suggestions. This comment here answers the question well - Java Singleton Design Pattern : Questions.

  • A static instance of your class is used for the [Singelton Design Pattern](https://stackoverflow.com/q/2832297/7947994). Not exactly what your friend implemented, but it is the closest "good practice" I can think of. – JANO Jun 07 '22 at 11:08
  • Stop your colleague before it's too late. If this is a school project, use a singleton instead. If this is real code, use a DI framework. – Kayaman Jun 07 '22 at 11:11
  • 1
    This is not an example of a 'static class'. This is a 'static instance'. They aren't the same thing. – user207421 Jun 07 '22 at 11:32
  • 1
    Actually, this is just a `static` variable. It doesn’t change any property of the class itself. Neither does it affect the object. In Java, objects are not affected by the variable(s) referring to them. The logic would be the same if the `staticGroupProject` variable was placed in `GroupProjectUtils` instead of `GroupProject`. It doesn’t limit the number of variables or instances of type `GroupProject` which could exist somewhere else. – Holger Jun 08 '22 at 08:15

0 Answers0