0

Is it improper to or not to use a getter in a for-each loop. (I'm new to this)
Example for reference

public static void main(String[] args) {
        ArrayList<Program> programs = new ArrayList<>();

        Program program1 = new Program(1, "National Geographic");
        Program program2 = new Program(12, "TV2");
        Program program3 = new Program(24, "Disney Channel");
        Program program4 = new Program(33, "MTV");

        programs.add(program1);
        programs.add(program2);
        programs.add(program3);
        programs.add(program4);

        for(Program p : programs) {
            System.out.println(p.name + " " + p.number);
        }
    }
Nidos
  • 1
  • 1
  • 6
    In general, it **is** not proper to directly access the fields `name` and `number` without a getter. The `for-each` loop is immaterial. – Elliott Frisch Jan 16 '23 at 22:46
  • 3
    It looks as though your `Program` class has `public` fields. It's better to make them `private` and use a getter. – tgdavies Jan 16 '23 at 22:46
  • Possibly related: [Why use getters and setters/accessors?](https://stackoverflow.com/q/1568091) – Pshemo Jan 16 '23 at 22:47
  • Seconding both of the above. getters are preferred, strongly, over accessing fields directly. Don't worry about optimization until you find a need to actually optimize. – markspace Jan 16 '23 at 22:47
  • 3
    I'm going to be slightly controversial here. If the for each loop in question is somewhere inside the `Program` class, then there's no harm in using the fields directly. If it's in any other class, you should use getters. – Dawood ibn Kareem Jan 16 '23 at 23:00

0 Answers0