子弹 の VISIONS

NEVER back down ~~

C++博客 首页 新随笔 联系 聚合 管理
  112 Posts :: 34 Stories :: 99 Comments :: 0 Trackbacks
C++ Tips
                  C++ Tips
                  Sections
            Intro
            I.   ABCs and Inheritance
            II.  Scope
            III. CLASSES
            IV.  MISC
            V.   OVERLOADING
            VI.  PARAMETERS
            VII. Constructors (more on classes)
            VIII.EXCEPTIONS
            IX.  TEMPLATES (more on classes)

Intro
This is not a code guideline document. See the C++ Style Guide for guidelines.
This is more of a document to fuel questions while you design and code
with C++. In some cases the point is simply stated and probably comes
off as a rule. In reality, they are simply meant as rules of thumb.
One of the main problems in C++ (more so than C) is that C++ provides
many mechanisms in the language by which the same task can be achieved
through different policies.  For example, C++ has the Polymorphism mechanism.
Some of the policies are templates, macros, inheritance, overloading,
(those are the static, compile-time ones), and virtual functions (the
run-time polymorphic policy).  Hopefully the following will provide 
enough fuel for questions to arrive at the best policy to use for a 
particular design.

I. ABCs and Inheritance
-----------------------
1. Abstract Base Class (ABC) : Make ABC class constructor protected when
      possible. Derived classes can have public constructor to override
      this.  The same is true for non-ABC classes as well.
2. Class Inheritance : Use protected keyword where ever possible, never use
      public to expose data members so the inheriting classes have access
      to them.
3. Multiple Inheritance and VBC's :The only drawback is the most derived
      class must initialize the lowest base classes. This breaks
      encapsulation.  Most people view multiple inheritance as a bad
      thing, but when used sparingly for parts of a design, there is
      no problem with it.
4. Data in classes should be keep private as much as possible.  Use a
      member function if a client needs to access the data.  If a member
      function does not need to be seen by a client, make it private.
      If the class might be inherited, then protected may be a good choice.
5. Private inheritance: Don't use it.  Too many ambiguities when used with
      run-time type identification.  Use a private data member instead
      or use public inheritance.
      Example:      class Foo: private Bar { ... }      dont do

6. Inheritance & virtual overrides: Care must be taken in overriding
      inherited functions. Sometimes functions are grouped together,
      and all need to be overridden. The base class designer must make
      this clear, if overriding one function requires multiple 
      functions to be overridden.
7. Inheritance & Get/Set functions: Typically functions that perform
      Get/Set shouldn't be overridden unless they are used by
      the derived class. Otherwise if the base class does direct
      field manipulation, you usually can't override it correctly,
      or it could be a maintenance nightmare.
      Note: Get/Set functions as referred to above are merely meant as
      abstractions. As a rule of thumb (thumb must be getting pretty
      big by now), one should not create functions called Get or Set,
      or flavors thereof. They tend to break the spirit of encapsulation.
      Of course, there will be times to use them.

II. SCOPE
---------
1. Law of Demeter : Do not make references to classes in a class that are
      not variables of the class, inherited by the class, or global.
      This also applies to including header files.
      Example:
            class Foo{public: Go(){} };
            class Bar{ Foo aFoo;  public:       Foo GetFoo(){return aFoo;} };
            class Fubar{ public:
                        void Bad(){  Bar aBar;  aBar.GetFoo().Go(); }
            };
      The method Bad() breaks encapsulation. It calls a method of a class
      it probably does not need to know about.  This will also affect 
      maintainability. If the Foo class changes, the changes may also 
      need to be done in the Fubar class.  
      The other side of the coin that must be looked at is do you
      want a pass-through method in the Bar class that simply
      calls the Go() method of the Foo class.  Lots of silly simple
      1 line member functions may not be desirable in all the classes.
      What probably needs to be looked at to decide what road to take
      is speed, or perhaps redesign the classes.
      Beyond the Law of Demeter is Doug's rule of thumb: Don't
      play hide and seek with data.
