Cleaning Shit Up

On refactoring, structuring code, and making our lives easier when working together.

Some References

Ask a bunch of developers what the best way is and what do you get?

One person's happiness != team happiness

Code Style Guides

Just like with visual design, code should have a "style guide" as well.

 

Automate all the things!

  • Linting
  • Editor Config
  • Continuous Integration / Testing
  • And if all else fails...Code Reviews

Preventing ugly code is sometimes easier than cleaning it up...but how?

Consistent code naming and folder structure

  • base/ – contains global styles, such as resets, typography, colors, etc.
  • components/ – contains each self-contained component in its own .scsspartial
  • layout/ – contains styling for larger layout components; e.g. nav, header, footer, etc.
  • pages/ – contains page-specific styling, if necessary
  • themes/ – contains styling for different themes
  • utils/ – contains global mixins, functions, helper selectors, etc.
  • vendors/ – contains 3rd-party styles, mixins, etc.
  • main.scss – output file that brings together all of the above parts

Ask any programmer that has inherited somebody else's code and they will say that their code is "A big hairy mess"

Don't reWRITE...instead, reFACTOR

How to deal with such a monumental task?

Let's talk principles of clean code and project architecture

class Person {
    public name : string;
    public surname : string;
    public email : string;
    constructor(name : string, surname : string, email : string){
        this.email = email;
        this.name = name;
        if(this.validateEmail(email)) {
          this.surname = surname;
        }
        else {
            throw new Error("Invalid email!");
        }
    }
    validateEmail(email : string) {
        var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        return re.test(email);
    }
    greet() {
        alert("Hi!");
    }
}

Don't create "GOD" classes

class Email {
    public email : string;
    constructor(email : string){
        if(this.validateEmail(email)) {
          this.email = email;
        }
        else {
            throw new Error("Invalid email!");
        }        
    }
    validateEmail(email : string) {
        var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        return re.test(email);
    }
}

class Person {
    public name : string;
    public surname : string;
    public email : Email;
    constructor(name : string, surname : string, email : Email){
        this.email = email;
        this.name = name;
        this.surname = surname;
    }
    greet() {
        alert("Hi!");
    }
}

Every function and class should do one thing

// LaunchWizard.js
// 1000 lines of jquery that does...everything?

// Select the elements corresponding to the actively selected cloud
$(document).ready(function() {
  var location = window.location.pathname;
  var baseLocation = location.substring(0, location.indexOf("/launch_vm"));

  defaultSecurityGroup();
  processCloudChoice();
  i18nPromise.then(function(){
    determineIfPublicCloudInProgress();
    //        createLinkToInfrastructurePage();
    generateButtonLinks();

    $("#uploadImageType").val("local");
    $(".uploadImageUrl").hide();
    $(".uploadImageFile").show();

    $('#default-id-note').toggleClass("hidden", true);
    if ($(".authSection .CloudPassword")) {
      $(".authSection .CloudPassword").tooltip();
    }
    if ($(".authSection .CloudUserId")) {
      $(".authSection .CloudUserId").tooltip();
    }
    if ($everyInput('initialInstances')) {
      $everyInput('initialInstances').tooltip();
    }
    $('[data-toggle="tooltip"]').tooltip();
    processImageChoice();
  });

  // Check if sessionStorage is set indicating the NEW button was last pressed, we want to retain that state.
  if (sessionStorage.vmNewImageTypeSelected) {
    $('.image-selection').toggleClass("hidden", true);
    $('.image-upload').toggleClass("hidden", false);
    $('#new-image').prop("checked", true);
  }

  // Check if sessionStorage is set indicating the GROUP button was last pressed, we want to retain that state.
  if (sessionStorage.vmGroupTypeSelected) {
    $('[data-attr="instanceSelection"]').toggleClass("hidden", false);
    $('#group').prop("checked", true);
  }

  $('#addKeyDialog').on('show.bs.modal', function(event) {
    var modal = $(this);
    modal.find('#downloadKey').toggleClass("hidden", true);
    modal.find('.keyNameElement').toggleClass("hidden", false);
    modal.find('#closeKeyButton').text(i18n.t("label.CANCEL"));
    modal.find('#closeKeyButton').toggleClass("alchemy-btn-primary", false);
    modal.find('#closeKeyButton').toggleClass("alchemy-btn-secondary", true);
    modal.find('#saveKeyButton').toggleClass("hidden", false);
    modal.find('#privateKeyMsg').toggleClass("hidden", true);
    modal.find('#privateKey').text("");
    modal.find('.importPrimary').toggleClass("hidden", false);
    modal.find('.createPrimary').toggleClass("hidden", true);
    modal.find('#keyName').val("");
    modal.find('#publicKey').val("");
    modal.find('.publicKeyElement').toggleClass("hidden", false);
    removeBoxAlert("#keyName", "#keyNameAlert");
    removeBoxAlert("#publicKey", "#publicKeyAlert");
    removeBoxAlert("#workloadKey", "#sshAlertText");
  });

  $(".importButton").click(function() {
    $(".importPrimary").toggleClass("hidden", false);
    $(".createPrimary").toggleClass("hidden", true);
    $(".publicKeyElement").toggleClass("hidden", false);
    $("#keyNameLabel").text(i18n.t("label.KeyName"));
    removeBoxAlert("#keyName", "#keyNameAlert");
  });

  $(".createButton").click(function() {
    $(".importPrimary").toggleClass("hidden", true);
    $(".createPrimary").toggleClass("hidden", false);
    $(".publicKeyElement").toggleClass("hidden", true);
    $("#keyNameLabel").text(i18n.t("label.CreateKey"));
    removeBoxAlert("#keyName", "#keyNameAlert");
    removeBoxAlert("#publicKey", "#publicKeyAlert");
  });

  $("#saveKeyButton").click(addKey);

  $everyInput('initialInstances').change(function() {
    $everyInput('initialInstances').removeClass("boxAlert");
    var regex = /^\d*$/;
    if (!regex.test($("#initialInstances").val())) {
      $everyInput('initialInstances').addClass("boxAlert");
    }
  });

  $("#existing-image").click(function() {
    $(".image-upload").toggleClass("hidden", true);
    $(".image-selection").toggleClass("hidden", false);
    delete(sessionStorage.vmNewImageTypeSelected);
  });

  $("#new-image").click(function() {
    $(".image-upload").toggleClass("hidden", false);
    $(".image-selection").toggleClass("hidden", true);
    sessionStorage.vmNewImageTypeSelected = true;
  });

  $("#single").click(function() {
    $('[data-attr="instanceSelection"]').toggleClass("hidden", true);
    delete(sessionStorage.vmGroupTypeSelected);
    validateName();
  });

  $("#group").click(function() {
    $('[data-attr="instanceSelection"]').toggleClass("hidden", false);
    sessionStorage.vmGroupTypeSelected = true;
    validateName();
  });

  $('[data-submit="addWorkload"]').click(function() {
    if(checkEmptySSHKeyNotEmpty()) {
      removeVMGroupBoxAlert();
      removeSSHKeyAlert();
      var baseVMPath,payload,launchURL;
      payload = getWorkloadValues();

      //If "No key needed" is selected, then remove the workloadKey key from the payload.
      if ($activeInput('workloadKey').val() === "#_NONE_#") {
        delete payload.workloadKey;
      }

      //The paths are generated by manipulating the URL that generated the launch page.
      if( $("#group").prop("checked") ) {
        baseVMPath = window.location.pathname.substring(0, window.location.pathname.indexOf("/launch"));
        launchURL = baseVMPath + window.location.search;
      } else {
        baseVMPath = window.location.pathname.substring(0, window.location.pathname.indexOf("groups/launch"))+"s";
        launchURL = baseVMPath + window.location.search;
      }

      $("#standbyComponent").toggleClass("hidden");

      // METRICS begin: add IDA instrumentation code (close conversion and send form attributes if successful)
      met_createVMAfter(payload);
      // METRICS end

      //Set the web storage key, fip, based on whether they want a FIP or not
      //This value is consumed in the detail page to display the spinner for public IP
      sessionStorage.fip = ($("#assign-public-ip").prop("checked") ? true : false);

      $.ajax({
        dataType: "json",
        cache: false,
        type: "POST",
        data: payload,
        error: handleError,
        url: launchURL,
      }).then(function(data) {
        //redirect to details page (after waiting five seconds).
        setTimeout(function() {
          if( $("#group").prop("checked") ) {
            document.location.href = baseVMPath + "/" + data.data.stack_id + window.location.search;
          } else {
            document.location.href = baseVMPath + "/" + data.data.VM_id + window.location.search;
          }
        }, 5000);
      });
    }  else {
      // TODO: need to change text
      addSSHKeyAlert();
    }
  });

  $everyInput('workloadName').blur(function () {
    // if vmGroup is selected, check group name
    if (sessionStorage.vmGroupTypeSelected) {
      validateName();
    }
  });

  $("#imageName").blur(function () {
    validateImageName();
  });

  $("#imageLocation").blur(function () {
    if (!checkEmptyUploadImageLocation() && $("#uploadImageType").val() === "url") {
      // put up messsage
      addImageUrlBoxAlert();
    } else {
      // hide message box
      removeImageUrlBoxAlert();
    }
  });

  $everyInput('workloadName').change(checkVMGroupBox);

  $('[data-action="getRCFile"]').click(function() {
    var baseVMPath = window.location.pathname.substring(0, window.location.pathname.indexOf("/vmgroups/launch"));

    $("#standbyComponent").toggleClass("hidden", false);
    $.ajax({
      dataType: "html",
      cache: false,
      type: "GET",
      error: handleError,
      url: baseVMPath + "/clifile" + window.location.search
    }).then(function(data){
      downloadRCFile(data);
    });
  });


  $('#uploadImageModal').on('show.bs.modal', function(event) {
    var button = $(event.relatedTarget);
    var cloudname = button.data('cloudname');
    var cloudid = button.data('cloudid');
    var modal = $(this);
    modal.find('.uploadImageButton').attr('cloudid', cloudid);
    modal.find('#modalCloudName').text(cloudname);
  });


  $("#uploadImageType").change(function() {
    if ($(this).val() === "local") {
      $(".uploadImageFile").show();
      $(".uploadImageUrl").hide();
      removeImageUrlBoxAlert();
    } else {
      $(".uploadImageFile").hide();
      $(".uploadImageUrl").show();
      removeImageFileBoxAlert();
    }
  });

  $("#browseImageButton").change(function() {
    if ($(this).val() !== "") {
      $("#selectedFileLabel").text($(this).val().replace(/C\:\\fakepath\\/i, ''));
      removeImageFileBoxAlert();
    }
  });

  $("#uploadForm").submit(function() {
    var message;
    var basePath = window.location.pathname.substring(0, window.location.pathname.indexOf("/v1/") + 4);
    var cloud_id = $(this).find('.uploadImageButton').attr('cloudid');
    var nameValid = false;

    validateImageName (function(valid) {
      nameValid = valid;
    });

    if(!nameValid) {
      return false;
    }

    var imageParms = getImageParms();
    if (!imageParms.location && !imageParms.file) {
      if ($("#uploadImageType").val() === "local") {
        addImageFileBoxAlert();
      } else {
        addImageUrlBoxAlert();
      }
      return false;
    }

    var data = new FormData();
    data.append("diskformat", $("#diskFormat").val());
    data.append("name", $("#imageName").val());
    if ($("#uploadImageType").val() === "local") {
      data.append("file", $("#browseImageButton")[0].files[0]);
    } else {
      data.append("location", $("#imageLocation").val());
    }

    $("#uploadImageModal").modal('hide');
    $("#standbyComponent").toggleClass("hidden", false);
    // METRICS begin: add IDA instrumentation code (send element tag)
    met_uploadImage(imageParms);
    // METRICS end
    $.ajax({
      dataType: "json",
      cache: false,
      type: "POST",
      data: data,
      error: handleError,
      contentType: false,
      processData: false,
      url: basePath + "image/" + cloud_id + window.location.search,
    }).then(function(data) {
      //clean input
      $("#imageName").val("");
      $("#imageLocation").val("");
      $("#browseImageButton").val("");
      $("#standbyComponent").toggleClass("hidden", true);
      window.location.reload();
    });
    return false;
  });

  $("#networkDetailsDialog").click(function(){
    var selectedNetwork = $activeInput('workloadNetwork').val();
    var network, subnet;
    //TODO: fix for multiple subnets
    dustData.clouds.some(function(cloud) {
      return cloud.networks.some(function(net) {
        if(net.id === selectedNetwork) {
          network = net;
          subnet = cloud.subnets[0];
          return true;
        }
      });
    });
    if(!network || !subnet) {
      return;
    }
    $("#networkDetailsField").html(network.name + " / " + subnet.name);
    $("#subnetDetailsAddress").html(subnet.cidr);
    $("#subnetDetailsVersion").html(i18n.t(subnet.ipVersion === 4 ? "label.IPv4" : "label.IPv6"));
    $("#subnetDetailsGateway").html(subnet.gatewayIp);
  });

  $("#workloadCloud").change(processCloudChoice);
  $everyInput('workloadImage').change(processImageChoice);

});

