These are fundamental principles as per my understanding and belief. I have followed these principles and could program in multiple languages and technologies effectively
2. Some basic guidelines
This is a ‘Learning Program’ and not a
‘training program’.
◦ Hence your Active Participation is needed.
◦ Participate in discussions
◦ Ask questions/doubts.
◦ If you have not understood some
point/concept, Raise your hand and ASK
Avoid side conversations
Avoid phone calls/emails.
June 16 Commercial in Confidence (C) Nitin Bhide 2
3. Some basic guidelines
Understand that there are no 'absolute
truths' in software development. Hence
We may disagree with some points/
ideas. And THAT IS OK.
In dealing with disagreements, focus on
the technical merits.
◦ And not on who said it. (Your company
guidelines, some books etc etc)
June 16 Commercial in Confidence (C) Nitin Bhide 3
4. Some basic guidelines
You will
not get
these
slides.
So make
your own
notes
June 16 Commercial in Confidence (C) Nitin Bhide 4
5. The Principles
Fail Fast
TELL, Don’t ASK
Design By Contract
Minimize the Impact of Change
June 16 Commercial in Confidence (C) Nitin Bhide 5
6. PRINCIPLE 1
: FAIL FAST
June 16 Commercial in Confidence (C) Nitin Bhide 6
7. Fail Fast
Key to delivering High
quality products (software
/hardware /manufacturing)
June 16 Commercial in Confidence (C) Nitin Bhide 7
8. Principle behind Agile practices
TDD (Test Driven Development)
Automated Unit Tests
Pair programming
Short development cycles (Sprints)
Continuous integrations
June 16 Commercial in Confidence (C) Nitin Bhide 8
9. Principle behind Agile practices
TDD (Test Driven Development)
Automated Unit Tests
Pair programming
Short development cycles (Sprints)
Continuous integrations
June 16 Commercial in Confidence (C) Nitin Bhide 9
10. Toyota Production System
Build a culture of stopping to fix
problems, to get quality right from the
first.
Use visual control so no problems are
hidden.
June 16 Commercial in Confidence (C) Nitin Bhide 10
11. Variations
Fail Faster, Succeed Sooner
◦ By David Kelly, Founder IDEO
◦ It is Core axiom in the field of innovation
design
Fail early, Fail often
◦ Principle of Disney-Pixar
June 16 Commercial in Confidence (C) Nitin Bhide 11
12. What is it?
If an error occurs,
Fail Immediately and
Visibly!
• Don’t hide the error
• Don’t postpone reporting
the error
June 16 Commercial in Confidence (C) Nitin Bhide 12
13. Why “Fail Fast” ?
Error is constrained
• Effects of error are localized.
• Cost of Error is reduced
Easy to detect the reason for Error
• The error is reported where it happened
• Else, if reported late, it is very hard to detect the
source of the error
June 16 Commercial in Confidence (C) Nitin Bhide 13
14. Cost of Fixing an Error
Cost
TimeError Introduced
Depends on distance between
‘error introduced’ to ‘error reported’
June 16 Commercial in Confidence (C) Nitin Bhide 14
15. Fail Fast Systems
Fail Early and Fix Early
• Only way to avoid cost associated with
production failures
• Fail-fast systems are usually designed
to stop normal operation rather than
attempt to continue a possibly flawed
process
15
16. “Failure can be a good thing. If it saves
you from following a doomed path for a
year, you’re glad to have failed early
rather than late.”
Kate Gregory (2005)
Gregory Consulting
June 16 Commercial in Confidence (C) Nitin Bhide 16
17. FAIL FAST IN SOFTWARE
June 16 Commercial in Confidence (C) Nitin Bhide 17
18. Why “Fail Fast” ?
Error is constrained
• Data (Userdatabase) is not corrupted
• “Crash is Bad” is not always true.
Easy debugging
• The error is reported where it happened
• Else, if reported late, it is very hard to detect the
source of the error
June 16 Commercial in Confidence (C) Nitin Bhide 18
19. Why “Fail Fast” ?
Finds bugs early, not later.
• Debugging is ‘unpredictable’. Hence it is
biggest schedule risk.
• Distance between “point of failure” and
“point of reporting failure” usually
determines the time for debugging.
• Fail Fast ensure that this distance is low.
June 16 Commercial in Confidence (C) Nitin Bhide 19
20. Fail Fast Principle –
Key to robust software
Bugs are risky and expensive. They are pain in
neck to reproduce and locate
Failing fast reduces the debugging cost and
pain, significantly.
Over time, more and more errors will fail fast
Cost of debugging decreases
Quality of application improves and the
product becomes robust
June 16 Commercial in Confidence (C) Nitin Bhide 20
21. Failure types
User input errors
Programming errors
◦ Error conditions
◦ Violation of Assumptions
◦ Compilation Errors
June 16 Commercial in Confidence (C) Nitin Bhide 21
22. User input error
Tell the user about the error right
away
◦ Don’t do this
In step 8 in a wizard get a message “Can’t
proceed; illegal value for step 2. Start Over”
June 16 Commercial in Confidence (C) Nitin Bhide 22
23. How to Fail Fast - User Input Errors?
Ask the user to correct the error
immediately after the error is done
Don’t postpone it and lose the data the
user has filled till now
May not have to fail if the user’s intent
can be inferred, but if you have to fail,
do it as above
June 16 Commercial in Confidence (C) Nitin Bhide 23
24. Programming error – error
condition
A condition in the software which can
happen
It is NOT an illegal condition
It requires special handling by
Application and Usually needs to
reported to User.
◦ Configuration data for the application is missing
◦ Data can’t be retrieved from the database
◦ User tries to do “File Save” on CDROM drive
June 16 Commercial in Confidence (C) Nitin Bhide 24
25. How to Fail Fast - Error
conditions?
Present an appropriate message to the user
◦ For a connection failure
NOT: ORA-03114: not connected to ORACLE
Rather: “We are unable to connect to the System of Record.
Please check the network connectivity or contact the System
Administrator.”
User error objects or exception handling
Workaround may be OK, but if not, fail as
mentioned above
◦ Resource unavailable (e.g., connection not made), wait and
try again (may it gets connected now)
◦ Corrupted data, but reasonable default value available (but
log the issue so that the corrupted data can be fixed)
June 16 Commercial in Confidence (C) Nitin Bhide 25
26. How to Fail Fast – Error
conditions?
e.g.,
Public int maxConnections()
{
String property = getProperty(“maxConnections”);
if(NULL == property)
{
throw NullPropertyException;<- Fail fast
}
else
{
return property.toInt();
}
}
June 16 Commercial in Confidence (C) Nitin Bhide 26
27. Programming error – Violation of
Assumption
A condition in the software which
should “NEVER” arise
e.g.,
Char *DuplicateString(const char *iStr)
{
char *StrNew = NULL;
StrNew = (char *)malloc(strlen(iStr) + 1));
-> Should iStr be NULL???
strcpy(StrNew, iStr); …
}
June 16 Commercial in Confidence (C) Nitin Bhide 27
28. How to Fail Fast – Violation of
Assumptions?
Fail Fast at time of compilation if
an ‘assumption is violated’
Typically achieved using language
features/ Compiler checks.
◦ Making a copy constructor/ operator=
private to ensure nobody can create a
copy of the object.
June 16 Commercial in Confidence (C) Nitin Bhide 28
29. How to Fail Fast - Violation of
Assumptions?
Assertion is the key
◦ Assertion: Tiny piece of code that checks a
condition and then fails if the condition
isn’t met
Use assertion
◦ To validate conditions that you expect to
hold at certain points in the code (in other
words – invariants)
◦ Rather than assuming these invariants
hold, you test them explicitly
June 16 Commercial in Confidence (C) Nitin Bhide 29
30. How to Fail Fast - Violation of
Assumptions?
Typical locations for using assertion
◦ At the start of a function, to check that the
state in which the function is invoked is as
expected – i.e., to check the precondition (e.g.,
checking the input arguments)
◦ At the end of a complicated procedure, to
check that the result is plausible – i.e., to check
the postcondition
◦ At intermediate locations, to check the sanity
of data of at that point and then proceed ahead
June 16 Commercial in Confidence (C) Nitin Bhide 30
31. How to Fail Fast - Violation of
Assumptions?
e.g.,
Char *DuplicateString(char *iStr)
{
Assert(NULL != iStr);<- Should never happen. Responsibility of
the caller function to send valid input
char *StrNew = NULL;
StrNew = (char *)malloc(strlen(iStr) + 1));
-> Should iStr be NULL???
strcpy(StrNew, iStr);
…
}
June 16 Commercial in Confidence (C) Nitin Bhide 31
32. How to Fail Fast - Violation of
Assumptions?
void SomeFunc()
{
…
Document *pDoc = GetDoc();
Assert(NULL != Doc);
…
int NumData = 0;
NumData = pDoc->GetNumData();
Assert((LowRange <= NumData) && (HighRange >= NumData));
…
CreateDataHandlers(NumData);
…
}
June 16 Commercial in Confidence (C) Nitin Bhide 32
33. How to Fail Fast - Violation of
Assumptions?
double CalcSqaureRoot(double dValue)
{
double dSqRootVal;
…logic…
Assert((CalcSqaure(dSqRootVal) – dValue) < TOL) <-
SelfCheck!!!
<- Ofcourse CalcSqaure() should be dependable
return dSqRootVal;
}
If dValue comes in as negative value, what should
CAlsSqaureRoot() do???
June 16 Commercial in Confidence (C) Nitin Bhide 33
34. How to Fail Fast – Compilation
Errors?
Can the error (of using =, instead of ==), in the
following statement, be found even before it is
executed?
If(Var = NULL)
SomeFunc();
Make the complier generate an error for such a
scenario. Write the statement as
If(NULL = Var)
SomeFunc();
The compiler will raise an error as something cannot be
assigned to a constant.
June 16 Commercial in Confidence (C) Nitin Bhide 34
35. Eric Lippert on Assertions
Assertions should document situations that are impossible, in such a manner that if
the allegedly impossible situation comes to pass, the developer is informed.
Exceptions, by contrast, provide a control flow mechanism for exceptional,
unlikely, or erroneous situations, but not impossible situations. For me, the key
difference is this:
It should ALWAYS be possible to produce a test case which exercises a given
throw statement. If it is not possible to produce such a test case then you have a
code path in your program which never executes, and it should be removed as
dead code.
It should NEVER be possible to produce a test case which causes an assertion to
fire. If an assertion fires, either the code is wrong or the assertion is wrong;
either way, something needs to change in the code.
That's why I would not replace an assertion with an exception. If the assertion
cannot actually fire, then replacing it with an exception means you have an
untestable code path in your program. I dislike untestable code paths.
June 16 Commercial in Confidence (C) Nitin Bhide 35
36. Asserts in Mars Rover Software
We originally formulated the rule to require all
functions with more than 10 lines of code
contain at least one assertion.
We later revised it to require that the flight software
as a whole, and each module within it, had to reach a
minimal assertion density of 2%.
The MSL flight software reached an overall assertion
density of 2.26%, a significant improvement over
earlier missions
Gerard J. Holzmann, Mars Code,
From ACM Communications Feb 2014
June 16 Commercial in Confidence (C) Nitin Bhide 36
37. Fail Fast Fallacies
It results in pretty fragile software, which seems to
failing now and then
◦ NO, it fails only if an error occurs (Writing bad code and
putting unreasonable assertions is NOT Fail Fast, it is pure-
plain bad coding)
◦ NO, as the production version has already been stripped of
the errors which should not occur or handles are put in place
to take care of the errors
◦ YES, if the developer or the QA shirk from their respective
duty. The developer is also a stakeholder because he sees the
code and knows much better that QA that what can go wrong
and where can it go wrong. The QA uses the application as
black box and try to emulate the user scenario
June 16 Commercial in Confidence (C) Nitin Bhide 37
38. Fail Fast Fallacies
Application should not contain
assertions in the production version
(release version). It is only for debug
version ?????
WHAT DO YOU THINK ?
June 16 Commercial in Confidence (C) Nitin Bhide 38
39. PRINCIPLE 2 :
TELL, DON’T ASK
June 16 Commercial in Confidence (C) Nitin Bhide 39
40. “The Paperboy and the Wallet”
By David Bock
The paperboy comes to your door, demanding
payment of Rs 150.00 for the month.
What will you do?
You turn around, and the
paperboy Pulls your wallet
out of your back pocket,
takes the 150 bucks, and
Puts the wallet back.
Instead of asking for the wallet,
the paperboy should instead tell
the customer to pay the Rs
150.00
As absurd as that sounds, many
programs are written in this style,
which leaves the code open to all
sorts of problems (and explains
why The Paper boy is now having
a iPhone, while you use
Micromax)
Code should work the same way
We want to tell objects what to do,
not ask them for their state.
June 16 Commercial in Confidence (C) Nitin Bhide 40
41. Elevator Interface
You are on 2nd Floor.
You want to go to 1st Floor
Which button to
Press ?
Or
Elevator is on 1st Floor
June 16 Commercial in Confidence (C) Nitin Bhide 41
42. Elevator Interface
You are on 2nd Floor.
You want to go to 1st Floor
Which button to
Press Now ?
Or
One Elevator is on 1st Floor
Other Elevator is on 3rd Floor
June 16 Commercial in Confidence (C) Nitin Bhide 42
43. Usually, Interfaces based on ‘TELL’
are more flexible
than interfaces based on ‘ASK’
June 16 Commercial in Confidence (C) Nitin Bhide 43
44. Tell, Don’t Ask – A Paradigm Shift
Procedural Paradigm
Object Oriented Paradigm
Procedural code gets
information then makes
decisions. (Ask &Decide)
Object-oriented code tells
objects to do things
June 16 Commercial in Confidence (C) Nitin Bhide 44
45. Mapping Requirements to Classes
Problem
under
Consideration
Requirements &
Objects Identification
Hierarchy of classes
• Problem under consideration can be
broken down into Requirements
• Requirements can be mapped to set
of classes
• If possible, Class Hierarchy can be
created
June 16 Commercial in Confidence (C) Nitin Bhide 45
46. Tell, Don’t Ask
TELL objects what you want them to do
Do not ASK them questions about their state,
make a decision, and then tell them what to
do
The logic you are implementing is probably
the called object's responsibility, not yours.
For you to make decisions outside the object
violates its encapsulation
June 16 Commercial in Confidence (C) Nitin Bhide 46
47. Ask Vs Tell In
Object Oriented Paradigm
Ask, then take Decision
Class Rect
--------
-------
------
-----
float Width( )
float Height( )
float w = rect.width(); // ASK for width
float h = rect.height(); // ASK for height
float area = w * h; // Compute area
BAD IDEA
Asking object for it’s values
and then computing something
with those values
Tell, Don’t Ask
Class Rect
--------
-------
------
-----
float Width( )
float Height( )
// TELL me the area
float area = rect.area();
Tell the Object
float Area( )
June 16 Commercial in Confidence (C) Nitin Bhide 47
48. Think Declaratively,
not Procedurally
It is easier to stay out of the trap of Asking, if
you start designing classes based on their
responsibilities
You can then progress naturally to
◦ specifying commands that the class may execute
◦ as opposed to queries that inform you as to the
state of the object
June 16 Commercial in Confidence (C) Nitin Bhide 48
49. Important considerations
Freezing Responsibility of a class or
group of linked classes will ease in
◦ Modularizing the code
Partitioning a program
◦ Abstraction
Provides Crisply define boundary
Focuses on outside view of an object
Separates the implementation from behavior
◦ Encapsulation
Data and Implementation encapsulation
June 16 Commercial in Confidence (C) Nitin Bhide 49
51. PRINCIPLE 3 :
DESIGN BY CONTRACT
(DBC)
June 16 Commercial in Confidence (C) Nitin Bhide 51
52. Design by Contract – History
The term Design by Contract (DBC) was coined by Bertrand Meyer in
connection with his design of the Eiffel programming language
The central idea of DBC is a metaphor on how elements of a software
system collaborate with each other on the basis of mutual obligations
and benefits
The metaphor comes from business life, where a "client" and a
"supplier" agree on a "contract" which defines for example that
◦ The supplier has to provide a certain product (obligation) and is entitled to
expect that the client has paid its fee (benefit).
◦ The client must pay the fee (obligation) and is entitled to get the product
(benefit).
◦ Both parties must satisfy certain obligations, such as laws and regulations,
applying to all contracts
June 16 Commercial in Confidence (C) Nitin Bhide 52
53. Clients using a Dynamic Link Library
Application
DLL
Exported
Functions define
the Contract
Interfaces
Interface
Application
Interface
Functions define
the Contract
DBC at Various Levels in Software
June 16 Commercial in Confidence (C) Nitin Bhide 53
54. DBC at Various Levels in Software
OO Abstractions
Client
dc2.foo()
dc1.foo()
Abstract class
Guarantees the
Client for particular
functionality
Base Class
virtual foo() = 0;
Derived Class
DC1
virtual foo();
Derived Class
DC2
virtual foo();
dc1
dc2
Public functions of a Class
Client
Pt.distance( ); Public functions act
as a contract
Class Point
public:
distance( );
private:
geodesicpath( );
pt
June 16 Commercial in Confidence (C) Nitin Bhide 54
55. DBC at Various Levels in Software
Device Drivers
Standards and Protocols
COM (Component Object Model)
SOA (Service Oriented Architecture)
June 16 Commercial in Confidence (C) Nitin Bhide 55
56. DBC at Class / Routine Level
If a routine from a class in object-oriented
programming provides a certain
functionality, it may
◦ Impose a certain obligation to be guaranteed on
entry by any client module that calls it: the
routine's precondition
◦ Guarantee a certain property on exit: the routine's
postcondition
◦ Maintain a certain property, assumed on entry and
guaranteed on exit: the class invariant
June 16 Commercial in Confidence (C) Nitin Bhide 56
57. Class Point
public:
distance( );
private:
geodesicpath( );
distance( )
ASSERT
ASSERT
ASSERT
DBC at Class / Routine Level
What does distance expect ? Pre-condition
What does it guarantee ? Post-condition
What does it maintain ? Class invariant
June 16 Commercial in Confidence (C) Nitin Bhide 57
58. DBC Methodology
Using the DBC methodology
◦ the program code itself must never try to verify the contract
conditions
◦ whole idea is that code should “Fail Hard/Fail Fast", with the
contract verification being the safety net
◦ DBC's “Fail Hard/Fail Fast", property makes debugging for-
contract behavior much easier because the intended
behaviour of each routine is clearly specified
◦ The contract conditions should never be violated in program
execution: thus, they should be left as it is in the code
June 16 Commercial in Confidence (C) Nitin Bhide 58
60. Minimizing Impact of Change
THE FUNDAMENTAL PRINCIPLE
Basis Behind All Major Evolutions in
Programming
June 16 Commercial in Confidence (C) Nitin Bhide 60
61. Contradictory Requirements
Keep Software Soft => Allow Change
But Minimize the Impact of Change
June 16 Commercial in Confidence (C) Nitin Bhide 61
62. Why ?
To achieve this, we design to minimize the
impact of change.
We wish to save time and money, reduce the
introduction of new defects, and reduce the
pain and suffering inflicted on overworked
developers.
June 16 Commercial in Confidence (C) Nitin Bhide 62
63. How To Minimize Impact of Change
?
1. Isolate code
◦ Orthogonality
◦ Object oriented programming
2. Minimize Dependencies
◦ Maintain Unidirectional dependencies
◦ Avoid circular dependencies
June 16 Commercial in Confidence (C) Nitin Bhide 63
64. How To Minimize Impact of Change
?
3. Standardize/Define Contracts
◦ Published interfaces
◦ Protocols and Standards
◦ Abstractions
◦ SOA
4. Reuse, Don’t reinvent
◦ Design (design patterns)
◦ Code (Libraries and Frameworks)
◦ OO Concepts like Composition and
Inheritance
June 16 Commercial in Confidence (C) Nitin Bhide 64
65. How To Minimize Impact of Change
?
5. Continuous Verification (Fail Fast)
◦ Assertions
◦ Automated Tests (Junit, MkODT)
◦ TDD (Test Driven Development)
June 16 Commercial in Confidence (C) Nitin Bhide 65
70. References
Fail Fast (http://martinfowler.com/ieeeSoftware/failFast.pdf)
Eric Lippert’s quote about assertions
(http://stackoverflow.com/questions/1467568/debug-assert-vs-
exception-throwing)
Tell Don’t Ask https://pragprog.com/articles/tell-dont-ask
Tell Don’t Ask http://martinfowler.com/bliki/TellDontAsk.html
On the criteria to be used in decomposing systems into
modules by Parnas (In Communications of ACM 1972 )
https://www.cs.umd.edu/class/spring2003/cmsc838p/Design/c
riteria.pdf
Design By Contract
(http://en.wikipedia.org/wiki/Design_by_contract)
Check the article on ‘http://tagswap.net/pub/docs/OOP_Principles_TellDontAsk.pdf’ (has some good code samples)
You have to press the elevator button based on where you want to go (up or down). Don’t worry about where the ‘elevator’ currently is. (Tell)
If you look where elevator currently is (Ask) and then decide whether ‘elevator’ needs to come up or down (ask&decide). Let ‘elevator’ take the decision how best to serve you.
Both approaches work when there is only one elevator. But when there are two elevators and only one up/down button common to both elevator, Ask&Decide approach fails.