2. Scope: Another way to say the previous point is to keep scope
      small. This will increase the lifetime of the code and keep it
      maintainable and safe.
III. CLASSES
------------
1. Be explicit about the keywords, public, protected, and private in a class
      interface. Try not to have multiple sections. In other words, 
      multiple private sections in the class interface.  It is generally
      a good idea to place the public section first because this is 
      what most people are looking for when they go to use a class.
2. Make classes as atomic as possible. Give them a clear purpose. Break
      them into smaller classes if they become too complex. This may
      also eliminate duplicate code.
3. Don't let the compiler generate the default constructor,destructor,
      operator= and copy constructor.  If the class is entirely value
      based, this is probably fine, if not, for example, if the class
      has a data member that is a pointer, the above will probably not
      work.  Note, the default copy constructor only does a memcpy
      of the class, so all you copy is the pointer data. This may not
      be sufficient for copying a class.  Regardless, if you do want the
      default ones, place them in the code, and leave them commented.
      For example:
            // Fubar(const Fubar&)   use default copy constructor
4. If your class contains pointers, you should create the default constructor
      destructor, operator=, and copy constructor.
5. Class Copy: If the class should never be copied, then place the copy
      constructor in the private section and don't implement it.
      The linker will catch this, and the program will fail to build.
      This, although not graceful, is better than a malformed program.
6. Initialization: Perform all data member initialization in the constructor.
      It's best not to leave uninitialized objects running around in 
      the system.  Note, it is often more efficient using the
      constructor initializer list, otherwise, the default constructor
      would be called, and then you probably call member functions of
      the object later in the constructor.  For example:
      class Foo{ Bar mung;  Foo(int iCount) : mung(iCount) {}  ... };
      The variable mung is initialized once. But in the following:
      class Foo{ Bar mung;  Foo(int iCount){ mung = iCount; }  ... };
      mung's default constructor is called before the body of the
      class Foo's constructor is entered. Then mung is set again -
      this assumes that mung has an assignment operator. The net
      effect is that mung is initialized twice.
7. Class Naming:  There exists several ways to name classes that seem to
      work well for certain groups or people.  There is Hungarian notation
      and the "Taligent's Guide to Designing Programs" that document some
      of the more typical methods.

IV. MISC
--------
1. Implicit int:  The 'implicit int' rule will go away in the next 
      C++ standard. So for a proto like:  'main()'  you will have to 
      say 'int main()' in the future. Same for variables.
2. Preprocessor: Avoid it.  Use const values in the class, or inline
      functions instead of macros.  This is not to say, never use any
      #defines.
      Main reason:      #define MIN(a,b)      ( (aSomeFunction(); }

V. OVERLOADING
--------------
1. operator overloading:  It's syntactic sugar. Don't add them if they
      are not needed.  This does NOT refer to the typical ones like
      '=', '==', but ones like '()', '[]', '+'.  It does not always 
      make sense to add two objects together.

2. Overloading:  If a member function is conditionally executing code, 
      it may be a candidate for operator overloading, or just overloading.
3. Operator overloading and chaining: When designing an overloaded
      operator, think about whether it needs to be chained. For example:
            String cstr = "a" + "b" + "c";
      The String class's operator returns a reference to the String class.
      A partial implementation might be:
      
      class String{ public:
      String& operator+(const char *pcBuf){ 
                  // code to add the char* to the string
                  return *this;
      }
            ...
      };

VI. PARAMETERS
--------------
1. Argument Passing:  The first choice is typically a const ref.  The 
      const ref is basically an alias, and is easier to use than a 
      pointer.  It creates the same amount of instruction code as passing
      a pointer (for most cases). It's typically better than passing
      by value, where an object constructor will be called (if its an
      object).  As a rule of thumb, you might want too give the following
      a whirl:
            IN      const &
            OUT      &            If the object has the support functs
            INOUT      *&            Acts like a **.
      So for an IN parameter, what the 'const &' says, is here is a 
      reference to it, but you cannot modify the object. But you can
      call member functions that do not change the object ( member
      functions defined as const).  The OUT parameter is a parameter
      that is passed to a function that will modify it.  If the parameter
      needs to be created, then the INOUT parameter of *& may be a
      good choice.
