X Class Solar Flare Sends ‘Shockwaves’ on The Sun

Creating a Todo class

In this series on refactoring an AngularJS todo app, so far we’ve created a class for our controller and started extracting the logic within the controller’s methods to separate functions.

Currently we’ve got this in our Controller class:

class Controller {
  constructor() {
    this.todos = [
      { text: "learn AngularJS", done: true },
      { text: "build an AngularJS app", done: false },
    ];
  }

  addTodo() {
    this.todos.push(
      { text: this.todoText, done: false }
    );
    this.todoText = "";
  }
  ...
}

Enforcing structure

When defining this.todos, there’s nothing currently enforcing any sort of structure. What’s to keep me from adding a todo with {dog: ‘bark’, bananas: true}? We might then end up with a todo with perfectly valid data, but the structure wouldn’t match what the template is expecting.

We can fix this by creating a Todo class like this:

class Todo {
  constructor(text, done = false) {
    this.text = text;
    this.done = done;
  }
}

Since new todos would likely not be marked as “done”, we’re setting the default done property to false. That way new todos are easier to generate and read.

// Old way:
const todo1 = { text: "learn WordPress", done: false };

// New way, which now defaults to not done:
const todo2 = new Todo(“learn React”);

// New way, when wanting to override the default
const todo3 = new Todo(“learn AngularJS”, true);

Making code easier to read

Remember that addTodo method that was a little difficult to read? Now it makes more sense:

class Controller {
  constructor() {
    this.todos = [
      new Todo("learn AngularJS", true),
      new Todo("build an AngularJS app"),
    ];
  }

  addTodo() {
    this.todos.push(new Todo(this.todoText));
    this.todoText = "";
  }
  ...
}

Next time we’ll take a look at the functions we’re using for getting the remaining todos and archiving todos, and see if there are ways to refactor them even further.


Discover more from AaronTweeton.com

Subscribe to get the latest posts sent to your email.