Article 4A06C A Switch for Grenk

A Switch for Grenk

by
Remy Porter
from The Daily WTF on (#4A06C)

Let's say you've got a project object in your code. A project might be opened, or it might be closed. In either case, you want to register an event handler to change the status- closed projects can be opened, opened projects can be closed. Now imagine you're Antonio's co-worker, Grenk.

No, this time, it's not a matter of streams. Today, it's ternary abuse, of the "why is this even here" sort.

switch(project.getStatus()){ case CLOSED: { //snip: re-open the project break; } case OPEN: { //snip: close the project break; }}registerEvent(projectDB.getStatus().equals(StatusProjectEnum.CLOSED) ? TypeEventProjectEnum.ENABLED : TypeEventProjectEnum.DISABLED, project.getId(), sessionUser, project.getStatus().equals(StatusProjectEnum.CLOSED) ? "Enabled project " + project.getDescription() : "Disabled project " + project.getDescription());getDao().update(project);

Let's trace the logic. We start with a switch on the project status. If it's CLOSED we open it, if it's OPEN we close it. Then, we call the registerEvent method, and use a ternary on the project status to decide what parameters to pass to the method. The result is an unreadable mess, and it's extra confusing because we just passed by a perfectly good switch. Why not just put a call to registerEvent in each branch of the switch?

Which, by the way, is exactly what Antionio did. During the code review, Grenk objected that Antonio's version wasn't as "DRY" as his, but the rest of the team agreed that this was more readable.

raygun50.png [Advertisement] Forget logs. Next time you're struggling to replicate error, crash and performance issues in your apps - Think Raygun! Installs in minutes. Learn more. TheDailyWtf?d=yIl2AUoC8zAujgYFjuyFt8
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments