Over a million developers have joined DZone.

Where do conditionals come from?

DZone's Guide to

Where do conditionals come from?

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Given that we want to reduce the number of conditional branches in our code, I wonder whether it is possible to catalogue all of the reasons they exist, so that we might then in turn list a few ways to eliminate each category.

So to that end I’ve listed out those origins of conditionals that I could think of. Is this a fool’s errand? Possibly, but let’s give it a try anyway. Please comment if you can spot any that I have missed, and let’s see if we can grow a “complete” list…

  1. Checking a value returned to me from code I own
    This is the essence of the Null Check smell, and more generally Connascence of Meaning. For example, see this (intentionally bad) code from William C. Wake’s Refactoring Workbook:
    public class Report {
      public static void report(Writer out, List<Machine> machines, Robot robot) throws IOException
        if (robot.location() != null)
          out.write(" location=" + robot.location().name());
        if (robot.bin() != null)
          out.write(" bin=" + robot.bin());
  2. Checking a value returned to me from code I do not own
    For example, in Rails projects we often see code of this kind:
    if User.exists?(:user_id => current_user.id)
      # ...
      # ...
  3. Checking a parameter passed to me by code I own
    Whenever I write a method that accepts a Boolean parameter, I open myself up to the Control Couple smell. Here’s an example from Piotr Solnica’s blog:
    def say(sentence, loud = false)
      if loud
        puts sentence.upcase
        puts sentence
  4. Checking a parameter passed to me by code I do not own
    Here’s an example from the jQuery documentation:
    var xTriggered = 0;
    $( "#target" ).keypress(function( event ) {
      if ( event.which == 13 ) {
      var msg = "Handler for .keypress() called " + xTriggered + " time(s).";
      $.print( msg, "html" );
      $.print( event );
  5. Checking my own state or attributes
    Here’s an (intentionally bad) example from Martin Fowler’s Refactoring:
    class Employee {
      private int _type;
      static final int ENGINEER = 0;
      static final int SALESMAN = 1;
      static final int MANAGER = 2;
      Employee (int type) {
        _type = type;
      int payAmount() {
        switch (_type) {
          case ENGINEER:
            return _monthlySalary;
          case SALESMAN:
            return _monthlySalary + _commission;
          case MANAGER:
            return _monthlySalary + _bonus;
            throw new RuntimeException("Incorrect Employee");
  6. Checking a value I set previously in this method
    For example:
    public String format(List&lt;String&gt; items) {
      StringBuffer s = new StringBuffer();
      boolean first = true;
      for (String item : items) {
        if (first)
          first = false;
          s.append(", ");
      return s.toString();
  7. Checking the type of an exception thrown by code I own
    Here’s an example from the PHP language documentation:
    function inverse($x) {
        if (!$x) {
            throw new Exception('Division by zero.');
        return 1/$x;
    try {
        echo inverse(5) . "\n";
        echo inverse(0) . "\n";
    } catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    // Continue execution
    echo "Hello World\n";
  8. Checking the type of an exception thrown by code I do not own
    We often find code such as this in Rails controllers:
    def delete
      schedule_id = params[:scheduleId]
      rescue ActiveRecord::RecordNotFound
        render :json => "record not found"
      rescue ActiveRecord::ActiveRecordError
        # handle other ActiveRecord errors
      rescue # StandardError
        # handle most other errors
      rescue Exception
        # handle everything else
      render :json => "ok"

Is this list anything like complete? Can it ever be?

I wonder if a useful next step might be to write down some general strategies for removing each of these kinds of conditonal…?

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}