SlideShare a Scribd company logo
1 of 37
Download to read offline
Object Oriented Programming -
           Essential Techniques


                      S G Ganesh
                    sgganesh@gmail.com
Language Pragmatics


 A language is not just syntax and learning
  a language isn’t just learning to program.
 Mastering a language requires good
  understanding of language semantics,
  pragmatics, traps and pitfalls with
  considerable experience in programming
  and design using that language.
Five Specific OO Tips and Techniques

 We’ll see 5 specific tips/techniques
 Based on understanding, experience and
  usage of language features
 Tips are about pragmatics of using
  language features
 The mistakes covered in the tips are errors
  in usage
 Examples in C++ and Java (sometimes in
  C#)
1. Avoid calling virtual functions in constructors

   Constructors do not support runtime
    polymorphism fully as the derived objects are
    not constructed yet when base class constructor
    executes.

   So, avoid calling virtual functions from base-
    class constructors, which might result in subtle
    bugs in the code.
C++ resolves virtual function calls to base type
struct base {
    base() {
          vfun();
    }
    virtual void vfun() {
          cout << “Inside base::vfunn”;
    }
};
struct deri : base {
    virtual void vfun() {
          cout << “Inside deri::vfunn”;
    }
};
int main(){
    deri d;
}
C++ resolves virtual function calls to base type
struct base {
    base() {
          vfun();
    }
    virtual void vfun() {
          cout << “Inside base::vfunn”;
    }
};
struct deri : base {
    virtual void vfun() {
          cout << “Inside deri::vfunn”;
    }
};
int main(){
    deri d;
}

// prints:Inside base::vfun
Java/C# resolves virtual function calls dynamically

// Java example
class base {
    public base() {
      vfun();
    }
    public void vfun() {
      System.out.println(quot;Inside base::vfunquot;);
    }
}
class deri extends base {
    public void vfun() {
      System.out.println(quot;Inside deri::vfunquot;);
    }
    public static void main(String []s) {
      deri d = new deri();
    }
}
Java/C# resolves virtual function calls dynamically

// Java example
class base {
    public base() {
      vfun();
    }
    public void vfun() {
      System.out.println(quot;Inside base::vfunquot;);
    }
}
class deri extends base {
    public void vfun() {
      System.out.println(quot;Inside deri::vfunquot;);
    }
    public static void main(String []s) {
      deri d = new deri();
    }
}

// prints: Inside deri::vfun
In C++, pure virtual methods might get called

struct base {
    base() {
          base * bptr = this;
          bptr->bar();
          // even simpler ...
          ((base*)(this))->bar();
    }
    virtual void bar() =0;
};
struct deri: base {
    void bar(){ }
};
int main() {
    deri d;
}
In C++, pure virtual methods might get called

struct base {
    base() {
          base * bptr = this;
          bptr->bar();
          // even simpler ...
          ((base*)(this))->bar();
    }
    virtual void bar() =0;
};
struct deri: base {
    void bar(){ }
};
int main() {
    deri d;
}
// g++ output:
// pure virtual method called
// ABORT instruction (core dumped)
Dynamic method call in Java might lead to trouble
// Java code
class Base {
     public Base() {
            foo();
     }
     public void foo() {
            System.out.println(quot;In Base's foo quot;);
     }
}
class Derived extends Base {
     public Derived() {
            i = new Integer(10);
     }
     public void foo() {
            System.out.println(quot;In Derived's foo quot; + i.toString() );
     }
     private Integer i;
}
class Test {
     public static void main(String [] s) {
            new Derived().foo();
     }
}
Dynamic method call in Java might lead to trouble
// Java code
class Base {
     public Base() {
            foo();
     }
     public void foo() {
            System.out.println(quot;In Base's foo quot;);
     }
}
class Derived extends Base {
     public Derived() {
            i = new Integer(10);
     }
     public void foo() {
            System.out.println(quot;In Derived's foo quot; + i.toString() );
     }
     private Integer i;
}
class Test {
     public static void main(String [] s) {
            new Derived().foo();
     }
}
// this program fails by throwing a NullPointerException
2. Preserve the basic properties of methods while
overriding

   Overriding the methods incorrectly can result in
    bugs and unexpected problems in the code.
   Adhering to Liskov’s Substitution Principle is
    possible only when overriding is done properly.
   Make sure that the method signatures match
    exactly while overriding is done
   Provide semantics similar to the base method in
    the overridden method.
In C++, provide consistent default parameters

struct Base {
   virtual void call(int val = 10)
        { cout << “The default value is :”<< endl; }
};

struct Derived : public Base {
   virtual void call(int val = 20)
        { cout << “The default value is :”<< endl; }
};

// user code:
Base *b = new Derived;
b->call();
In C++, provide consistent default parameters

struct Base {
   virtual void call(int val = 10)
        { cout << “The default value is :”<< endl; }
};

struct Derived : public Base {
   virtual void call(int val = 20)
        { cout << “The default value is :”<< endl; }
};

// user code:
Base *b = new Derived;
b->call();

// prints:
// The default value is: 10
In Java, final might be removed while overriding

class Base {
public void vfoo(final int arg) {
          System.out.println(quot;in Base; arg = quot;+arg);
    }
}
class Derived extends Base {
public void vfoo(int arg) {
          arg = 0;
          System.out.println(quot;in Derived; arg = quot;+arg);
    }
    public static void main(String []s) {
          Base b = new Base();
    b.vfoo(10);
    b = new Derived();
    b.vfoo(10);
    }
}
In Java, final might be removed while overriding

class Base {
public void vfoo(final int arg) {
           System.out.println(quot;in Base; arg = quot;+arg);
     }
}
class Derived extends Base {
public void vfoo(int arg) {
           arg = 0;
           System.out.println(quot;in Derived; arg = quot;+arg);
     }
     public static void main(String []s) {
           Base b = new Base();
     b.vfoo(10);
     b = new Derived();
     b.vfoo(10);
     }
}
// prints:
// in Base; arg = 10
// in Derived; arg = 0
Provide consistent exception specification

struct Shape {
   // can throw any exceptions
   virtual void rotate(int angle) = 0;
   // other methods
};

struct Circle : public Shape {
   virtual void rotate(int angle) throw (CannotRotateException) {
         throw CannotRotateException();
   }
   // other methods
};

// client code
Shape *shapePtr = new Circle();
shapePtr->rotate(10);
// program aborts!
3. Beware of order of initialization problems.


 Many subtle problems can happen
  because of order of initialization issues.
 Avoid code that depends on particular
  order of implementation as provided by the
  compiler or the implementation.
In C++, such init can cause unintuitive results

// translation unit 1
int i = 10;

// translation unit 2
extern int i;
int j = i;
// j is 0 or 10?
// depends on the compiler/link line.
In Java, such init can cause unintuitive results

class Init {
   static int j = foo();
   static int k = 10;
   static int foo() {
     return k;
   }
   public static void main(String [] s) {
     System.out.println(quot;j = quot; + j);
   }
}
In Java, such init can cause unintuitive results

class Init {
   static int j = foo();
   static int k = 10;
   static int foo() {
     return k;
   }
   public static void main(String [] s) {
     System.out.println(quot;j = quot; + j);
   }
}

// prints
//      j=0
4. Avoid switch/nested if-else based on types


 Programmers from structured
  programming background tend to use
  extensive use of control structures.
 Whenever you find cascading if-else
  statements or switch statements checking
  for types or attributes of different types to
  take actions, consider using inheritance
  with virtual method calls.
C# code to switch based on types

public enum Phone {
    Cell = 0, Mobile, LandLine
}
// method for calculating phone-charges
public static double CalculateCharges(Phone phone, int seconds){
    double phoneCharge = 0;
    switch(phone){
    case Phone.Cell:
          // calculate charges for a cell
    case Phone.Mobile:
          // calculate charges for a mobile
    case Phone.LandLine:
          // calculate charges for a landline
    }
    return phoneCharge;
}
C# code with if-else using RTTI

abstract class Phone {
     // members here
}
class Cell : Phone {
     // methods specific to cells
}
// similar implementation for a LandLine
public static double CalculateCharges(Phone phone, int seconds){
     double phoneCharge = 0;
     if(phone is Cell){
            // calculate charges for a cell
     }
     else if (phone is LandLine){
            // calculate charges for a landline
     }
     return phoneCharge;
}
C# code: Correct solution using virtual functions

abstract class Phone {
   public abstract double CalculateCharges(int seconds);
   // other methods
}
class Cell : Phone {
   public override double CalculateCharges(int seconds){
         // calculate charges for a cell
   }
}

// similar implementation for a LandLine
// Now let us calculate the charges for 30 seconds
Phone ph = new Cell ();
ph.CalculateCharges(30);
5. Avoid hiding of names in different scopes.


 Hiding of names in different scopes is
  unintuitive to the readers of the code
 Using name hiding extensively can affect
  the readability of the program.
 Its a convenient feature; avoid name
  hiding as it can result in subtle defects and
  unexpected problems.
Hiding of names can happen in different situations

   The name in the immediate scope can hide the
    one in the outer scope (e.g. function args and
    local variables)
   A variable in a inner block can hide a name from
    outer block (no way to distinguish the two)
   Derived class method differs from a base class
    virtual method of same name in its return type or
    signature - rather it is hidden.
   Derived member having same name and
    signature as the base-class non-virtual non-final
    member; the base member is hidden (e.g. data
    members)
C++ examples for name hiding

// valid in C++, error in Java/C#
void foo { // outer block
    int x, y;
    {      // inner block
           int x = 10, y = 20;
           // hides the outer x and y
    }
}

// C++ Code
int x, y;                   // global variables x and y
struct Point {
    int x, y;               // class members x and y
    Point(int x, int y);    // function arguments x and y
};
C++/Java/C# example for a bug with hiding

// Bug in C++, Java and C#
Point(int x, int y) {
    x = x;
    y = y;
}

// C++
Point(int x, int y) {
    this->x = x;
    this->y = y;
}
// Java and C#
Point(int x, int y) {
    this.x = x;
    this.y = y;
}
C++: No overloading across scopes

struct Base {
   void foo(int) {
         cout<<quot;Inside Base::foo(int)quot;;
   }
};

struct Derived : public Base {
   void foo(double) {
         cout<<quot;Inside Derived::foo(double)quot;;
   }
};

Derived d;
d.foo(10);
C++: No overloading across scopes

struct Base {
   void foo(int) {
         cout<<quot;Inside Base::foo(int)quot;;
   }
};

struct Derived : public Base {
   void foo(double) {
         cout<<quot;Inside Derived::foo(double)quot;;
   }
};

Derived d;
d.foo(10);
// prints:
// Inside Derived::foo(double)
Java: Overloading across scopes!

class base {
   public void foo(int i) {
     System.out.println(quot;In Base::foo(int)quot;);
   }
}

class deri extends base {
   public void foo(double i) {
     System.out.println(quot;Inside deri::foo(double)quot;);
   }
   public static void main(String []s) {
     deri d = new deri();
     d.foo(10);
   }
}
Java: Overloading across scopes!

class base {
   public void foo(int i) {
     System.out.println(quot;In Base::foo(int)quot;);
   }
}

class deri extends base {
   public void foo(double i) {
      System.out.println(quot;Inside deri::foo(double)quot;);
   }
   public static void main(String []s) {
      deri d = new deri();
      d.foo(10);
   }
}
// prints: Inside Base::foo(int)
How to write robust code and avoid defects?


   Many of the language rules, semantics and
    pragmatics are unintuitive
   What can help in detecting bugs early?
       Tools (but of limited extent)
       Extensive testing
       Peer review
       Good knowledge and experience
   No other approach can create robust code than
    passion towards writing excellent code
Q&A
Thank you!

More Related Content

What's hot (20)

C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
C tutorial
C tutorialC tutorial
C tutorial
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
 
C++11
C++11C++11
C++11
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
C++11
C++11C++11
C++11
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
C Basics
C BasicsC Basics
C Basics
 
Programs of C++
Programs of C++Programs of C++
Programs of C++
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
pointers 1
pointers 1pointers 1
pointers 1
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th Study
 

Viewers also liked

Modern Software Architecure Bootcamp - 2nd July 2016 - Bangalore
Modern Software Architecure Bootcamp - 2nd July 2016 - BangaloreModern Software Architecure Bootcamp - 2nd July 2016 - Bangalore
Modern Software Architecure Bootcamp - 2nd July 2016 - BangaloreGanesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
An Overview Of Standard C++Tr1
An Overview Of Standard C++Tr1An Overview Of Standard C++Tr1
An Overview Of Standard C++Tr1Ganesh Samarthyam
 
OCAJP 7 and OCPJP 7 certifications
OCAJP 7 and OCPJP 7 certificationsOCAJP 7 and OCPJP 7 certifications
OCAJP 7 and OCPJP 7 certificationsGanesh Samarthyam
 
IBM MQ - High Availability and Disaster Recovery
IBM MQ - High Availability and Disaster RecoveryIBM MQ - High Availability and Disaster Recovery
IBM MQ - High Availability and Disaster RecoveryMarkTaylorIBM
 
IBM Websphere MQ Basic
IBM Websphere MQ BasicIBM Websphere MQ Basic
IBM Websphere MQ BasicPRASAD BHATKAR
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Jérôme Petazzoni
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
Running High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on DockerRunning High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on DockerSematext Group, Inc.
 
Docker for Java Developers
Docker for Java DevelopersDocker for Java Developers
Docker for Java DevelopersNGINX, Inc.
 
Docker introduction
Docker introductionDocker introduction
Docker introductiondotCloud
 
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker images
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker imagesRootedCON 2017 - Docker might not be your friend. Trojanizing Docker images
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker imagesDaniel Garcia (a.k.a cr0hn)
 

Viewers also liked (15)

Modern Software Architecure Bootcamp - 2nd July 2016 - Bangalore
Modern Software Architecure Bootcamp - 2nd July 2016 - BangaloreModern Software Architecure Bootcamp - 2nd July 2016 - Bangalore
Modern Software Architecure Bootcamp - 2nd July 2016 - Bangalore
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
An Overview Of Standard C++Tr1
An Overview Of Standard C++Tr1An Overview Of Standard C++Tr1
An Overview Of Standard C++Tr1
 
OCAJP 7 and OCPJP 7 certifications
OCAJP 7 and OCPJP 7 certificationsOCAJP 7 and OCPJP 7 certifications
OCAJP 7 and OCPJP 7 certifications
 
IBM MQ - High Availability and Disaster Recovery
IBM MQ - High Availability and Disaster RecoveryIBM MQ - High Availability and Disaster Recovery
IBM MQ - High Availability and Disaster Recovery
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
IBM Websphere MQ Basic
IBM Websphere MQ BasicIBM Websphere MQ Basic
IBM Websphere MQ Basic
 
IBM MQ V9 Overview
IBM MQ V9 OverviewIBM MQ V9 Overview
IBM MQ V9 Overview
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Running High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on DockerRunning High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on Docker
 
Docker for Java Developers
Docker for Java DevelopersDocker for Java Developers
Docker for Java Developers
 
Docker by Example - Basics
Docker by Example - Basics Docker by Example - Basics
Docker by Example - Basics
 
Docker introduction
Docker introductionDocker introduction
Docker introduction
 
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker images
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker imagesRootedCON 2017 - Docker might not be your friend. Trojanizing Docker images
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker images
 

Similar to Oop Presentation

Wap to implement bitwise operators
Wap to implement bitwise operatorsWap to implement bitwise operators
Wap to implement bitwise operatorsHarleen Sodhi
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionYu-Sheng (Yosen) Chen
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
为什么 rust-lang 吸引我?
为什么 rust-lang 吸引我?为什么 rust-lang 吸引我?
为什么 rust-lang 吸引我?勇浩 赖
 
C++ Interface Versioning
C++ Interface VersioningC++ Interface Versioning
C++ Interface VersioningSkills Matter
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptishan743441
 
Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphismmohamed sikander
 
Rust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineRust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineMatt Provost
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17LogeekNightUkraine
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Abu Saleh
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Andrzej Jóźwiak
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of cTushar B Kute
 

Similar to Oop Presentation (20)

Oop Extract
Oop ExtractOop Extract
Oop Extract
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Wap to implement bitwise operators
Wap to implement bitwise operatorsWap to implement bitwise operators
Wap to implement bitwise operators
 
C++ programs
C++ programsC++ programs
C++ programs
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
C++ idioms.pptx
C++ idioms.pptxC++ idioms.pptx
C++ idioms.pptx
 
Android code convention
Android code conventionAndroid code convention
Android code convention
 
为什么 rust-lang 吸引我?
为什么 rust-lang 吸引我?为什么 rust-lang 吸引我?
为什么 rust-lang 吸引我?
 
Sbaw091006
Sbaw091006Sbaw091006
Sbaw091006
 
C++ Interface Versioning
C++ Interface VersioningC++ Interface Versioning
C++ Interface Versioning
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
 
Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphism
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
 
Rust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineRust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command Line
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 

More from Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Ganesh Samarthyam
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizGanesh Samarthyam
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 

More from Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Oop Presentation

  • 1. Object Oriented Programming - Essential Techniques S G Ganesh sgganesh@gmail.com
  • 2. Language Pragmatics  A language is not just syntax and learning a language isn’t just learning to program.  Mastering a language requires good understanding of language semantics, pragmatics, traps and pitfalls with considerable experience in programming and design using that language.
  • 3. Five Specific OO Tips and Techniques  We’ll see 5 specific tips/techniques  Based on understanding, experience and usage of language features  Tips are about pragmatics of using language features  The mistakes covered in the tips are errors in usage  Examples in C++ and Java (sometimes in C#)
  • 4. 1. Avoid calling virtual functions in constructors  Constructors do not support runtime polymorphism fully as the derived objects are not constructed yet when base class constructor executes.  So, avoid calling virtual functions from base- class constructors, which might result in subtle bugs in the code.
  • 5. C++ resolves virtual function calls to base type struct base { base() { vfun(); } virtual void vfun() { cout << “Inside base::vfunn”; } }; struct deri : base { virtual void vfun() { cout << “Inside deri::vfunn”; } }; int main(){ deri d; }
  • 6. C++ resolves virtual function calls to base type struct base { base() { vfun(); } virtual void vfun() { cout << “Inside base::vfunn”; } }; struct deri : base { virtual void vfun() { cout << “Inside deri::vfunn”; } }; int main(){ deri d; } // prints:Inside base::vfun
  • 7. Java/C# resolves virtual function calls dynamically // Java example class base { public base() { vfun(); } public void vfun() { System.out.println(quot;Inside base::vfunquot;); } } class deri extends base { public void vfun() { System.out.println(quot;Inside deri::vfunquot;); } public static void main(String []s) { deri d = new deri(); } }
  • 8. Java/C# resolves virtual function calls dynamically // Java example class base { public base() { vfun(); } public void vfun() { System.out.println(quot;Inside base::vfunquot;); } } class deri extends base { public void vfun() { System.out.println(quot;Inside deri::vfunquot;); } public static void main(String []s) { deri d = new deri(); } } // prints: Inside deri::vfun
  • 9. In C++, pure virtual methods might get called struct base { base() { base * bptr = this; bptr->bar(); // even simpler ... ((base*)(this))->bar(); } virtual void bar() =0; }; struct deri: base { void bar(){ } }; int main() { deri d; }
  • 10. In C++, pure virtual methods might get called struct base { base() { base * bptr = this; bptr->bar(); // even simpler ... ((base*)(this))->bar(); } virtual void bar() =0; }; struct deri: base { void bar(){ } }; int main() { deri d; } // g++ output: // pure virtual method called // ABORT instruction (core dumped)
  • 11. Dynamic method call in Java might lead to trouble // Java code class Base { public Base() { foo(); } public void foo() { System.out.println(quot;In Base's foo quot;); } } class Derived extends Base { public Derived() { i = new Integer(10); } public void foo() { System.out.println(quot;In Derived's foo quot; + i.toString() ); } private Integer i; } class Test { public static void main(String [] s) { new Derived().foo(); } }
  • 12. Dynamic method call in Java might lead to trouble // Java code class Base { public Base() { foo(); } public void foo() { System.out.println(quot;In Base's foo quot;); } } class Derived extends Base { public Derived() { i = new Integer(10); } public void foo() { System.out.println(quot;In Derived's foo quot; + i.toString() ); } private Integer i; } class Test { public static void main(String [] s) { new Derived().foo(); } } // this program fails by throwing a NullPointerException
  • 13. 2. Preserve the basic properties of methods while overriding  Overriding the methods incorrectly can result in bugs and unexpected problems in the code.  Adhering to Liskov’s Substitution Principle is possible only when overriding is done properly.  Make sure that the method signatures match exactly while overriding is done  Provide semantics similar to the base method in the overridden method.
  • 14. In C++, provide consistent default parameters struct Base { virtual void call(int val = 10) { cout << “The default value is :”<< endl; } }; struct Derived : public Base { virtual void call(int val = 20) { cout << “The default value is :”<< endl; } }; // user code: Base *b = new Derived; b->call();
  • 15. In C++, provide consistent default parameters struct Base { virtual void call(int val = 10) { cout << “The default value is :”<< endl; } }; struct Derived : public Base { virtual void call(int val = 20) { cout << “The default value is :”<< endl; } }; // user code: Base *b = new Derived; b->call(); // prints: // The default value is: 10
  • 16. In Java, final might be removed while overriding class Base { public void vfoo(final int arg) { System.out.println(quot;in Base; arg = quot;+arg); } } class Derived extends Base { public void vfoo(int arg) { arg = 0; System.out.println(quot;in Derived; arg = quot;+arg); } public static void main(String []s) { Base b = new Base(); b.vfoo(10); b = new Derived(); b.vfoo(10); } }
  • 17. In Java, final might be removed while overriding class Base { public void vfoo(final int arg) { System.out.println(quot;in Base; arg = quot;+arg); } } class Derived extends Base { public void vfoo(int arg) { arg = 0; System.out.println(quot;in Derived; arg = quot;+arg); } public static void main(String []s) { Base b = new Base(); b.vfoo(10); b = new Derived(); b.vfoo(10); } } // prints: // in Base; arg = 10 // in Derived; arg = 0
  • 18. Provide consistent exception specification struct Shape { // can throw any exceptions virtual void rotate(int angle) = 0; // other methods }; struct Circle : public Shape { virtual void rotate(int angle) throw (CannotRotateException) { throw CannotRotateException(); } // other methods }; // client code Shape *shapePtr = new Circle(); shapePtr->rotate(10); // program aborts!
  • 19. 3. Beware of order of initialization problems.  Many subtle problems can happen because of order of initialization issues.  Avoid code that depends on particular order of implementation as provided by the compiler or the implementation.
  • 20. In C++, such init can cause unintuitive results // translation unit 1 int i = 10; // translation unit 2 extern int i; int j = i; // j is 0 or 10? // depends on the compiler/link line.
  • 21. In Java, such init can cause unintuitive results class Init { static int j = foo(); static int k = 10; static int foo() { return k; } public static void main(String [] s) { System.out.println(quot;j = quot; + j); } }
  • 22. In Java, such init can cause unintuitive results class Init { static int j = foo(); static int k = 10; static int foo() { return k; } public static void main(String [] s) { System.out.println(quot;j = quot; + j); } } // prints // j=0
  • 23. 4. Avoid switch/nested if-else based on types  Programmers from structured programming background tend to use extensive use of control structures.  Whenever you find cascading if-else statements or switch statements checking for types or attributes of different types to take actions, consider using inheritance with virtual method calls.
  • 24. C# code to switch based on types public enum Phone { Cell = 0, Mobile, LandLine } // method for calculating phone-charges public static double CalculateCharges(Phone phone, int seconds){ double phoneCharge = 0; switch(phone){ case Phone.Cell: // calculate charges for a cell case Phone.Mobile: // calculate charges for a mobile case Phone.LandLine: // calculate charges for a landline } return phoneCharge; }
  • 25. C# code with if-else using RTTI abstract class Phone { // members here } class Cell : Phone { // methods specific to cells } // similar implementation for a LandLine public static double CalculateCharges(Phone phone, int seconds){ double phoneCharge = 0; if(phone is Cell){ // calculate charges for a cell } else if (phone is LandLine){ // calculate charges for a landline } return phoneCharge; }
  • 26. C# code: Correct solution using virtual functions abstract class Phone { public abstract double CalculateCharges(int seconds); // other methods } class Cell : Phone { public override double CalculateCharges(int seconds){ // calculate charges for a cell } } // similar implementation for a LandLine // Now let us calculate the charges for 30 seconds Phone ph = new Cell (); ph.CalculateCharges(30);
  • 27. 5. Avoid hiding of names in different scopes.  Hiding of names in different scopes is unintuitive to the readers of the code  Using name hiding extensively can affect the readability of the program.  Its a convenient feature; avoid name hiding as it can result in subtle defects and unexpected problems.
  • 28. Hiding of names can happen in different situations  The name in the immediate scope can hide the one in the outer scope (e.g. function args and local variables)  A variable in a inner block can hide a name from outer block (no way to distinguish the two)  Derived class method differs from a base class virtual method of same name in its return type or signature - rather it is hidden.  Derived member having same name and signature as the base-class non-virtual non-final member; the base member is hidden (e.g. data members)
  • 29. C++ examples for name hiding // valid in C++, error in Java/C# void foo { // outer block int x, y; { // inner block int x = 10, y = 20; // hides the outer x and y } } // C++ Code int x, y; // global variables x and y struct Point { int x, y; // class members x and y Point(int x, int y); // function arguments x and y };
  • 30. C++/Java/C# example for a bug with hiding // Bug in C++, Java and C# Point(int x, int y) { x = x; y = y; } // C++ Point(int x, int y) { this->x = x; this->y = y; } // Java and C# Point(int x, int y) { this.x = x; this.y = y; }
  • 31. C++: No overloading across scopes struct Base { void foo(int) { cout<<quot;Inside Base::foo(int)quot;; } }; struct Derived : public Base { void foo(double) { cout<<quot;Inside Derived::foo(double)quot;; } }; Derived d; d.foo(10);
  • 32. C++: No overloading across scopes struct Base { void foo(int) { cout<<quot;Inside Base::foo(int)quot;; } }; struct Derived : public Base { void foo(double) { cout<<quot;Inside Derived::foo(double)quot;; } }; Derived d; d.foo(10); // prints: // Inside Derived::foo(double)
  • 33. Java: Overloading across scopes! class base { public void foo(int i) { System.out.println(quot;In Base::foo(int)quot;); } } class deri extends base { public void foo(double i) { System.out.println(quot;Inside deri::foo(double)quot;); } public static void main(String []s) { deri d = new deri(); d.foo(10); } }
  • 34. Java: Overloading across scopes! class base { public void foo(int i) { System.out.println(quot;In Base::foo(int)quot;); } } class deri extends base { public void foo(double i) { System.out.println(quot;Inside deri::foo(double)quot;); } public static void main(String []s) { deri d = new deri(); d.foo(10); } } // prints: Inside Base::foo(int)
  • 35. How to write robust code and avoid defects?  Many of the language rules, semantics and pragmatics are unintuitive  What can help in detecting bugs early?  Tools (but of limited extent)  Extensive testing  Peer review  Good knowledge and experience  No other approach can create robust code than passion towards writing excellent code
  • 36. Q&A