function $activeCloud() {
  var id = $("#workloadCloud").val().replace(/:/g, "\\:");
  return $( '[data-cloudIdTag="' + id + '"]' );
}

// Select the input that corresponds to the currently selected cloud
function $activeInput(name) {
  return $activeCloud().find('[data-inputId="' + name + '"]')
}

// Select every input regardless of cloud selection
function $everyInput(name) {
  return $( '[data-inputId="' + name + '"]' );
}


function downloadKey() {
  var filename;
  var keyName = $('#keyName').val().trim();
  var privateKey = $('#privateKey').text();
  filename = keyName + ".pem";
  downloadFile(filename, privateKey, true);
};

function isEmptyField(fieldName) {
  var fieldVal = $(fieldName).val();
  if (/\S/.test(fieldVal)) {
    return false;
  } else {
    return true;
  }
};

function isValidName(fieldName) {
  var fieldVal = $(fieldName).val();
  if (/^[a-zA-Z][a-zA-Z0-9_\-]*$/.test(fieldVal)) {
    return true;
  } else {
    return false;
  }
};

function addBoxAlert(fieldName, fieldAlert) {
  $(fieldName).addClass("boxAlert");
  $(fieldAlert).removeClass("hidden");
};

function removeBoxAlert(fieldName, fieldAlert) {
  $(fieldName).removeClass("boxAlert");
  $(fieldAlert).addClass("hidden");
};

function checkKeyName() {
  var isValid = true;
  if (isEmptyField("#keyName")) {
    addBoxAlert("#keyName", "#keyNameAlert");
    $("#keyNameAlert").text(i18n.t("msg.RequiredField"));
    isValid = false;
  } else if (!isValidName("#keyName")) {
    addBoxAlert("#keyName", "#keyNameAlert");
    $("#keyNameAlert").text(i18n.t("msg.InvalidName"));
    isValid = false;
  } else {
    removeBoxAlert("#keyName", "#keyNameAlert");
  }
  return isValid;
};

function checkPublicKey() {
  var isValid = true;
  if (isEmptyField("#publicKey") && !$('.importPrimary').hasClass('hidden')) {
    addBoxAlert("#publicKey", "#publicKeyAlert");
    isValid = false;
  } else {
    removeBoxAlert("#publicKey", "#publicKeyAlert");
  }
  return isValid;
};

function addKey() {
  if (checkKeyName() && checkPublicKey()) {
    $("#standbyComponent").toggleClass("hidden");
    if ($('.importPrimary').hasClass('hidden')) {
      $('#publicKey').val("");
    }
    // METRICS begin: add IDA instrumentation code (send element tag)
    met_addKey(!$('.importPrimary').hasClass('hidden'),!$('.createPrimary').hasClass('hidden'));
    // METRICS end
    $.ajax({
      dataType: "json",
      cache: false,
      type: "post",
      error: handleError,
      data: {
        keyName: $("#keyName").val(),
        publicKey: $("#publicKey").val(),
        cloudId: $("#workloadCloud").val()
      },
      url: window.location.pathname + "/key" + window.location.search,
    }).done(function(payload) {
      //            //$("<option value='" + $("#keyName").val() + "'>" + $("#keyName").val() + "</option>").insertBefore($('#workloadKey option:first-child'));
      $("#standbyComponent").toggleClass("hidden");
      $activeInput('workloadKey').prepend("<option value='" + $("#keyName").val() + "'>" + $("#keyName").val() + "</option>");
      $activeInput('workloadKey').find('option:first').attr("selected", "selected");
      if (payload.data.private_key) {
        $(".createPrimary").toggleClass("hidden", true);
        $("#downloadKey").toggleClass("hidden", false);
        $(".keyNameElement").toggleClass("hidden", true);
        $("#closeKeyButton").text(i18n.t("label.Close"));
        $("#closeKeyButton").toggleClass("alchemy-btn-primary alchemy-btn-secondary");
        $("#saveKeyButton").toggleClass("hidden", true);
        $("#privateKeyMsg").text($("#privateKeyMsg").text().replace("{0}", $("#keyName").val()));
        $("#privateKeyMsg").toggleClass("hidden", false);
        $("#downloadKeyLink").text($("#downloadKeyLink").text().replace("{0}", $("#keyName").val()));
        $("#privateKey").text(payload.data.private_key);
        downloadKey();
      } else {
        $("#addKeyDialog").modal('hide');
      }
    });
  }
};


function addCredentialBoxAlert(cloudUser, cloudPassword) {
  if (!/\S/.test(cloudUser)) {
    $(".authSection:not(.hidden) .CloudUserId").addClass("boxAlert");
  }
  if (!/\S/.test(cloudPassword)) {
    $(".authSection:not(.hidden) .CloudPassword").addClass("boxAlert");
  }
};

function removeCredentialGroupBoxAlert() {
  $(".authSection:not(.hidden) .CloudUserId").removeClass("boxAlert");
  $(".authSection:not(.hidden) .CloudPassword").removeClass("boxAlert");
};

function connect() {
  removeCredentialGroupBoxAlert();
  var cloudUser = $(".authSection:not(.hidden) .CloudUserId").val();
  var cloudPassword = $(".authSection:not(.hidden) .CloudPassword").val();
  if (!/\S/.test(cloudUser) || !/\S/.test(cloudPassword)) {
    addCredentialBoxAlert(cloudUser, cloudPassword);
    return;
  }
  $("#standbyComponent").toggleClass("hidden");
  $.ajax({
    dataType: "json",
    cache: false,
    type: "post",
    error: handleError,
    data: {
      cloudpwd: $(".authSection:not(.hidden) .CloudPassword").val(),
      clouduser: $(".authSection:not(.hidden) .CloudUserId").val(),
      cloudId: $("#workloadCloud").val()
    },
    url: window.location.pathname + "/connect" + window.location.search
  }).then(function(payload) {
    location.reload();
  });
};

$(".connect").click(connect);

function checkEmptyUploadImageName() {
  var ImageName = $("#imageName").val();
  // Check if string isn't empty or whitespace.
  if (/\S/.test(ImageName)) {
    return true;
  } else {
    return false;
  }
};

function checkEmptyUploadImageLocation() {
  var ImageName = $("#imageLocation").val();
  // Check if string isn't empty or whitespace.
  if (/\S/.test(ImageName)) {
    return true;
  } else {
    return false;
  }
};

function checkEmptyVMGroup() {
  var VMGroupName = $activeInput('workloadName').val();
  // Check if string isn't empty or whitespace.
  if (/\S/.test(VMGroupName)) {
    return true;
  } else {
    return false;
  }
};

function checkValidVMGroup() {
  var VMGroupName = $activeInput('workloadName').val();
  // Make sure string starts with a character and only contains certain chars
  if (/^[a-zA-Z][a-zA-Z0-9_\.-]*$/.test(VMGroupName)) {
    return true;
  } else {
    return false;
  }
};

function checkEmptySSHKeyNotEmpty() {
  var sshKey = $activeInput('workloadKey').val();
  // Check if string isn't empty or whitespace.
  if (sshKey) {
    return true;
  } else {
    return false;
  }
};

function addVMGroupBoxAlert() {
  $activeInput('workloadName').addClass("boxAlert");
  $("#workloadNameAlert").removeClass("hidden");
};

function addImageNameBoxAlert() {
  $("#imageName").addClass("imageNameAlert");
  $("#imageNameAlertText").removeClass("visibleHidden");
  $("#imageNameAlertText").addClass("visible");

  //disable upload button
  $(".uploadImageButton").addClass("disabled");
};

function addImageUrlBoxAlert() {
  $("#imageLocation").addClass("imageNameAlert");
  $("#imageUrlAlertText").removeClass("visibleHidden");
  $("#imageUrlAlertText").addClass("visible");

  //disable upload button
  $(".uploadImageButton").addClass("disabled");
};

function addImageFileBoxAlert() {
  $("#browserImageButtonDiv").addClass("imageNameAlert");
  $("#imageFileAlertText").removeClass("visibleHidden");
  $("#imageFileAlertText").addClass("visible");

  //disable upload button
  $(".uploadImageButton").addClass("disabled");
};

function removeVMGroupBoxAlert() {
  $activeInput('workloadName').removeClass("boxAlert");
  $("#workloadNameAlert").addClass("hidden");
};

function removeImageNameBoxAlert() {
  $("#imageName").removeClass("imageNameAlert");
  $("#imageNameAlertText").removeClass("visible");
  $("#imageNameAlertText").addClass("visibleHidden");

  //enable upload button
  $(".uploadImageButton").removeClass("disabled");
};

function removeImageUrlBoxAlert() {
  $("#imageLocation").removeClass("imageNameAlert");
  $("#imageUrlAlertText").removeClass("visible");
  $("#imageUrlAlertText").addClass("visibleHidden");

  //enable upload button
  $(".uploadImageButton").removeClass("disabled");
};

function removeImageFileBoxAlert() {
  $("#browserImageButtonDiv").removeClass("imageNameAlert");
  $("#imageFileAlertText").removeClass("visible");
  $("#imageFileAlertText").addClass("visibleHidden");

  //enable upload button
  $(".uploadImageButton").removeClass("disabled");
};

function checkVMGroupBox() {
  if (checkEmptyVMGroup() && checkValidVMGroup()) {
    removeVMGroupBoxAlert();
  }
};
function addSSHKeyAlert() {
  $activeInput("workloadKey").addClass("boxAlert");
  $activeInput("workloadKey").next().removeClass("hidden");
};

function removeSSHKeyAlert() {
  $activeInput("workloadKey").removeClass("boxAlert");
  $activeInput("workloadKey").next().addClass("hidden");
};

function getWorkloadValues() {
  return {
    workloadName: $activeInput('workloadName').val(),
    workloadKey: $activeInput('workloadKey').val(),
    workloadImage: $activeInput('workloadImage').val(),
    workloadFlavor: $activeInput('workloadFlavor').val(),
    workloadNetwork: $activeInput('workloadNetwork').val(),
    workloadSecurityGroups: [$activeInput('workloadSecurityGroups').val()], //for now, send an array of 1, until we support multi select
    workloadInstances: $("#initialInstances").val(),
    cloudId: $("#workloadCloud").val(),
    FloatingIP: $("#assign-public-ip").prop("checked") ? "YES" : "NO"
  };
};
function getExistingGroupNames(callback){
  var stacks = [];
  try {
    stacks = dustData.clouds[$("#workloadCloud").index()].stacks;
  } catch(error) {}

  callback(stacks);
};

function getExistingImageNames(callback){
  var images = [];
  try {
    images = dustData.clouds[$("#workloadCloud").index()].images;
  } catch(error) {}

  callback(images);
};

function validateName() {
  if (checkEmptyVMGroup()) {
    if (checkValidVMGroup()) {
      // only check name's uniqueness if group is selected
      if (sessionStorage.vmGroupTypeSelected) {
        validateGroupName();
      } else {
        // passed name checks clear box (single button)
        removeVMGroupBoxAlert();
      }
    } else {
      // display message name contains illegal characters
      $("#workloadNameAlert").text(i18n.t("msg.InvalidName"));
      addVMGroupBoxAlert();
    }
  } else {
    // display message name is required
    $("#workloadNameAlert").text(i18n.t("msg.RequiredField"));
    addVMGroupBoxAlert();
  }
};

function checkImageNameUnique(callback) {
  // get existing image name
  getExistingImageNames(function(imgNames) {
    var nameFound = false;
    if(imgNames) {
      $.each(imgNames, function (key, value) {
        if(value.name === $("#imageName").val()) {
          nameFound = true;
          // return false to break out of loop if name found
          return false;
        }
      });
    }

    callback(nameFound);
  });
};

function validateImageName(callback) {
  var valid = false;
  if (checkEmptyUploadImageName()) {
    checkImageNameUnique(function(found) {
      if (found) {
        // display message image name already exists
        $("#imageNameAlertText").text(i18n.t("msg.ImageNameAlreadyUsedInline"));
        addImageNameBoxAlert();
        valid = false;
      } else {
        // passed name checks clear box
        removeImageNameBoxAlert();
        valid = true;
      }
    });
  } else {
    $("#imageNameAlertText").text(i18n.t("msg.RequiredField"));
    addImageNameBoxAlert();
    valid = false;
  }
  if(callback) {
    callback(valid);
  }
};

function validateGroupName() {
  // get existing vm group names
  getExistingGroupNames(function(grpNames) {
    var nameFound = false;
    if(grpNames) {
      $.each(grpNames, function (key, value) {
        if(value.name === $activeInput('workloadName').val()) {
          nameFound = true;
          // return false to break out of loop if name found
          return false;
        }
      });
    }

    if(nameFound) {
      // display message group name already exists
      $("#workloadNameAlert").text(i18n.t("msg.GroupNameAlreadyUsedInline"));
      addVMGroupBoxAlert();
    } else {
      // passed name checks clear box (group button)
      removeVMGroupBoxAlert();
    }
  });
};

function downloadRCFile(data) {
  var filename = "rcFile";

  downloadFile(filename, data, true);
  $("#standbyComponent").toggleClass("hidden", true);
};

function processImageChoice() {
  var id = $("#workloadCloud").val().replace(/:/g, "\\:");
  var isPublic = $("#" + id).attr('data-type') === "public";
  var creds = $('[data-cloudIdTag="' + id + '"].authSection:not(.hidden)');
  var opt = "#" + $activeInput('workloadImage').val();
  if (isPublic && !(creds && creds.length > 0)
      && $(opt).attr("data-visibility") === "public") {
        $('#default-id-note').toggleClass("hidden", false);
      } else {
        $('#default-id-note').toggleClass("hidden", true);
      }
};

function processCloudChoice() {
  var id = $("#workloadCloud").val().replace(/:/g, "\\:");
  var isPublicCloudSelected = $("#" + id).attr('data-type') === "public";

  $('[data-cloudIdTag]').toggleClass('hidden', true);
  $activeCloud().toggleClass("hidden", false);

  $("#assign-public-ip").prop("checked", isPublicCloudSelected);
  processImageChoice();
  var creds = $activeCloud().find('.authSection');
  var inputs = $activeCloud().not('[data-attr="authSection"]').find("input, select, button, a, radio, textarea");

  inputs.attr("disabled", creds && creds.length > 0);

  $('[data-link="horizon"]').attr('href', $("#" + id).attr("data-dashboard-url"));
  if (!isPublicCloudSelected) {
    $('[data-cloud="private"]').toggleClass("hidden", false);
    $('[data-cloud="public"]').toggleClass("hidden", true);
  } else {
    $('[data-cloud="private"]').toggleClass("hidden", true);
    $('[data-cloud="public"]').toggleClass("hidden", false);
    if ($('#' + id).attr('data-hasCreds') === 'true') {
      $('[data-cloud="public"]').attr("disabled", false);
    } else {
      $('[data-cloud="public"]').attr("disabled", true);
    }
  }


  var url = $('[data-link="horizon"]').attr('href');
  if(url.indexOf('softlayer') !== -1){
    //Uncomment this when we want to hide the launchHorizon button on dashboard
    //       $('[data-cloud="public"]').toggleClass("hidden", true);
    $('#rcFile').toggleClass("hidden", false);
  } else{
    $('#rcFile').toggleClass("hidden", true);
    //        $('[data-cloud="public"]').toggleClass("hidden", false);
  }

  // TEMPORARY: Disable Horizon button if in London prod
  var hostname = window.location.hostname;
  if (hostname.indexOf(".stage1") === -1 && hostname.indexOf(".eu-gb.bluemix.net") !== -1) {
    $('[data-cloud="public"]').toggleClass("hidden", true);
    $('[data-cloud="private"]').toggleClass("hidden", true);
  }
};

function defaultSecurityGroup() {
  $everyInput('workloadSecurityGroups').each(function(idx, select) { //iterate each security group dropdown
    var options = Array.prototype.slice.call(select.options);
    var foundAllowAllSG = false;

    //iterate through each <option> within this particular security group, if "allow_all" group is there, we can safely default it
    options.forEach( function(option) {
      return foundAllowAllSG || option.value === "allow_all";
    });

    if (foundAllowAllSG) {
      //default it to allow_all until we can multi-select
      select.value = "allow_all";
    }
  });
}

function determineIfPublicCloudInProgress() {
  var reload = function() {
    location.reload();
  };
  if ($(".PublicCloudInProgress").length > 0) {
    $("#standbyComponent").toggleClass("hidden");
    $("#standbyComponent .message").toggleClass("hidden");
    $("#standbyComponent .message").html(
      i18n.t("msg.AddedToPublicCloud"));
      setTimeout(reload, 30000);
  }
};
function createLinkToInfrastructurePage() {
  var ace_config_string, ace_config, redirect, orgId, spaceId, link;
  try {
    if (window.location.hostname === "localhost") {
      //we're local, just add a link to hardcoded infrastructure page for now
      link = "http://localhost:3001/v1/clouds" + window.location.search;
    } else {
      ace_config_string = decodeURIComponent(
        window.location.search.substring(
          window.location.search
          .indexOf("?ace_config=") + 12)
      );

      ace_config = JSON.parse(ace_config_string);
      orgId = ace_config.orgGuid;
      spaceId = ace_config.spaceId;
      redirect = ace_config.redirect;
      link = redirect.split("#")[0] + "#/manage/guid=" + orgId + "&type=infrastructure";
    }
  } catch (error) {}
  if (link) {
    $("#openInfrastructurePage").attr("href", link);
  }
};

function generateButtonLinks() {
  var hostpath = getHostPath();
  var helplink = "https://www." + hostpath + "/docs/virtualmachines/vm_index.html";
  $('[data-link="viewDocs"]').attr('href', helplink);
  $('[data-link="publicKeyLearnMore"]').attr('href', helplink + "#vm_ssh_key");
  $('[data-link="termsLink"]').attr('href', "http://www." + hostpath + "/docs/navigation/notices.html#terms");
};

function downloadImage() {
  var basePath = window.location.pathname.substring(0, window.location.pathname.indexOf("/v1/") + 4);
  var cloudId = $("#workloadCloud").val().replace(/:/g, "\\:");
  var imageId = $activeInput('workloadImage').val();
  var imageName = $("#"+imageId).attr("data-name").replace(/ /g,'_');
  var url = basePath + "image/" + cloudId + "/" + imageId + "/" + imageName + window.location.search;
  if(imageName !== ""){
    $("#standbyComponent").toggleClass("hidden", false);
    downloadFile(null, url, false);
    $("#standbyComponent").toggleClass("hidden", true);
  }
};

function getImageParms() {
  //trim spaces from inputs
  $("#imageName").val($.trim($("#imageName").val()));
  $("#diskFormat").val($.trim($("#diskFormat").val()));
  var parms = {
    name: $("#imageName").val(),
    diskformat: $("#diskFormat").val()
  };

  if ($("#imageLocation").val() !== "" && $("#uploadImageType").val() === "url") {
    $("#imageLocation").val($.trim($("#imageLocation").val()));
    parms.location = $("#imageLocation").val();
  }

  if ($("#browseImageButton").val() !== "" && $("#uploadImageType").val() === "local") {
    var filePath = $("#browseImageButton").val();
    parms.file = filePath.replace(/C:\\fakepath\\/i, '');
  }

  return parms;
};

The current state of the project I inherited

(this is just one of many like it)

How might you break this up into multiple components?

document.addEventListener('DOMContentLoaded', () => {
  i18nPromise.then(() => {
    determineIfPublicCloudInProgress();
    $everyInput('default-id-note').toggleClass('hidden', true);

    CloudSelection.init();
    ImageSelection.init();
    DocsPanel.init();
    Navigation.init();
  });

  Header.init();
  SSHKey.init();
  ServerName.init();
  CreateButton.init();
  UploadScript.init();
  NetworkDetails.init();
  Credentials.init();
  DataPanel.init();

  initModals();
  initializeMultiselect();
  setDefaultSecurityGroup();
  initServerTypeButtons();

  Fab.create(document.querySelector('[data-floating-action-button]'))
  .element.classList.toggle('fab--close');
});

From 1000 lines to ~30

I will not repeat myself
I will not repeat myself
I will not repeat myself
I will not repeat myself
I will not repeat myself
I will not repeat myself
I will not repeat myself
I will not repeat myself
I will not repeat myself
I will not repeat myself
while( i < 10 ) {
    return "I will not repeat myself";
}

DRY principle

(Don't repeat yourself)

A real example

var id = $("#workloadCloud").val().replace(/:/g, "\\:");
var selector = ('[data-cloudIdTag="' + id + '"]');
var hide_selector = ('[data-cloudIdTag]:not([data-cloudIdTag="' + id + '"])');
var isPublicCloudSelected = $("#" + id).attr('data-type') === "public";
 
$(selector).toggleClass("hidden", false);
$(hide_selector).toggleClass("hidden", true);

var creds = $('[data-cloudIdTag="' + id + '"]' + ".authSection:not(.hidden)");
var inputs = $(".mainContent input, .mainContent select, .mainContent button, .mainContent a");
 
inputs.attr("disabled", creds && creds.length > 0);

This "cloud selector" code was being used / copied about 30 times throughout the code

Selection was abstracted out into a utility class

// Select every input regardless of cloud selection
export const $activeCloud = () => {
  const id = $('#workloadCloud').val().replace(/:/g, '\\:');
  return $(`[data-cloudIdTag="${id}"]`);
};
export const $everyInput = (name) => $(`[data-inputId="${name}"]`);
export const $activeInput = (name) => $activeCloud().find(`[data-inputId="${name}"]`);
// Old
workloadKey: $(".workloadKey:not(.hidden)").val(),
workloadFlavor: $(".workloadFlavor:not(.hidden)").val(),

// New
import { $activeInput } from './utils/Utils.js';

workloadKey: $activeInput('workloadKey').val(),
workloadImage: $activeInput('workloadImage').val(),

If you are like me, yesterday's code will always suck.

 

All you can do is keep iterating.

 

It's all a mindset of consistent improvement

IBM Design Thinking

Observe

 

Get to know best practices. Test new ways of thinking. Understand why people are doing things the way they are

Reflect

Look back on and learn from mistakes. Hold retrospectives on outcomes and challenges that weren't predicted.

Make

Keep coding. Things will break. Mistakes will happen. Follow best practices and keep what you have learned in mind, and keep moving forward.

Let's make that work for code

Always leave code better than it was when you opened it.

Thanks!

Give feedback / high 5s / etc

Cleaning Shit Up

By Colby Williams

Cleaning Shit Up

Refactoring, structuring code, and making our lives easier when working together by following agreed upon conventions and best practices.

  • 2,303