Upload
chao-kung-liu
View
142
Download
0
Embed Size (px)
Citation preview
Who is this sharing for?
• Who wants to read this book
• Who wants to be a good programmer
• Who wants to know how to solve problems like the master
• Who codes in C&C++
Who is the speaker?Programming Skills :
•6 years experience in C#• Information Exchange• Internal API
•3 years experience in JAVA• Real-time quotes server
•2 years experience in C&C++• WFBS 8.0 , WFBS 9.0• OSCE 10.6 SP3, OSCE 11
Juggernaut Liu
Style
• Writing code that works well and is a pleasure to read
–Programs are read not only by computers but also by programmers!
• If you work on a program you didn’t write, preserve the style you find there.– The Boy Scout Rule : – Always leave the campground cleaner than you found it.
• Once styling the program become automatic, your subconscious will take care of many of the details for you, and even the code you produce under pressure will be better!
Style – Naming(1)
● A name should be informative, concise, memorable, and pronounceable if possible.
● Use descriptive names for globals, short names for locals.○brief comment with the declaration of each global variable
● Sample:
Style – Naming(2)
• Use active names for functions. – Function names should be based on active verbs, perhaps
followed by nouns.
Style – Naming(3)
• Be accurate. – A name not only labels, it conveys information to the reader. A
misleading name can result in mystifying bugs.
• Bad Samples:– Originally, PhoneString phoneString– Now, PhoneNumber phoneString
Style – Expressions and Statements(1)
• Use the natural form for expressions. – Write expressions as you might speak them aloud
Style – Expressions and Statements(2)
• Parenthesize to resolve ambiguity. – Parentheses specify grouping and can be used to make the intent
clear even when they are not required
Style – Define numbers
• Define numbers as constants, not macros
• Effective C++ item 2: Prefer consts, enums, and inlines to #defines.
Style – Comments• Don’t belabor the obvious
• Comment functions and global data• Don’t contradict the code
Design
• "In the end, only familiarity with the tools and techniques of the field will provide the right solution for a particular problem, and only a certain amount of experience will provide consistently professional results.“
– Raymond Fielding. The Technique of Special Effects Cinematography
Design
• A good algorithm or data structure might make it possible to solve a problem in seconds that could otherwise take years.
• Assess potential algorithms and data structures. Consider how much data the program is likely to process.
• It best to start detailed design with data structures, guided by knowledge of what algorithms might be used.
Design
• Use a library or language feature if you can.
• Write or borrow a short, simple, easy to understand implementation.
• Production code takes much more effort than prototypes do.
Interfaces - The issues to be worked out
• Interfaces: – What services and access are provided?
• Information hiding: – What information is visible and what is private?
• Resource management: – Who is responsible for managing memory and other limited
resources?
• Error handling: – Who detects errors. who reports them, and how?
Interfaces – Principles(1)
• Hide implementation details
– The implementation behind the interface should be hidden from the rest of the program so it can be changed without affecting or breaking anything
– Avoid global variables
– Classes in C++ and Java are better mechanisms for hiding information
Interfaces – Principles(2)
• Choose a small orthogonal set of primitives
– An interface should provide as much functionality as necessary but no more, and the functions should not overlap excessively in their capabilities.
– Narrow interfaces are to be preferred to wide ones
– Do one thing, and do it well.– Don’t add to an interface just because it’s possible to do so
Interfaces – Principles(3)
• Don't reach behind the user's back
– A library function should not write secret files and variables or change global data, and it should be circumspect about modifying data in its caller.
Interfaces – Principles(4)
• Do the same thing the same way everywhere.
– Consistency and regularity are important.
Interfaces – Resource Management
• Free a resource in the same layer that allocated it
• C++ constructors and destructors help enforce this rule
• The existence of automatic garbage collection does not mean that there are no memory-management issues in a design
Interfaces – Error handling
● Detect errors at a low level, handle them at a high level
● Use exceptions only for exceptional situations○ Exceptions should not be used for handling expected
return values
Debug - Advice on Good Clues, Easy Bugs• Look for familiar patterns
– Ask yourself whether this is a familiar pattern
• Examine the most recent change– Looking carefully at recent changes helps to localize the problem
• Get a stack trace– Examine the state of a program after death.– Check improbable values of arguments
• Explain your code to someone else– Read the code– Take a break
Debug - Advice on No Clues, Hard Bugs
• Make the bug reproducible
• Divide and conquer– Narrow down the possibilities– Proceed by binary search
• Write self-checking code– Display messages– Logs– checking function
• Keep records
Debug - Non-reproducible Bugs
• Check whether all variables have been initialized
• Does something depend on the external environment of the program?
Testing - Tips for Testing
• Write testing code temporarily–In Unit Test : Do not add any code in production code just for testing.
–Remove testing code before publishing
• Use 0xDEADBEEF rather than 0
• Clear Input / Output
• Vary your test cases
• Test on multiple machines, compilers, and operating systems.
Performance
● Find the bottleneck
● Strategies for Speed
● Space Efficiency
● Basic cycle for performance optimization
Performance - Strategies for Speed(1)
• Use a better algorithm or data structure
• Collect common subexpressions– Bad samples:
?
Performance - Strategies for Speed(2)
• Replace expensive operations by cheap ones
• Unroll or eliminate loops
Performance - Strategies for Speed(3)
• Cache frequently-used values– Re-use recently accessed
• Precompute results– Trading space for time
Performance - Strategies for Speed(4)
• Buffer input and output– String += VS String.Append
• Use approximate values– If accuracy isn't an issue, use lower-precision data types
• Rewrite in a lower-level language– Lower-level languages tend to be more efficient.
Performance - Space Efficiency
• Save space by using the smallest possible data type
• Don't store what you can easily recompute
• However :– Major improvements are more likely to come from better data
structures or algorithm– Space efficiency often comes with a cost in run-time
Basic cycle for performance optimization
● Measure● Focus on the few places where a change will make the
most difference● Verify the correctness of your changes● Measure again
Portability
● Why do we worry about portability?● Language● Headers and Libraries● Program Organization● Data Exchange● Internationalization● Summary
Portability – Why?
Why do we worry about portability?
•Less maintenance and more utility
•Environments change
•A portable program is a better designed program
Portability – Language
●Follow the standard and mainstream
●Hide system dependencies behind interfaces○Good samples : The I/O libraries
●Sizes of data types○sizeof (char) <= sizeof (short) <= sizeof (int) <= sizeof (long)
○sizeof (float) <= sizeof (double)
●Alignment of structure and class members○sizeof (struct X) bytes,○Not sizeof (char) + sizeof(int)
Portability – Headers and Libraries
• Use standard libraries
• Problems– Headers tend to be cluttered– Header files also can "pollute" the namespace by declaring a
function with the same name
• Solutions– Use a different header for each compiler or environment– Redefining the name
Portability – Program Organization
• Union– Conditional compilation – Include a header which defines all
• Intersection (Suggestion)– Use only features available everywhere– Avoid conditional compilation
Portability – Data Exchange
• TEXT
• Binary Data– little-endian vs big-endian– Sender and receiver agree on the byte order in transmission
Portability – Internationalization
• Do not assume ASCII– Unicode– UTF-8 – Wide Characters (C/C++)
• Do not assume English– L10N– UI
Portability - Summary
• Portable code is an ideal that is well worth striving for, since so much time is wasted making changes to move a program from one system to another or to keep it running as it evolves and the systems it runs on changes.
• The intersection approach is better than the union one.– Loss of efficiency and features– Z>B
Notation
• Perhaps of all the creations of man language is the most astonishing.– Giles Lytton Strachey, Words and Poetry
Notation
• If you find yourself writing too much code to do a mundane job, or if you have trouble expressing the process comfortably, maybe you're using the wrong language.
• If the right language doesn't yet exist, that might be an opportunity to create it yourself.
Notation - Formatting Data(2)
• Pack one of the format data
Each pack_type needs to implement its own logic !!
Reference
• Reviews from Amazon– http://www.amazon.com/Practice-Programming-Addison-Wesley-P
rofessional-Computing/dp/020161586X
• All members’ power point in iShare
• MSDN GC Class
• My Blog– http://juggernaut-liu.blogspot.tw/2014/04/practice-of-programming-
portability.html– http://juggernaut-liu.blogspot.tw/2014/05/practice-of-programming-
notation.html