Code quality and testing were the topics today. Code quality was related to code style, comments, and testing with mocha.

Code style was a more of a common sense topic along with comments. Code style is sticking with me since I am seeing examples of how to write clean code throughout javascript.info, freecodecamp, and w3schools. Just make sure things are well spaced out and not cluttered together.

The type of comments to leave were detailed. Good rule of thumb is that if your code is so unclear that it requires a comment, just rewrite the code. Avoid using self explanatory comments and comments if possible. However, if you cannot, comment in regards to the architecture and function usage.

Besides code styles, I learned about testing in development so that bugs do not occur in the final product. Debugging through console is one way to fix errors, however that manual process is tedious. There is an automated way to fix errors which is through behavior driven development. BDD is three things tests, documentation, and examples.

The example of BDD used in the course was creating a spec.

describe("pow", function() {

  it("raises to n-th power", function() {
    assert.equal(pow(2, 3), 8);
  });

});

A spec has three main building blocks that you can see above:describe("title", function() { ... })

What functionality we’re describing. Uses to group “workers” – the it blocks. In our case we’re describing the function pow.it("title", function() { ... })

In the title of it we in a human-readable way describe the particular use case, and the second argument is a function that tests it.assert.equal(value1, value2)

The code inside it block, if the implementation is correct, should execute without errors.

Functions assert.* are used to check whether pow works as expected. Right here we’re using one of them – assert.equal, it compares arguments and yields an error if they are not equal. Here it checks that the result of pow(2, 3) equals 8.

The flow of development usually looks like this:

  1. An initial spec is written, with tests for the most basic functionality.
  2. An initial implementation is created.
  3. To check whether it works, we run the testing framework Mocha (more details soon) that runs the spec. Errors are displayed. We make corrections until everything works.
  4. Now we have a working initial implementation with tests.
  5. We add more use cases to the spec, probably not yet supported by the implementations. Tests start to fail.
  6. Go to 3, update the implementation till tests give no errors.
  7. Repeat steps 3-6 till the functionality is ready.

It’s just rinse and repeat from there using JavaScript libraries of mocha, chai, and sinon.

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: