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;
}
-
3Beyond @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.Erik Eidt– Erik Eidt2017年06月02日 14:56:57 +00:00Commented Jun 2, 2017 at 14:56
2 Answers 2
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.
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(....);