Make a Person Avoiding Repetition Advice

Tell us what’s happening:
Hi, everyone,

My code is running fine and passing all the tests.

However, I am wondering if there would be a way to avoid repeating var names = firstAndLast.split(' '); inside this.setFullName.

I guess I could make var names be a function, but I can’t put my finger on how I could make that do what I want.

I’d appreciate your advice on this.

Thanks a lot!

Your code so far


var Person = function(firstAndLast) {
  var names = firstAndLast.split(" ");
  this.getFullName = function() {
    return names.join(" ");
  };
  this.getFirstName = function() {
    return names[0];
  }
  this.getLastName = function() {
    return names[1];
  }
  this.setFirstName = function(first) {
    names[0] = first;
  }
  this.setLastName = function(last) {
    names[1] = last;
  }
  this.setFullName = function(firstAndLast) {
    var names = firstAndLast.split(' ');
    this.setFirstName(names[0]);
    this.setLastName(names[1]);
    return this.getFullName;
  }
  return firstAndLast;
};

var bob = new Person('Bob Ross');

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36.

Link to the challenge:

You can’t avoid repetition because you have to split the names string at those points – once when Person is initialised, and once when a new name string is provided. You cannot avoid this, the program cannot work if you don’t do it, there’s nothing wrong with it.

You could wrap it in a function, but that would be pointless – it’s still repetition, and for the sake of changing the name of something to pretend it’s cleaner code you’d be adding a needless extra function call.

If you are looking to refactor some code to avoid repeating things (this is not one of these situations), then probably wait until you’ve had to copy paste something at least three or four times before you even start thinking about it at all

Thank you, Dan! That’s good to hear. Perhaps I am trying too hard to stick to the DRY rule.

Alternatively, you could convert this into an ES6 Class and use arrow functions to tighten up the code.

class Person {
  constructor(firstAndLast){
  let names = firstAndLast.split(' ');
  this.getFullName = () => names.join(' ');
  this.getFirstName = () => names[0];
  this.getLastName = () => names[1];
  this.setFirstName = first => names[0] = first;
  this.setLastName = last => names[1] = last;
  this.setFullName = name => names = name.split(' ');
}
}

let bob = new Person('Bob Ross');
bob.getFullName();