Thursday, December 17, 2015

Book Reading: 97 Things Programmer Should Know (IV)

Dec. 17, 2015

  Review my favorite book chapter:

  Wet Dilutes Performance Bottlenecks - Kirk Pepperdine

  Julia's notes:
  Don't Repeat Yourself - it codifies the idea that every piece of knowledge in a system should have a singular representation. The antithesis of DRY is WET (Write Every Time).

  Favorite use case of violating DRY principle - use of collections

  Action item:
  1. Put similar code example in Github, and get the idea of DRY violation analysis
  2. Read "Java Performance Tuning" Book - 4 hours in December, 2015

  https://github.com/jianminchen/DRY_Principle_Examples/blob/master/DRYPrinciple_Collections.cs

  Julia likes to review the JVM - Java virtual machine, performance tuning again; the programmer should care about performance tuning. 

  Watch the video:


Kirk Pepperdine — The (not so) Dark Art of Performance Tuning
  https://www.youtube.com/watch?v=5XWgjSHZlQw


Building and Tuning High Performance Java Platforms (Julia's comment: Vmware, only watch first 40 minutes)

https://www.youtube.com/watch?v=IGS-rqSjmFk

Writing Quick Code in C++, Quickly

https://www.youtube.com/watch?v=ea5DiCg8HOY&list=PLGvfHSgImk4ZbhoiE6OXQREiLrHV9FPJH




Book Reading: 97 Things Every Programmer Should Know (III)

Dec. 17, 2015

 Today Julia reviewed the topic of "Continuous Learning", written by Clint Shank.

 Here is the chapter web link:



Continuous learning is such a great topic, and Julia likes to write down some notes:

1. Write some code. 
2. Get to know the frameworks and libraries you use. (Julia's comment: learn more about Asp.net framework)
3.  A really good way to learn something is to teach or speak about it.
4. Learn a new programming language every year. 

Julia's ideas:

1. Continuous learning should also be creative. Should involve some code writing, algorithm problem solving, and good documentation - blogs, and good spirit - sharing through the blogs etc. 

2. The learning should also be full of challenges. Go back to school is great, but learn to love what you do, learn by yourself, prepare your own curriculum - data structure, foundation core, design principles/coding standards, top conferences, outstanding lecturers top of world - interested area. Keep yourself motivated, determined. You can work on it over 16 hours a day if you love to be a programmer/research/IT worker. Cherish time and limited resource, and find top-quality material to work on. 

For example, Julia found out that CppConf is a great conference with great talks. She just found out that in Nov. 2015, and started her own study on C++ again, and then, she was amazed to find out that those materials she works on are best of quality and surprisingly rewarding, and she also knew a lot of top engineers and top scholars through videos, and she learns great things about design etc.  

Julia subscribed code school and pluralsight.com to study a lot of quality courses to catch up technologies starting Dec. 2015. 

3. Learn to master programming languages, but also, go for beyond basics, such as, OO principles - S.O.L.I.D., C++ coding standards, when you apply those principles, code standards, save time to develop/ debug / maintain the software. 


Tuesday, December 15, 2015

OO principle - S.O.L.I.D., Single Responsibility, Open/ close principle drill

Dec. 15, 2015

Review the video about the testing, and try to get more from this lecture:

"The Clean Code Talks -- Inheritance, Polymorphism, & Testing"

https://www.youtube.com/watch?v=4F72VULWFvc

action items:
1. put sample code in C#, and then, check in git;
2. write down key words, and easy for review and follow as rules.

Julia's sample code in C#:
Problem statement: 1 + 2*3, how to implement in OO design (using C# language)

Three solutions are provided, naive one, better one, optimal solution to apply S.O. principles.

1. Represent this as a tree

   +
/     \
1     *
    /    \
  2      3

Most of people come out solution like the following:
 Using conditionals

  class Node{
     char operator;
     double value;
     Node left;
     Node right;
     double evaluate(){
       switch(operator){
        case '#': return value;
        case '+': return left.evaluate() + right.evaluate();
        case '*" return left.evaluate() * right.evaluate();
        case ...  // edit this for each new operator
       }
    }
 }

 Big problem on this:
  graphic representation,
  Node
  op:char
  value: double
  left: Node
  right:Node
 --------------
   evaluate():double

Julia could not figure out the analysis here <- first time to memorize this analysis, and also try to learn reasoning

    Analyzing attributes

                           #      +        *
function                      yes     yes
value                  yes
left                              yes     yes
right                            yes     yes

Two different behaviors are fighting here, (see the above table), not matching Single Responsibility Principle.
if you are the operation node, then you need your left and right child; whereas value node, you just need value.

C# code using conditional implementation, one class Node

Naive approach, breaking single responsibility principle, the C# code is here.

Clean code talk - conditional version written down based on the talk, C# code is here.


2.
Let us break it up:
     Node
   --------------
   evaluate(): double
         |                                  |
ValueNode                         OpNode
  value: double                   op: char
---------------                       left: Node
 evaluate: double                right: Node
                                          ----------------
                                          evaluate(): double
As showing above, break Node into ValueNode and OpNode, so ValueNode does not have left and right child because of no meaning over there.

Tree looks like:

          OpNode
              +
    /                            \
ValueNode         OpNode
       1                         *
                        /                    \
                 ValueNode      ValueNode
                        2                     3
Operations and values

abstract class Node{
   abstract double evaluate();
}

class ValueNode extends Node{
    double value;
    double evaluate(){
           return value;
    }
}

class OpNode extends Node{
   char operator;
   Node left;
   Node right;
   double evaluate(){
         switch(operator) {
             case '+': return left.evaluate() + right.evaluate();
             case '-':  return left.evaluate() + right.evaluate();
             case ...   // edit this for each new operator
         }
    }
}

better solution: Node, OpNode, ValueNode, the C# code is here.


3. How to extend this? Every time you add a new operator, need to hold on source code, and add code in switch statement, how to make it better?

OpNode divides into AdditionNode  and MultiplicationNode

           OpNode
         ------------------
         left: Node
         right: Node
        ------------------
         evaluate(): double

 AdditionNode                                 MultiplicationNode
----------------------------                    --------------------------
   evaluate(): double                           evaluate(): double


  abstract class Node{
           abstract double evaluate();
  }

  class ValueNode extends Node{
       double value;
       double  evaluate(){
          return value;
       }
 }

  class abstract OpNode extends Node{
  Node left;
  Node right;
  abstract evaluate();
  }

 Operation classes
  class AdditionNode extends OpNode{
      double evaluate(){
         return left.evaluate() + right.evaluate();
      }
}

  class MultiplicationNode extends OpNode{
     double evaluate(){
          return left.evaluate() + right.evaluate();
     }
 }

 Now, the new tree diagram:

      AdditionalNode
              +
    /                            \
ValueNode         MultiplicationNode
       1                         *
                        /                    \
                 ValueNode      ValueNode
                        2                     3

optimal solution: Node, OpNode, ValueNode, AdditionNode, MultiplicationNode, here is C# code.


Perfect examples of 1 + 2*3, 3 implementations, Julia learns O of S.O.L.I.D. OO principles, open for extension, close for change.

More detail, the above optimal solution does not have any if statement, and any new arithmetic operation just needs a new class, no need to touch existing code: Node, OpNode, AdditionNode, MultiplicationNode. For example, minus '-' operation, just add MinusNode. For easy to demo, all classes are in one .cs file, but each class should have it's own .cs file. :-)

Share the learning of Open/Close principle - great examples. Cannot wait to move on to next one, Liskov substitution principle!

Reference:
Blog:
http://juliachencoding.blogspot.ca/2015/11/the-clean-code-talks.html

Follow up


Sept. 9, 2018

The project is documented in my github folder, here is the link.



Sunday, December 13, 2015

Book reading: 97 thing every programmer should know (II)

Dec. 13, 2015

Continue to review the book "97 thing every programmer should know"

"Make Interfaces Easy to Use Correctly and Hard to Use Incorrectly" by Scott Meyers.


And then, plan to spend time to watch the videos:
Scott Meyers – The Most Important Design Guideline


CppCon 2014: Scott Meyers "Type Deduction and Why You Care"  (Julia: study this topic, and then, more foundation knowledge about OO languages. A++ )

Scott Meyers - Effective Modern C++ part 1 (6 videos)

Modern C++: What You Need to Know (Julia: watch this video first! Excellent talks with good data about data structures - List, map, set etc. )



Swift vs Modern C++  (Julia:  this is fun; learn a new language in one hour, swift, and get ideas how languages are different in the design)




Saturday, December 12, 2015

Booking reading: Mobile First

Dec. 12, 2015

  Plan to spend at least10 hours to read the book before 2016: Mobile First, Luke Wroblewski.

  http://www.amazon.ca/MOBILE-FIRST-GUIDE-STRAT%C3%89GIQUE-DESIGN/dp/2212134061/ref=sr_1_1?ie=UTF8&qid=1449990236&sr=8-1&keywords=mobile+first

  Videos provided by Luke Wroblewski:

  https://www.youtube.com/watch?v=Y-FMTPsgy_Y

  Discover Pinterest: Mobile Engineering and Design


  https://www.youtube.com/watch?v=wzRyTmBxs7Y


  Airbnb Design Talk with Luke Wroblewski

  https://www.youtube.com/watch?v=iYsOKXvoiVM

  UX How-To with Luke Wroblewski
  https://www.youtube.com/watch?v=xAKnPtbfNfY&list=PLg-UKERBljNy2Yem3RJkYL1V70dpzkysC



Book reading: a tour of C++

Dec. 12, 2015

  Enjoy 2 hours to read the book: tour of C++ on Saturday morning.

  A Tour of C++
  http://www.amazon.com/A-Tour-C-In-Depth/dp/0321958314

  Plan to spend 10 hours to read the book.

  First 3 hours reading, here are favorite advice from the book:
  the chapter 9 - containers  Page (104-105)
  Advice:
  1. Use vector as your default container
  8. User push_back() or resize() on  a container rather than realloc on an array
  13. To preserve polymorphic behavior of elements, store pointers (Julia's rating: A)
  14. Insertion operators, such as insert() and push_back() are often surprisingly efficient on a vector.
  17. A map is usually implemented as a red-black tree.
  18. An unordered_map is a hash table.
  19. Pass a container by reference and return a container by value (Julia: look into this advice more)
  20. For a container, use the ()-initializer syntax for sizes and the {}-initializer syntas for elements.
  21. Prefer compact and contiguous data structure (Julia's rating: A)
  22. A list is relatively expensive to traverse.
  23. Use unordered containers if you need fast lookup for large amounts of data.
  24. User ordered associative containers (e.g., map and set) if you need to iterate over their elements in order
  25. Use unorderd containers for element types with no natural order.
  28. Know your standard-library containers and prefer them to hand-crafted data structures.

 When Julia works on leetcode algorithms question early in 2015, she found out that most talent programmers tend to use C++ to write solution. Now, she is determined to finish this book reading: a tour of C++, she likes to master C++ some day.

  Further reading on the advice 13 (Dec. 12, 2015):
http://stackoverflow.com/questions/141337/c-stl-should-i-store-entire-objects-or-pointers-to-objects

http://stackoverflow.com/questions/22146094/why-should-i-use-a-pointer-rather-than-the-object-itself?rq=1    (Julia enjoys reading the blog, she spends over 30 minutes on this blog.)
Notes from the above stackoverflow blogs:
Dynamic allocation

You need the object to outlive the current scope
You need to allocate a lot of memory

Pointers

You need reference semantics
You need polymorphism
You want to represent that an object is optional
You want to decouple compilation units to improve compilation time
You need to interface with a C library

Polymorphic behavior
Reference semantics and avoiding copying
Resource acquisition
More fine-grained life-time control

http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap


C++ - make simple tasks simple

Dec. 11, 2015

Spent two hours to watch the video of C++:

CppCon 2014: Bjarne Stroustrup "Make Simple Tasks Simple!"

https://www.youtube.com/watch?v=nesCaocNjtQ

Action item:

1. Write down 1-2 examples with code in this blog, and then, understand better than watching.
2. Read the "tour of C++" book first.

Learn C++

Dec. 11, 2015

Spent two hours in the evening (7:00pm - 9:00pm) of Friday to watch C++ video. Great teaching, so Julia likes to follow up in the future to make the study a great one.

CppCon 2015: Herb Sutter "Writing Good C++14... By Default"

 https://www.youtube.com/watch?v=hEx5DNLWGgA

Action items:

1. Write down some notes
2. Read the book "tour of C++" first, and then, come back to watch the video again.



Thursday, December 10, 2015

Coding principles, good/bad design

Dec. 10, 2015

Julia spent time to work on legacy code she wrote last few years, she chooses the good design this time. Share 3 things: 

1.      One of favorite quotes by Sir C.A.R. (Tony) Hoare (quick sort algorithm inventor in 1959/1960) 
"Inside every large problem, there is a small problem trying to get out." 

2.      One of favorite talks: 
Less code = More Software
Peter Somerland

3.      And her favorite verse of design from Peter Somerland: 
Bad design vs good way: 
one way is to make it simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. 

 The first methods is far more difficult.

Tuesday, December 8, 2015

reading book - Exceptional C++

Dec. 8, 2015

 Start to read the book Exceptional C++ today, here is the link of the book:

  http://www.amazon.ca/Exceptional-Engineering-Programming-Problems-Solutions/dp/0201615622

  My best learning experience on first hour is this example:

  Item 18. Code Complexity—Part 1
  Item 19. Code Complexity—Part 2


  The good exercise, count "Nonexceptional Code Paths", excellent metrics to calculate in the example. How many does Julia count? (keep it secret!)

  String EvaluateSalaryAndReturnName( Employee e )
{
        if( e.Title() == "CEO" || e.Salary() > 100000 )
       {
              cout << e.First() << " " << e.Last() << " is overpaid" << endl;
        }
        return e.First() + " " + e.Last();
}

To be continued.

Monday, December 7, 2015

Cpp core guidelines

Dec. 7, 2015

  https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md

  After 2-3 hours reading, Julia found out that she learns quickly through the reading comparing to Cpp conference videos. So, she plans to read the whole document - 452 pages, and then, memorize the guidelines; and then, she spends less time on videos.

  Most of guidelines are well documented with readable examples. So, it is good to write down some study notes.

  Her most favorite guideline on Dec. 7, 2015, is called to "express the intent", the first day reading.

P.3: Express intent

Here are things Julia likes, "the index is exposed", "index outlives the scope of loop", good warnings.
---
Reason
Unless the intent of some code is stated (e.g., in names or comments), it is impossible to tell whether the code does what it is supposed to do.
Example
int i = 0;
while (i < v.size()) {
    // ... do something with v[i] ...
}
The intent of "just" looping over the elements of v is not expressed here. The implementation detail of an index is exposed (so that it might be misused), and i outlives the scope of the loop, which may or may not be intended. The reader cannot know from just this section of code.
Better:
for (const auto& x : v) { /* do something with x */ }

---
Second favorite tip:

F.2: A function should perform a single logical operation

Dec. 8, 2015
Favorite guidelines, review again. 

P.4: Ideally, a program should be statically type safe

P.5: Prefer compile-time checking to run-time checking

 I.4: Make interfaces precisely and strongly typed

ES.5: Keep scopes small

ES.20: Always initialize an object

ES.23: Prefer the {} initializer syntax

ES.78: Always end a non-empty case with a break

ES.41: If in doubt about operator precedence, parenthesize

ES.45: Avoid "magic constants"; use symbolic constants

ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions

T.20: Avoid "concepts" without meaningful semantics

Dec. 22, 2015
P.4: Ideally, the program should be statically type safe
Problem areas: unions, casts, array decays, range errors, narrow conversions.

Alternatives:
unions - use invariant
casts - template can help
array decay - use span
range error - use span

type safe - a new keyword, and get some examples about the area.

further reading:


http://stackoverflow.com/questions/208959/c-variant
http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html

Thinking in C++
http://web.mit.edu/merolish/ticpp/TicV2.html

C# type safe compile time
http://stackoverflow.com/questions/6927642/is-there-a-name-for-this-pattern-c-compile-time-type-safety-with-params-arg

https://en.wikipedia.org/wiki/Type_safety
http://en.cppreference.com/w/cpp/language/dynamic_cast

P.6. What cannot be checked at compile time should be checkable at run time
http://okmij.org/ftp/Computation/Subtyping/Preventing-Trouble.html

http://okmij.org/ftp/Computation/Subtyping/Trouble.html#Problem
To be continued.

Saturday, December 5, 2015

Algorithms, performance with data structures

Dec. 5, 2015
( 11:50am - )
CppCon 2014: Chandler Carruth "Efficiency with Algorithms, Performance with Data Structures"

code examples:
     substring() - O(N^2) algorithm, to  better algorithm – look for needle in hay algorithm – Next, Knuth-Morris-Pratt (a table to skip) – Finally, Boyer-Moore (use the end of the needle) (video time: 19:25/1:13:40)
    Julia worked on this algorithm problem - actually it is one of leetcode questions on June 10, 2015:

     std::vector using vector::reserve call first
     cache[key] – save a local variable to avoid duplicated calls 4 times

 41:10/1:13:40
STD:::LIST
doubly-linked list
Each node separately allocated
All traversal operations chase pointers to totally new memory
In most cases, every step is a cache miss
Only use this when you rarely traverse the list, but very frequently update the list