Showing posts with label computer science. Show all posts
Showing posts with label computer science. 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

Tuesday, June 30, 2020

Networking 101

Some people know a lot about computer networking. I know a bit about human networking but very little about computer networking. Since I am writing a story these days and I am naturally curious, this post would be a helpful reference for myself and others. Expect periodic updates!

TTEthernet
The Time-Triggered Ethernet (SAE AS6802) (also known as TTEthernet or TTE) standard defines a fault-tolerant synchronization strategy for building and maintaining synchronized time in Ethernet networks, and outlines mechanisms required for synchronous time-triggered packet switching for critical integrated applications, IMA and integrated modular architectures.

References:
https://en.m.wikipedia.org/wiki/TTEthernet


Wednesday, August 28, 2019

Words That Sound Badass

 

Semantic Segmentation

Image segmentation is a computer vision task in which we label specific regions of an image according to what's being shown.

https://www.jeremyjordan.me/semantic-segmentation/

https://hackernoon.com/semantic-segmentation-datasets-for-autonomous-driving-1182ebd2aff0

Regression Testing

Regression Testing is defined as a type of software testing to confirm that a recent program or code change has not adversely affected existing features. Regression Testing is nothing but a full or partial selection of already executed test cases which are re-executed to ensure existing functionalities work fine.

Simple Network Management Protocol (SNMP) 

Simple Network Management Protocol (SNMP) is an application–layer protocol defined by the Internet Architecture Board (IAB) in RFC1157 for exchanging management information between network devices. It is a part of Transmission Control Protocol⁄Internet Protocol (TCP⁄IP) protocol suite.

Michel Thomas Method

Michel Thomas was a language teacher with a specific approach to teaching. Thomas proposed that there is no such thing as "a student with learning difficulties, only teachers with teaching difficulties." The method presents the target language by interleaving new with old material, teaching generalization from language principles, contextual diversity, and learning self-correction in an environment that attempts to be stress-free, as the teacher is responsible for learning, not the student.

https://www.michelthomas.com

Monday, April 18, 2011

[IT] Advantages of Hexadecimal



If you work with computers on some level beyond Microsoft Office or browsing the net, at some point, you will run across hexadecimals. What are they and why do people bother using them when they seem something better left for assembly programmers?

Hexadecimal is just a base-16 number system. We humans because we grew up in a society where most of us has 10 fingers, use the decimal system for the most part. In hex, in addition to the numerals 0-9 to represent values zero through nine, we also have letters A-F to represent values ten through fifteen.

Consider the number 10995. In decimal system, we have
(1 x 10^4) + (0 x 10^3) + (9 x 10^2) + (9 x 10^1) + (5 x 10^0) = 10995

In hexadecimal system, we have 2AF3:
(2 × 16^3) + (10 × 16^2) + (15 × 16^1) + (3 × 16^0) = 2AF3

What's important is to realize that numbers are abstract counting notions which can have infinite ways of displaying in reality. Actually, base 10 really offers no advantage to us except that we humans are born with 10 fingers and toes which make it easier for us to count. We could use base-23 or base-159 for no good reason.

However, there are distinct advantages to using hexadecimal in computer science:

1. You can store more information in the same space. In a hex code with two digits you can express the numbers 0 through 255. In a decimal code with two digits you can count from 0 to 99.

2. Hexadecimal (base 16) converts easily to binary (base 2), which is used by computers at the fundamental level. A two digit hexadecimal number can range from 0 to 255, which can be expressed in eight digits of binary code.

Programmers sometimes like to throw around dorky jokes that ordinary people won't get. The following is a good test to see how dorky you are:

3x12=36
2x12=24
1x12=12
0x12=18

Programmers typically put 0x in front of a number that's in hex base. This way, people don't get confused. So here, the first three lines are interpreted as multiplication while the last is considered the hex interpretation of 12, which is (1 x 16^1) + (2 x 16^0) or 18.

Here's a better one:

Q: Let’s say only you and dead people can read hex. If you teach your buddy how to read hex also, what do you all have in common?
A: You are all deaf.

If you need an explanation, you're still not quite a dork. Work on it though! Still, for completeness, explanation: "dead" refers to a hexadecimal number DEAD (57005 base 10), as opposed to the state of not being alive. With you and your friend, that's two more to the group, so add 2 to D to get F. Hence, DEAD + 2 = DEAF.

Sunday, April 17, 2011

[IT] Short Discourse on Encoding (ASCII, UTF-8, etc.)

