Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts

Saturday, October 3, 2020

Clean Code: 5 Takeaways

 I haven't read this book Clean Code by Robert C. Martin but I heard it was good. I did read the synopsis here by this Medium author and I think I'll take his word for it. Here's a few things that I just copied and pasted from his article.*

Published in 2008, and over recent years, it has consistently ranked as one of the top five highest-selling books on Amazon. The author, affectionately known as “Uncle Bob,” was one of the original authors of the Agile Manifesto and has some serious credentials. The book has achieved an average rating of 4.4 on Goodreads from over 13,000 ratings. Suffice to say, it’s one of those books every programmer should read.

1. Programming is a craft.

But how do we go from simply writing code to crafting code?

According to Martin, the main tools we have at our disposal are continuous refactoring and test-driven development (TDD). These work together like two sides of a coin. Here are some definitions:

Refactoring is the process of restructuring existing computer code without changing its external behavior.

Test-driven development is a process where requirements are turned into specific test cases, then the code is added so the tests pass.

So, the process of crafting software might look something like this:

  1. Write failing tests that verify the required but unimplemented behaviour.
  2. Write some (potentially bad) code that works and makes those tests pass.
  3. Incrementally refactor the code, with the tests continuing to pass, making it more clean with each development iteration.

2. Keep it short!

According to Martin this means two things:

  • Function bodies should be short — hardly ever longer than 20 lines and mostly less than 10 lines
  • Functions should take as few arguments as possible, preferably none

Function brevity makes code easier to read. It also steers us towards a situation where functions do one thing — and do it well.

He makes a similar point about classes. With classes, he suggests using responsibilities as the measure of size rather than lines of code. The idea is a class should only be responsible for one thing. This is known as the single responsibility principle (SRP).

Keeping entities short is a divide-and-conquer strategy for making code cleaner. If we have a big file with lots of lengthy, complicated code, we can divide that file into modules, divide the modules into functions, and divide functions into subfunctions until the logic and intent are clear.

3. Make code self-documenting.

In the sections on comments, meaningful names, and formatting, Martin makes a strong case for code being self-documenting. An example of this is given as follows:

// Check to see if the employee is eligible for full benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))

This gets refactored to

if (employee.isEligibleForFullBenefits())

Note:

  • The comment is removed
  • The conditional logic is encapsulated into a method
  • Because a method is used and not a free-standing function, instance variables can be used, creating a zero-argument method call
  • The method is given a descriptive name, making its responsibility super clear

There's a full chapter on naming, which is essentially an elaboration on Tim Ottinger’s rules. These include:

  • Use intention-revealing names — e.g, int elapsedTimeInDays, not int days
  • Use pronounceable names — e.g., Customer, not DtaRcrd102
  • Avoid encodings — don’t use an m_ prefix for members and don’t use Hungarian notation
  • Pick one word per concept — don’t fetch, retrieve, get for the same concept

 4. Respect abstraction.

If we want to make sure our functions are only doing one thing, we need to make sure the statements within each function are all at the same level of abstraction.

public String render() throws Exception
{
  StringBuffer html = new StringBuffer("<hr");
  if (size > 0)
    html.append(" size="").append(size + 1).append("\"");
  html.append(">");
  
  return html.toString();
}

This is refactored to

public String render() throws Exception
{
  HtmlTag hr = new HtmlTag("hr");
  if (extraDashes > 0)
    hr.addAttribute("size", hrSize(extraDahses));
   return hr.html();
 }
 
private String hrSize(int height)
{
  int hrSize = height + 1;
  return String.format("%d", hrSize);
}

Notes:

  • The render() function is now only responsible for constructing an hr tag
  • The low-level details of constructing the tag are now delegated to the HtmlTag module
  • Size formatting is abstracted into a separate function

5. Clean code is about principles and hard work.

“Clean code is not written by following a set of rules. You don’t become a software craftsman by learning a list of heuristics. Professionalism and craftsmanship come from values that drive disciplines.” — Robert C. Martin

*https://medium.com/better-programming/clean-code-5-essential-takeaways-2a0b17ccd05c

Wednesday, April 1, 2020

Interactive Fiction for Fun





Stealing Wikipedia's definition, Interactive fiction, often abbreviated IF, is software simulating environments in which players use text commands to control characters and influence the environment. Works in this form can be understood as literary narratives, either in the form of interactive narratives or interactive narrations.

IF happens to be a gem of a genre for someone like me who loved to read choose-your-own-adventure novels when I was a kid. To have books with destinies decided not just by the author but by the reader was astounding to me. Besides, I frequently look at my own life this way. What if I chose to go to the park instead of just staying in that day? What if I decided to kiss the girl on the date instead of not? What if I decided to cook curry instead of fish? The most trivial choices can lead to momentous results.

Perhaps because of this, I was intrigued when I discovered Twine -- an open source tool for creating interactive fiction. Check it out: http://twinery.org/

Here are a few examples of works that people in this community have created. I am not saying they're the best stories but they can be interesting to read.


https://tayruh.github.io/monster

http://slimedaughter.com/games/twine/wtwla/ 
Strange but beautiful I hear (with music).

http://mirror.ifarchive.org/if-archive/games/competition2013/web/solarium/solarium.html#1e

https://philome.la/winningcake/a-trial/play/index.html

http://ifarchive.org/if-archive/games/competition2018/Bogeyman/bogeyman.html

For more games, you can check out what other people are playing:
https://intfiction.org/c/playing