Take the following POJOs:
public class Widget {
private String fizz;
private Long buzz;
private List<Fidget> collaborators;
// Constructor, getters & setters
}
public class Fidget {
private String fizz;
private String foo;
// Constructor, getters & setters
}
And the following (working) method:
public void compriseWidgets(List<Fidget> fidgetList) {
List<Widget> widgets = new ArrayList<Widget>();
Widget currentWidget = null;
for (Fidget fidget : fidgetList) {
if (currentWidget == null ||
!currentWidget.getFizz().equals(fidget.getFizz())) {
currentWidget = new Widget();
widgets.add(currentWidget);
currentWidget.setFizz(fidget.getFizz());
currentWidget.setBuzz(fidget.getFoo().length());
}
currentWidget.getCollaborators().add(fidget);
}
return widgets;
}
Here we want to return a List<Widget>
and populate that list only:
- From the first
Fidget
in the input list (hencecurrentWidget == null
); and - If the
Fidget
andcurrentWidget
have the samefizz
value
Furthermore, we want to keep appending collaborators
to the currentWidget
regardless of whether the fizzes match or not.
My problem
A new code style guideline is requiring that we declare ALL variables with final
...meaning I need to get the above code refactored to look like so:
public void compriseWidgets(final List<Fidget> fidgetList) {
final List<Widget> widgets = new ArrayList<Widget>();
final Widget currentWidget = null;
for (final Fidget fidget : fidgetList) {
...
}
return widgets;
}
Because it requires both the creation of a new Widget
inside the loop, but an external (outside the loop) reference to a Widget
that we can add collaborators
to, I'm at a total loss for how to rewrite this with final
. Any ideas? Also, please note, this is nothing that I can "push back" on, I just need to figure it out and get it working with the new coding standard.