2. Returning Ref:  In functions that return a reference, remember not to
      reference a temporary object and return it.  For example:
            String &Zippo(void){ ....  return String();
      What happens, is that the String() is a temporary object that
      upon return goes out of scope and is destroyed.  Thus, you
      return a reference to a destroyed object. Unfortunately, the
      program will probably work in most cases till it's shipped.
      The ol' Heisenbug!
3. Ref vs Pointer: Here's another way to look at when to use references,
      and when should to use pointers.
      C programmers sometimes don't like references since the
      reference semantics they provide isn't *explicit* in the caller's
      code. After a bit of C++ experience, however, one quickly realizes
      this "information hiding" is an asset rather than a liability. In
      particular, reuse-centered OOP tends to migrate the level of
      abstraction away from the language of the machine toward the
      language of the problem.  References are usually preferred over
      ptrs whenever you don't need "re-seating". This usually means that
      references are most useful in a class' public interface. References
      then typically appear on the skin of an object, and pointers on the
      inside. The exception to the above is where a function's parameter
      or return value needs a "sentinel" reference. This is usually best
      done by returning/taking a pointer, and giving the nil ptr (0) this
      special significance (references should always alias *objects*, not
      a dereferenced nil ptr).

VII. Constructors (more on classes)
-----------------------------------
1. Creating Constructors: These creatures should be simple. Try not to
      do anything in them that may generate errors.  Remember they
      don't have return values. If it's necessary to allocate
      memory or other complex things in the constructor, throw an exception
      if possible as the first recourse. Else, the class will have to be
      protected everywhere that may use something that may be in error.
      It's generally not a pretty sight to see an error returned in the
      constructor's signature.
2. Constructors: Another reason to keep them simple is in the case
      of inheritance.
3. Destructors:  It's responsibility is to release resources allocated 
      during the class's lifetime, not just from construction.
4. Member Initialization List: The constructor can have a comma separated
      member initialization list. If a class contains value based classes
      as data members, they can be initialized in the constructor. For
      example:
      class Foo{
            String cstr1;      // value based class called String
            String cstr2;      // value based class called String
      public:
            Foo(const char* pcStr1, const char*pcStr2):
                  cstr1(pcStr1), cstr2(pcStr2){}
      };
      With the variables cstr1, and cstr2 initialized in the constructor,
      they are initialized only once. Else, if they were initialized in 
      the body of the constructor, they would first be initialized with
      a default constructor, then again in the body.
      
VIII. EXCEPTIONS
----------------
1. Exceptions: Use exception hierarchies, possibly even derived from the
      Standard C++ ones.
2. Exceptions: Throw exceptions by value and catch them by reference.
      This way the exception handling mechanism cleans up anything
      created on the heap. If you throw exceptions by pointer, the
      catcher must know how to destroy them.  This is probably not
      a good coupling.  Even so, any up casting may slice and dice the
      object.

IX. TEMPLATES (more on classes)
-------------------------------
1. Templates:  Before creating new ones, see if they are in RogueWave,
      or part of the C++ Standard.
2. Templates:  When creating them, try to filter out any code that
      does not depend on the type, and place that into a base class.
      Thus, the template class itself is only the necessary information
      that depends on type. Good examples can be found in RogueWave.


Douglas J. Waters
(best reached on the internet)
Internet: waters@openmarket.com
Phone: (781) 359-7220
posted on 2008-07-18 09:17 子弹のVISIONS 阅读(547) 评论(0)  编辑 收藏 引用 所属分类: 1.x 临时目录

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理