Skip to main content

Posts

Showing posts from May 6, 2022

Split your Loop

Greetings! It is common thing in programming that we need to iterate over items. Question is, how do you iterate over collection and implement your logics? Most of the time, people violate single responsibility principle as loops are having multiple logics. I would like to have cleaner separation between unrelated logics. If you pay attention, you can see that in loops, we are doing multiple things. Let's see a little (dirty) example. public class SplitLoop { public static void main(String[] args) { List<Subject> subjects = Arrays.asList(new Subject("Maths", 90), new Subject("History", 85)); int total = 0; int marksForMaths = 0; for (Subject subject : subjects) { total += subject.getMarks(); if ("Maths".equals(subject.getTitle())) { marksForMaths = subject.getMarks(); } } System.out.println("Total " + total + " for Maths " + marksForMaths); } static class Subject { ...