I wrote the following code:
if (boutique == null) {
boutique = new Boutique();
boutique.setSite(site);
boutique.setUrlLogo(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getLogo());
boutique.setUrlBoutique(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getUrl());
boutique.setNom(fluxBoutique.getNom());
boutique.setSelected(false);
boutique.setIdWebSC(fluxBoutique.getId());
boutique.setDateModification(new Date());
boutiqueDao.persist(boutique);
} else {
boutique.setSite(site);
boutique.setUrlLogo(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getLogo());
boutique.setUrlBoutique(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getUrl());
boutique.setNom(fluxBoutique.getNom());
//boutique.setSelected(false);
boutique.setIdWebSC(fluxBoutique.getId());
boutique.setDateModification(new Date());
boutiqueDao.merge(boutique);
}
There is a commented-out line here. But I think it makes the code clearer, by making obvious what the difference is between if
and else
. The difference is even more noticeable with color highlighting .
Can commenting out code like this ever be a good idea?
Best Answer
Most of the answers focus on how to refactor this one specific case, but let me offer a general answer to why commented out code is usually bad:
First, commented out code isn't compiled. This is obvious, but it means that:
The code might not even work.
When the comment's dependencies change it will not obviously break.
Commented code is very much "dead code". The longer it sits there, the more it rots and provides less and less value to the next developer.
Second, the purpose is unclear. You really need a longer comment that provides context for why there are randomly commented lines. When I see just a commented line of code, I have to research how it got there just to understand why it got there. Who wrote it? What commit? What was the commit message/context? Etcetera.
Consider alternatives: