SOLID-ly functional

Some thoughts about the

Single Responsibility Principle

Code

SOLID

A class should have only one reason to change

A class function should have only one reason to change

function saveName(ev) {
  ev.preventDefault();

  var name = $('input.name').val();
  localStorage.setItem('name', name);
  $('p.name-display').text(name); 
}

$('form').on('submit', saveName);
var input = $('input.name');
var display = $('p.name-display');
var nameId = 'name';

// Save and display when a new name is entered
$('form').on('submit', function handleSubmit(ev) {
  ev.preventDefault();
  var name = getName();
  save(nameId, name);
  display(name);
});

// Display the name when the page loads
display(fetch(nameId));

// An abstraction layer emerges... 
function save(id, value) {
  localStorage.setItem(id, value);
}

function fetch(id) {
  localStorage.getItem(id);
}

function display(value) {
  display.text(value);
}

function getName() {
  return input.val();
}

A principle by any other name...

Simple, right?

THANKS!

 

Jared Stilwell

Señor UI Engineer

RetailMeNot

@meany_face

Made with Slides.com