As Joel Spolsky, the co-founder of Frog Creek Software and the very popular blog/company Stack Overflow, says, every programmer ought to know about the basics of encoding considering how many of us don't. It's really quite sad. So this will be a brief gist of what I gleaned from reading his article.

In the old days when English still dominated the computer world, a code called ASCII was able to represent every character using a number between 32 and 127. Space was 32, the letter "A" was 65, etc. This could conveniently be stored in 7 bits. Most computers in those days were using 8-bit bytes, so not only could you store every possible ASCII character, but you had a whole bit to spare. Code below 32 were unprintable and were used for control purposes like 7 which made the computer beep.

But the codes from 128-255 were left entirely open to the geographic region's inclination. For example on some PCs the character code 130 would display as é, but on computers sold in Israel it was the Hebrew letter Gimel (ג), so when Americans would send their résumés to Israel they would arrive asrגsumגs.

The eventual adopted ANSI standard secured all agreements below 128 but left what's above 128
to your regional taste. Before the Internet this whole patch of mess worked to a degree but as soon
as the Internet came in, something had to change. Enter Unicode.

Unicode

Some people are under the misconception that Unicode is simply a 16-bit code where each character takes 16 bits and therefore there are 65,536 possible characters. This is not, actually, correct. It is the single most common myth about Unicode, so if you thought that, don't feel bad.

In fact, Unicode makes you think a different way about encoding characters. Until now, we've assumed that a letter maps to some bits which you can store on disk or in memory:

A -> 0100 0001

In Unicode, a letter maps to something called a code point which is still just a theoretical concept. How that code point is represented in memory or on disk is another story.

Every platonic letter in every alphabet is assigned a magic number by the Unicode consortium which is written like this: U+0639. This magic number is called a code point. The U+ means "Unicode" and the numbers are hexadecimal. U+0639 is the Arabic letter Ain. The English letter A would be U+0041.

Encodings

The earliest idea for Unicode encoding, which led to the myth about the two bytes, was, hey, let's just store those numbers in two bytes each. So Hello becomes

00 48 00 65 00 6C 00 6C 00 6F

Couldn't it also be:

48 00 65 00 6C 00 6C 00 6F 00 ?

the people were forced to come up with the bizarre convention of storing a FE FF at the beginning of every Unicode string; this is called a Unicode Byte Order Mark and if you are swapping your high and low bytes it will look like a FF FE.

For a while it seemed like that might be good enough, but American programmers were complaining. English rarely used code points above U+00FF and the thought of wasted bytes shocked them. Besides, who's going to convert the ASCII character sets over?

Thus was invented UTF-8. UTF-8 was another system for storing your string of Unicode code points, those magic U+ numbers, in memory using 8 bit bytes. In UTF-8, every code point from 0-127 is stored in a single byte. Only code points 128 and above are stored using 2, 3, in fact, up to 6 bytes.

This has the neat side effect that English text looks exactly the same in UTF-8 as it did in ASCII, so Americans don't even notice anything wrong. Only the rest of the world has to jump through hoops. Specifically, Hello, which was U+0048 U+0065 U+006C U+006C U+006F, will be stored as 48 65 6C 6C 6F.

There are actually loads of other encoding out there but since December 2007, the most popular encoding on the web has been UTF-8 so it'll be good to know more about it. It's important to know the encoding for messages over the web. No such thing as plain text anymore!

For an email message, you are expected to have a string in the header of the form

Content-Type: text/plain; charset="UTF-8"

For a web page, the original idea was that the web server would return a similar Content-Type http header along with the web page itself -- not in the HTML itself, but as one of the response headers that are sent before the HTML page.

It would be convenient if you could put the Content-Type of the HTML file right in the HTML file itself, using some kind of special tag. Of course this seems to be a Catch-22: "how can you read the HTML file until you know what encoding it's in?!" Luckily, almost every encoding in common use does the same thing with characters between 32 and 127, so you can always get this far on the HTML page without starting to use funny letters:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

But that meta tag really has to be the very first thing in the section because as soon as the web browser sees this tag it's going to stop parsing the page and start over after reinterpreting the whole page using the encoding you specified.

What if a poorly informed web designer doesn't put this tag though? Apparently, every browser does something different to try to guess the character set. Sometimes, they get it right. Sometimes wrong which you the web browser will have to try to figure out what encoding the web designer actually meant for you to use. Is it Chinese? Hindi? Arabic? Good luck!

Thus comes the central point that for every web document you code up, be sure to include the encoding type!

For his whole article, I heartily recommend reading it here: