2

As I was working with this piece of code today, I got curious if there are any significant differences between these two or is it just personal preference when it comes to creating objects.

Exhibit A

private MailModuleStatus createMailModuleStatus(Project project, Team team, Account account){
 List<MailStatusCount> mailStatusCounts = mailModuleStatusHelper.getMailStatusCounts(team, DateUtils.getMidnightOfDate(new Date(), project.getTimeZone()));
 long unreadEmailCount = emailTrackService.countUnreadEmails(project, team);
 ScheduledEmail nextScheduledEmail = scheduledEmailService.findNextScheduledEmailToBeSent(account, team);
 return new MailModuleStatus(mailStatusCounts, unreadEmailCount, nextScheduledEmail);
}

Exhibit B

private MailModuleStatus createMailModuleStatus(Project project, Team team, Account account){
 MailModuleStatus mailModuleStatus = new MailModuleStatus();
 mailModuleStatus.setMailStatusCounts(mailModuleStatusHelper.getMailStatusCounts(team, DateUtils.getMidnightOfDate(new Date(), project.getTimeZone())));
 mailModuleStatus.setUnreadEmailCount(emailTrackService.countUnreadEmails(project, team));
 mailModuleStatus.setNextScheduledEmail(scheduledEmailService.findNextScheduledEmailToBeSent(account, team));
 return mailModuleStatus;
}
asked Jun 2, 2017 at 11:24
1
  • 3
    Beyond @Walfrat's answer, the former could support immutability, whereas with the latter one has to search to verify that no one else uses the setters. Commented Jun 2, 2017 at 14:56

2 Answers 2

6

The first one is better because you're sure you didn't forget anything.

Default constructor and setter are usually used by frameworks like Hibernate, Jackson when they need it. This is why you will usually have a default public constructor even if in an ideal world, you would prefer having only the one ensuring your object is properly initialized.

answered Jun 2, 2017 at 11:35
1

Even though B has much cleaner and understandable code at first sight, Exhibit A is (IMHO) better because you can use try..catch, null and sanity check your arguments before sending them to

return new MailModuleStatus(....);
answered Jun 4, 2017 at 8:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.