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


C++, coding standards, and code refactoring

Dec. 5, 2015

Surprised that C++ is such a popular programming language, a few days study, Julia was so amazed and she likes to learn C++ again; a lot of coding standards, C++ guidelines also applies to the programming languages she uses, C#, OO programming.
CppCon 2014: James McNellis & Kate Gregory "Making C++ Code Beautiful"
https://www.youtube.com/watch?v=BiYliKliFvs


CppCon 2014: James McNellis & Kate Gregory "Modernizing Legacy C++ Code"
https://github.com/CppCon/CppCon2014/tree/master/Presentations
video 26:46/59:20
Keep Functions Linear
Functions that have mostly linear flow are easier to understand
and easier to modify during maintenance and bug fix

Recommendations:
Eliminate complexity introduced by the preprocessor
Refactor functions to linearize and shorten them
Update any manual resource management to use RALL
Litter your code with the const qualifier
Convert C casts to C++ casts
Use algorithms instead of loops
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md

Surprised that C++ is such a popular programming language, a few days study, Julia was so amazed and she likes to learn C++ again; a lot of coding standards, C++ guidelines also applies to the programming she uses, C#, OO programming, and are great. 
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md

Friday, December 4, 2015

Coding standards - quick review


Dec. 4 , 2015

https://www.youtube.com/watch?v=zW-i9eVGU_k

CppCon 2015: Titus Winters "Lessons in Sustainability...”

video 38:00/1:09
Policies
You need ways to guide the codebase.What if everyone writes their own hash?
. style guides. Strongly encourage consistency and safety
. Code review, and take it seriously - encourage sane code
. Best practices - lightly encouraged guidance
. Readability - Require responsible supervision, mentorship
. Churn policies - encourage responsible infrastructure chanage.



Read the book:
C++ Coding Standards
101 Rules, Guidlines, and Best Practices
written by Herb Sutter, Andrei Alexandrescu

Julia understood that being a smart software developer, better spend time to work on coding standard, design principles, rules first, and then, develop some quality product with confidence.

Find 10 rules - most favorite ones.

Wednesday, December 2, 2015

C++ - write quick code in C++

Dec. 2, 2015

Julia likes to watch more C++ videos before she plans to write more Leetcode question using C# programming language. She likes to learn C++ by going through CppCon videos. Amazed that it is so easy to find high quality talk through the conference.

Read the book in short future (180 pages):
A tour of C++
( Dec. 3, 2015, read 1 hour, review Union, Enumeration (2.4, 2.5) )

videos:

CppCon 2014: Herb Sutter "Back to the Basics! Essentials of Modern C++ Style"

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

Writing Quick Code in C++, Quickly

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

CppCon 2015: Bjarne Stroustrup “Writing Good C++14”

https://www.youtube.com/watch?v=1OEu9C51K2A

CppCon 2015: Gabriel Dos Reis “Contracts for Dependable C++"

https://www.youtube.com/watch?v=Hjz1eBx91g8  ( Julia's rating: A, easy to understand, and will follow good contracts - write precondition, postcondition, invariant)

video 34:12/55:48 (Dec.4, 2015)
Semantics
- Precondition [[expects: condition]]
1. Arguments are evaluated
2. Condition is evaluated
3. Out-of-contract counter-measure deployed if contract violated
4. First statement of the user-authored function body executed

- Postcondition: [[ensures: condition]]
1. User-authored function boday executed (expected return)
    . Return expression, if any, evaluate
2. condition is evaluated
3. Out-of-contract counter-measure deployed if contract violated
4. Control transferred to caller.

CppCon 2015: Neil MacIntosh “Evolving array_view and string_view for safe C++ code"

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

https://github.com/isocpp/CppCoreGuidelines/tree/master/talks