C++ Coding StandardLast Modified: 2007-07-09Contributor E-mail / www.VanvelzenSoftware.com
Contents
IntroductionStandardization is ImportantIt helps if the standard annoys everyone in some way so everyone feels they are on the same playing field. The proposal here has evolved over many projects, many companies, and literally a total of many weeks spent arguing. It is no particular person's style and is certainly open to local amendments.Good PointsWhen a project tries to adhere to common standards a few good things happen:
Bad PointsNow the bad:
DiscussionThe experience of many projects leads to the conclusion that using coding standards makes the project go smoother. Are standards necessary for success? Of course not. But they help, and we need all the help we can get! Be honest, most arguments against a particular standard come from the ego. Few decisions in a reasonable standard really can be said to be technically deficient, just matters of taste. So be flexible, control the ego a bit, and remember any project is fundamentally a team effort.
Standards EnforcementFirst, any serious concerns about the standard should be brought up and worked out within the group. Maybe the standard is not quite appropriate for your situation. It may have overlooked important issues or maybe someone in power vehemently disagrees with certain issues :-)In any case, once finalized hopefully people will play the adult and understand that this standard is reasonable, and has been found reasonable by many other programmers, and therefore is worthy of being followed even with personal reservations. Failing willing cooperation it can be made a requirement that this standard must be followed to pass a code inspection. Failing that the only solution is a massive tickling party on the offending party.  Unless you want to flip a coin. Ain't easy - but it's the way I try to run my life.
Resources- Take a Look!General
Book RecommendationsWhat are some good C++ books you can buy for you and your team?
NamesMake Names FitNames are the heart of programming. In the past people believed knowing someone's true name gave them magical power over that person. If you can think up the true name for something, you give yourself and the people coming after power over the code. Don't laugh!If you find all your names could be Thing and DoIt then you should probably revisit your design. Class Names
Method and Function Names
Include Units in NamesIf a variable represents time, weight, or some other unit then include the unit in the name so developers can more easily spot problems. For example:UInt32 m_timeoutMsecs; UInt32 m_myWeightLbs;Better yet is to make a variable into a class so bad conversions can be caught. No All Upper Case AbbreviationsJustificationExampleclass CFluidOz // NOT CFluidOZ class CNetworkAbcKey // NOT CNetworkABCKey Class Names
Justification
Exampleclass CNameOneTwo class CName Class Library NamesMethod NamesJustificationExampleclass CNameOneTwo { public: Int32 DoIt( void ); void HandleError( void ); } Class Attribute Names
Justification
Exampleclass CNameOneTwo { public: Int32 VarAbc( void ); Int32 ErrorNumber( void ); private: Int32 m_varAbc; Int32 m_errorNumber; CString* m_name; } Method Argument Names
Exampleclass CNameOneTwo { public: Int32 StartYourEngines( Engine& someEngine , Engine& anotherEngine ); } Variable Names on the StackExampleInt32 CNameOneTwo::HandleError( Int32 errorNumber ) { Int32 error = OsErr(); Time timeOfError; ErrorProcessor errorProcessor; Time* outOfTime = NULL; }
Pointer Variables
Justification
ExampleCString* name = new CString(); CString* nameA, nameB, address; // note, only nameA is a pointer. Reference Variables and Functions Returning ReferencesJustification
Exampleclass Test { public: void DoSomething(StatusInfo& rStatus); StatusInfo& rStatus(); const StatusInfo& Status() const; private: StatusInfo& mrStatus; } Global VariablesJustificationExampleLogger gLog; Logger* gpLog; Global ConstantsJustificationIt's tradition for global constants to named this way. You must be careful to not conflict with other global #defines and enum labels.Exampleconst int A_GLOBAL_CONSTANT= 5; Static Variables
Justification
Exampleclass Test { public: private: static StatusInfo msStatus; } Type Names
Justification
Exampletypedef uint16 ModuleType; typedef uint32 SystemType; Enum NamesLabels All Upper Case with '_' Word SeparatorsThis is the standard rule for enum labels.Exampleenum PinStateType { PIN_OFF, PIN_ON }; Enums as Constants without Class ScopingSometimes people use enums as constants. When an enum is not embedded in a class make sure you use some sort of differentiating name before the label so as to prevent name clashes.Exampleenum PinStateType If PIN was not prepended a conflict { would occur as OFF and ON are probably PIN_OFF, already defined. PIN_ON }; Enums with Class ScopingJust name the enum items what you wish and always qualify with the class name: Aclass::PIN_OFF.Make a Label for an Error StateIt's often useful to be able to say an enum is not in any of its valid states. Make a label for an uninitialized or error state. Make it the first label if possible.Exampleenum { STATE_ERR, STATE_OPEN, STATE_RUNNING, STATE_DYING}; #define and Macro NamesJustificationThis makes it very clear that the value is not alterable and in the case of macros, makes it clear that you are using a construct that requires care.Some subtle errors can occur when macro names and enum labels use the same name. Example#define MAX(a,b) blah #define IS_ERR(err) blah C Function Names
Justification
Exampleint some_bloody_function() { } C++ File ExtensionsIn short: Use the .h extension for header files and .cc for source files.Header File Extension DiscussionUsing .hh extension is not widely popular but makes a certain kind of sense. C header files use .h file extension and C++ based header files use .hh file extension. The problem is if we consider a header file an interface to a service then we can have a C interface to a service and C++ interface to the service in the same file. Using preprocessor directives this is possible and common. The recommendation is to stick with using the .h extension.
Source File Extension DiscussionThe problem with the .C extension is that it is indistinguishable from the .c extensions in operating systems that aren't case sensitive. Yes, this is a UNIX vs. windows issue. Since it is a simple step aiding portability we won't use the .C extension. The .cpp extension is a little wordy. So the .cc extension wins by default.
DocumentationComments Should Tell a StoryConsider your comments a story describing the system. Expect your comments to be extracted by a robot and formed into a man page. Class comments are one part of the story, method signature comments are another part of the story, method arguments another part, and method implementation yet another part. All these parts should weave together and inform someone else at another point of time just exactly what you did and why.Document DecisionsComments should document decisions. At every point where you had a choice of what to do place a comment describing which choice you made and why. Archeologists will find this the most useful information.Use Extractable HeadersUse a document extraction system like Doxygen when documenting your code.These headers are structured in such a way as they can be parsed and extracted. They are not useless like normal headers. So take time to fill them out. If you do it right once no more documentation may be necessary. As part of your nighlty build system have a step the generates the documentation from the source. Then index the source using a tool like Lucene. Have a front end to the search so developers can do full text searches on nightly builds and for release builds. This is a wonderfully useful feature. The next step in automation is to front the repository with a web server documentation can directly refer to a source file with a URL.
Comment All Questions a Programmer May Have When Looking at Your CodeAt every point in your code think about what questions a programmer may have about the code. It's crucial you answer all those questions somehow, someway. If you don't, as the code writer, answer those questions, who will?If you think your code is so clear and wonderful that nobody will have any questions then you are lying to yourself. I have never seen a large system with this wonderful self-documenting code feature. I've seen very few small libraries are even a single class that are so wonderfully self-documented. You have a lot of tools at your disposal to answer questions:
I don't really consider unit tests a question answering device because if you can't understand the code by reading it, reading something else about the code you don't understand won't help you understand it better.
Make Your Code Discoverable by BrowsingProgrammers should be able to navigate your code by looking at markers in the code, namely the names and the directory structure. Nothing is more frustrating to than to have to look at pile of code and have no idea what it's organizing principles are.Have a logicanl directory structure. Have directories called doc, lib, src, bin, test, pkg, install, etc and whatever, so I at least have some idea where stuff is. People use the weirdest names and lump everything together so that it it can be detangles. Clear thought is evidenced from the beginning by a directory stucture. Don't put more than one class in a file. Otherwise, how will I know its there when I browse your code? Should I really need to use search to find every last thing? Can't I just poke around the code and find it? I can if you organize your code. Name your files after your classes. I didn't believe this one until I saw it. Why you name a file different than the class? How I am possibly supposed to know what's in the file otherwise?
Write Comments as You CodeYou won't every go back later and document your code. You just won't. Don't lie to yourself, the world, and your mother by saying that you will.So when you do something document it right then and there. When you create a class- document it. When you create a method- document it. And so on. That way when you finish coding you will also be finished documenting. I advocate simultaneously writing code, writing tests, and writing documentaiton. Which comes first depends on you and the problem. I don't think there is any rule that says which should come first. On the path to getting stuff done I'll take the entrance that seems easiest to me at the time. Once on the path it's easy to follow the entire trail. Won't this break the flow? No, I think it improves flow because it keeps you mindful of what you are doing, why you are doing, and how it fits in the big picture. My take on TDD (test driven development) is that it's not the tests that are really important, it's that the tests keep you mindful while programming. A test means you are keeping everything in you mind at once you need to remember to successfully code something up. As you can't keep large chunks in your mind then smaller chunks are better. Writing a test forces you to remember what your code is supposed to accomplish. It's forcing you to also think about the use case/story/intent behind why you are writing the code. The result is a pointed mind that has focussed all its powers on doing one thing. When you can bring that focus to you programming you can be successful. The tests are really secondary.  And I find code written mindfully, one step at a time, has very few bugs. Unit tests are just one definition of a "step." You can use the orignial story you are implementing as a step as well. I use unit tests more as a mental focussing device while developing, like Zen Archery, than for the actual tests. After development unit tests are very useful in making sure code doesn't break. So I am not saying unit tests aren't useful. I just don't think they are the real reason behind why TDD generates working code. With a clear well functioning focussed mind we generate working code. But getting into that state is hard. Writing comments simultaneously with all other aspects of development deepens your mindfulness because you are thinking about everything at once. All the interconnections are present in your brain because you are explaining the intent behind what you are doing. There's a saying that you don't know something until you teach it. Comments are teaching what you are doing to someone else. When you are writing comments you must generate the thoughts to teach, to explain to someone else the intent behing what you are doing. It's very difficult to make a coding error when all this context is hot in your mind. I'll go back and forth between documenting, testing, and coding. I'll let the problem dictate what happens when as I am working my way through solving the problem. Saying testing should always come first is too simple a rule and I think misses the larger point about software development. Software is ultimately mind stuff. Using our minds better is the real methodology.
Make Gotchas ExplicitExplicitly comment variables changed out of the normal control flow or other code likely to break during maintenance. Embedded keywords are used to point out issues and potential problems. Consider a robot will parse your comments looking for keywords, stripping them out, and making a report so people can make a special effort where needed.
Gotcha Keywords
Gotcha Formatting
Example// :TODO: tmh 960810: possible performance problem // We should really use a hash table here but for now we'll // use a linear search. // :KLUDGE: tmh 960810: possible unsafe type cast // We need a cast here to recover the derived type. It should // probably use a virtual method or template. See AlsoSee Interface and Implementation Documentation for more details on how documentation should be laid out.Interface and Implementation DocumentationThere are two main audiences for documentation:
Class UsersClass users need class interface information which when structured correctly can be extracted directly from a header file. When filling out the header comment blocks for a class, only include information needed by programmers who use the class. Don't delve into algorithm implementation details unless the details are needed by a user of the class. Consider comments in a header file a man page in waiting.Class ImplementorsClass implementors require in-depth knowledge of how a class is implemented. This comment type is found in the source file(s) implementing a class. Don't worry about interface issues. Header comment blocks in a source file should cover algorithm issues and other design decisions. Comment blocks within a method's implementation should explain even more.Directory DocumentationEvery directory should have a README file that covers:
Include Statement DocumentationInclude statements should be documented, telling the user why a particular file was included. If the file includes a class used by the class then it's useful to specify a class relationship:
Example#ifndef XX_h #define XX_h // SYSTEM INCLUDES // #includeNotice how just by reading the include directives the code is starting to tell you a story of why and how it was built. Block CommentsUse comments on starting and ending a Block:{ // Block1 (meaningful comment about Block1) ... some code { // Block2 (meaningful comment about Block2) ... some code } // End Block2 } // End Block1This may make block matching much easier to spot when you don't have an intelligent editor. Complexity ManagementLayeringLayering is the primary technique for reducing complexity in a system. A system should be divided into layers. Layers should communicate between adjacent layers using well defined interfaces. When a layer uses a non-adjacent layer then a layering violation has occurred.A layering violation simply means we have dependency between layers that is not controlled by a well defined interface. When one of the layers changes code could break. We don't want code to break so we want layers to work only with other adjacent layers. Sometimes we need to jump layers for performance reasons. This is fine, but we should know we are doing it and document appropriately.
Minimize Dependencies with Abstract Base ClassesOne of the most important strategies in C++ is to remove dependencies among different subsystems. Abstract base classes (ABCs) are a solid technique for dependency removal.An ABC is an abstraction of a common form such that it can be used to build more specific forms. An ABC is a common interface that is reusable across a broad range of similar classes. By specifying a common interface as long as a class conforming to that interface is used it doesn't really matter what is the type of the derived type. This breaks code dependencies. New classes, conforming to the interface, can be substituted in at will without breaking code. In C++ interfaces are specified by using base classes with virtual methods. The above is a bit rambling because it's a hard idea to convey. So let's use an example: We are doing a GUI where things jump around on the screen. One approach is to do something like: class Frog { public: void Jump(); } class Bean { public: void Jump(); }The GUI folks could instantiate each object and call the Jump method of each object. The Jump method of each object contains the implementation of jumping behavior for that type of object. Obviously frogs and beans jump differently even though both can jump. Unfortunately the owner of Bean didn't like the word Jump so they changed the method name to Leap. This broke the code in the GUI and one whole week was lost. Then someone wanted to see a horse jump so a Horse class was added: class Horse { public: void Jump(); }The GUI people had to change their code again to add Horse. Then someone updated Horse so that its Jump behavior was slightly different. Unfortunately this caused a total recompile of the GUI code and they were pissed. Someone got the bright idea of trying to remove all the above dependencies using abstract base classes. They made one base class that specified an interface for jumping things: class Jumpable { public: virtual void Jump() = 0; }Jumpable is a base class because other classes need to derive from it so they can get Jumpable's interface. It's an abstract base class because one or more of its methods has the = 0 notation which means the method is a pure virtual method. Pure virtual methods must be implemented by derived classes. The compiler checks. Not all methods in an ABC must be pure virtual, some may have an implementation. This is especially true when creating a base class encapsulating a process common to a lot of objects. For example, devices that must be opened, diagnostics run, booted, executed, and then closed on a certain event may create an ABC called Device that has a method called LifeCycle which calls all other methods in turn thus running through all phases of a device's life. Each device phase would have a pure virtual method in the base class requiring implementation by more specific devices. This way the process of using a device is made common but the specifics of a device are hidden behind a common interface. Back to Jumpable. All the classes were changed to derive from Jumpable: class Frog : public Jumpable { public: virtual void Jump() { ... } } etc ...We see an immediate benefit: we know all classes derived from Jumpable must have a Jump method. No one can go changing the name to Leap without the compiler complaining. One dependency broken. Another benefit is that we can pass Jumpable objects to the GUI, not specific objects like Horse or Frog: class Gui { public: void MakeJump(Jumpable*); } Gui gui; Frog* pFrog= new Frog; gui.MakeJump(pFrog);Notice Gui doesn't even know it's making a frog jump, it just has a jumpable thing, that's all it cares about. When Gui calls the Jump method it will get the implementation for Frog's Jump method. Another dependency down. Gui doesn't have to know what kind of objects are jumping. We also removed the recompile dependency. Because Gui doesn't contain any Frog objects it will not be recompiled when Frog changes. DownsideWow! Great stuff! Yes but there are a few downsides:Overhead for Virtual MethodsVirtual methods have a space and time penalty. It's not huge, but should be considered in design.Make Everything an ABC!Sometimes people overdo it, making everything an ABC. The rule is make an ABC when you need one not when you might need one. It takes effort to design a good ABC, throwing in a virtual method doesn't an ABC make. Pick and choose your spots. When some process or some interface can be reused and people will actually make use of the reuse then make an ABC and don't look back.Liskov's Substitution Principle (LSP)This principle states:All classes derived from a base class should be interchangeable when used as a base class.The idea is users of a class should be able to count on similar behavior from all classes that derive from a base class. No special code should be necessary to qualify an object before using it. If you think about it violating LSP is also violating the Open/Closed principle because the code would have to be modified every time a derived class was added. It's also related to dependency management using abstract base classes. For example, if the Jump method of a Frog object implementing the Jumpable interface actually makes a call and orders pizza we can say its implementation is not in the spirit of Jump and probably all other objects implementing Jump. Before calling a Jump method a programmer would now have to check for the Frog type so it wouldn't screw up the system. We don't want this in programs. We want to use base classes and feel comfortable we will get consistent behaviour. LSP is a very restrictive idea. It constrains implementors quite a bit. In general people support LSP and have LSP as a goal. Open/Closed PrincipleThe Open/Closed principle states a class must be open and closed where:
In practice the Open/Closed principle simply means making good use of our old friends abstraction and polymorphism. Abstraction to factor out common processes and ideas. Inheritance to create an interface that must be adhered to by derived classes. In C++ we are talking about using abstract base classes . A lot. Register/Dispatch IdiomAnother strategy for reducing dependencies in a system is the Register/Dispatch Idiom (RDI). RDI treats large grained occurrences in a system as events. Events are identified by some unique identifier. Objects in the system register with a dispatch system for events or classes of events it is interested in. Objects that are event sources send events into the dispatch system so the dispatch system can route events to consumers.RDI separates producers and consumers on a distributed scale. Event producers and consumers don't have to know about each other at all. Consumers can drop out of the event stream by deregistering for events. New consumers can register for events at anytime. Event producers can drop out with no ill effect to event consumers, the consumer just won't get any more events. It is a good idea for producers to have an "I'm going down event" so consumers can react intelligently. Logically the dispatch system is a central entity. The implementation however can be quite different. For a highly distributed system a truly centralized event dispatcher would be a performance bottleneck and a single point of failure. Think of event dispatchers as being a lot of different processes cast about on various machines for redundancy purposes. Event processors communicate amongst each other to distribute knowledge about event consumers and producers. Much like a routing protocol distributes routing information to its peers. RDI works equally well in the small, in processes and single workstations. Parts of the system can register as event consumers and event producers making for a very flexible system. Complex decisions in a system are expressed as event registrations and deregistrations. No further level of cooperation required. More expressive event filters can also be used. The above proposal filters events on some unique ID. Often you want events filtered on more complex criteria, much like a database query. For this to work the system has to understand all data formats. This is easy if you use a common format like attribute value pairs. Otherwise each filter needs code understanding packet formats. Compiling in filter code to each dispatcher is one approach. Creating a downloadable generic stack based filter language has been used with success on other projects, being both simple and efficient.
DelegationDelegation is the idea of a method using another object's method to do the real work. In some sense the top layer method is a front for the other method. Delegation is a form of dependency breaking. The top layer method never has to change while it's implementation can change at will.Delegation is an alternative to using inheritance for implementation purposes. One can use inheritance to define an interface and delegation to implement the interface. Some people feel delegation is a more robust form of OO than using implementation inheritance. Delegation encourages the formation of abstract class interfaces and HASA relationships. Both of which encourage reuse and dependency breaking. Exampleclass TestTaker { public: void WriteDownAnswer() { mPaidTestTaker.WriteDownAnswer(); } private: PaidTestTaker mPaidTestTaker; }In this example a test taker delegates actually answering the question to a paid test taker. Not ethical but a definite example of delegation!
Follow the Law of DemeterThe Law of Demeter states that you shouldn't access a contained object directly from the containing object, you should use a method of the containing object that does what you want and accesses any of its objects as needed.JustificationThe purpose of this law is to break dependencies so implementations can change without breaking code. If an object wishes to remove one of its contained objects it won't be able to do so because some other object is using it. If instead the service was through an interface the object could change its implementation anytime without ill effect.CaveatAs for most laws the Law of Demeter should be ignored in certain cases. If you have a really high level object that contains a lot of subobjects, like a car contains thousands of parts, it can get absurd to created a method in car for every access to a subobject.Exampleclass SunWorkstation { public: void UpVolume(int amount) { mSound.Up(amount); } SoundCard mSound; private: GraphicsCard mGraphics; } SunWorksation sun; Do : sun.UpVolume(1); Don't: sun.mSound.Up(1); Design by ContractThe idea of design by contract is strongly related to LSP . A contract is a formal statement of what to expect from another party. In this case the contract is between pieces of code. An object and/or method states that it does X and you are supposed to believe it. For example, when you ask an object for its volume that's what you should get. And because volume is a verifiable attribute of a thing you could run a series of checks to verify volume is correct, that is, it satisfies its contract.The contract is enforced in languages like Eiffel by pre and post condition statements that are actually part of the language. In other languages a bit of faith is needed. Design by contract when coupled with language based verification mechanisms is a very powerful idea. It makes programming more like assembling spec'd parts. Using Design by Contract
ClassesNaming Class FilesClass Definition in One FileEach class definition should be in its own file where each file is named directly after the class's name:ClassName.h Implementation in One FileIn general each class should be implemented in one source file:ClassName.cc // or whatever the extension is: cpp, c++ But When it Gets Really Big...If the source file gets too large or you want to avoid compiling templates all the time then add additional files named according to the following rule:ClassName_section.Csection is some name that identifies why the code is chunked together. The class name and section name are separated by '_'. Class LayoutA common class layout is critical from a code comprehension point of view and for automatically generating documentation. C++ programmers, through a new set of tools, can enjoy the same level generated documentation Java programmers take for granted.
Class and Method DocumentationIt is recommended a program like Doxygen be used to document C++ classes, method, variables, functions, and macros. The documentation can be extracted and put in places in a common area for all programmers to access. This saves programmers having to read through class headers. Documentation generation should be integrated with the build system where possible.
TemplatePlease use the following template when creating a new class./** A one line description of the class. * * #include "XX.h" <BR> * -llib * * A longer description. * * @see something */ #ifndef XX_h #define XX_h // SYSTEM INCLUDES // // PROJECT INCLUDES // // LOCAL INCLUDES // // FORWARD REFERENCES // class XX { public: // LIFECYCLE /** Default constructor. */ XX(void); /** Copy constructor. * * @param from The value to copy to this object. */ XX(const XX& from); /** Destructor. */ ~XX(void); // OPERATORS /** Assignment operator. * * @param from THe value to assign to this object. * * @return A reference to this object. */ XX& operator=(XX& from); // OPERATIONS // ACCESS // INQUIRY protected: private: }; // INLINE METHODS // // EXTERNAL REFERENCES // #endif // _XX_h_ Required Methods PlaceholdersThe template has placeholders for required methods . You can delete them or implement them.Ordering is: public, protected, privateNotice that the public interface is placed first in the class, protected next, and private last. The reasons are:
LIFECYCLEThe life cycle section is for methods that control the life cycle of an object. Typically these methods include constructors, destructors, and state machine methods.OPERATORSPlace all operators in this section.OPERATIONSPlace the bulk of a class's non access and inquiry method methods here. A programmer will look here for the meat of a class's interface.ACCESSPlace attribute accessors here.INQUIRYThese are the Is* methods. Whenever you have a question to ask about an object it can be asked via in Is method. For example: IsOpen() will indicate if the object is open. A good strategy is instead of making a lot of access methods you can turn them around to be questions about the object thus reducing the exposure of internal structure. Without the IsOpen() method we might have had to do: if (STATE_OPEN == State()) which is much uglier.What should go in public/protected/private?Public SectionOnly put an object's interface in the public section. DO NOT expose any private data items in the public section. At least encapsulate access via access methods. Ideally your method interface should make most access methods unnecessary. Do not put data in the public interface.Protected and Private SectionWhat should go into the protected section versus the private section is always a matter of debate.All ProtectedSome say there should be no private section and everything not in the public section should go in the protected section. After all, we should allow all our children to change anything they wish.
All PrivateAnother camp says by making the public interface virtual any derived class can change behavior without mucking with internals.
Wishy WashyRationally decide where elements should go and put them there. Not very helpful.And the Winner Is...Keeping everything all private seems the easiest approach. By making the public methods virtual flexibility is preserved.Prototype Source File#include "XX.h" // class implemented /////////////////////////////// PUBLIC /////////////////////////////////////// //============================= LIFECYCLE ==================================== XX::XX() { }// XX XX::XX(const XX&) { }// XX XX::~XX() { }// ~XX //============================= OPERATORS ==================================== XX& XX::operator=(XX&); { return *this; }// = //============================= OPERATIONS =================================== //============================= ACESS =================================== //============================= INQUIRY =================================== /////////////////////////////// PROTECTED /////////////////////////////////// /////////////////////////////// PRIVATE /////////////////////////////////// Use Header File GuardsInclude files should protect against multiple inclusion through the use of macros that "guard" the files.When Not Using Namespces#ifndef filename_h #define filename_h #endifThe new line after the endif if is required by some compilers.
When Using NamespacesIf namespaces are used then to be completely safe:#ifndef namespace_filename_h #define namespace_filename_h #endif
Required Methods for a ClassTo be good citizens almost all classes should implement the following methods. If you don't have to define and implement any of the "required" methods they should still be represented in your class definition as comments.
Justification
The Law of The Big ThreeA class with any of (destructor, assignment operator, copy constructor) generally needs all 3. For more information see http://www.parashift.com/c++-faq-lite/coding-standards.html#[25.9].ExampleThe default class template with all required methods. An example using default values:class Planet { public: /** The following is the default constructor if no arguments are supplied. */ Planet(int radius= 5); // Use compiler-generated copy constructor, assignment, and destructor. // Planet(const Planet&); // Planet& operator=(const Planet&); // ~Planet(); }; Method LayoutThe approach used is to place a comment block before each method that can be extracted by a tool and be made part of the class documentation. Here we'll use Doxygen which supports the Javadoc format. See the Doxygen documentation for a list of attributes supported by the document generator.
Method HeaderEvery parameter should be documented. Every return code should be documented. All exceptions should be documented. Use complete sentences when describing attributes. Make sure to think about what other resources developers may need and encode them in with the @see attributes./** Assignment operator. * * * @param val The value to assign to this object. * @exception LibaryException The explanation for the exception. * @return A reference to this object. */ XX& operator=(XX& val); Additional SectionsIn addition to the standard attribute set, the following sections can be included in the documentation:
/** Copy one string to another. * * PRECONDITION
Common Exception SectionsIf the same exceptions are being used in a number of methods, then the exceptions can be documented once in the class header and referred to from the method documentation.
Formatting Methods with Multiple ArgumentsWe should try and make methods have as few parameters as possible. If you find yourself passing the same variables to every method then that variable should probably be part of the class. When a method does have a lot of parameters format it like this:int AnyMethod( int arg1, int arg2, int arg3, int arg4); Different Accessor StylesWhy Accessors?Access methods provide access to the physical or logical attributes of an object. Accessing an object's attributes directly as we do for C structures is greatly discouraged in C++. We disallow direct access to attributes to break dependencies, the reason we do most things. Directly accessing an attribute exposes implementation details about the object.
Accessors Considered Somewhat HarmfulAt least in the public interface having accessors many times is an admission of failure, a failure to make an object's interface complete. At the protected or private level accessors are fine as these are the implementation levels of a class.Implementing AccessorsThere are three major idioms for creating accessors.Get/Setclass X { public: int GetAge() const { return mAge; } void SetAge(int age) { mAge= age; } private: int mAge; }The problem with Get/Set is twofold:
One Method Nameclass X { public: int Age() const { return mAge; } void Age(int age) { mAge= age; } private: int mAge; }Similar to Get/Set but cleaner. Use this approach when not using the Attributes as Objects approach. Attributes as Objectsclass X { public: int Age() const { return mAge; } int& rAge() { return mAge; } const String& Name() const { return mName; } String& rName() { return mName; } private: int mAge; String mName; }The above two attribute examples shows the strength and weakness of the Attributes as Objects approach. X x; x.rName()= "test";This approach is also more consistent with the object philosophy: the object should do it. An object's = operator can do all the checks for the assignment and it's done once in one place, in the object, where it belongs. It's also clean from a name perspective. When possible use this approach to attribute access. Init Idiom for Initializing Objects
Justification
Exampleclass Test { public: Test() { Init(); // Call to common object initializer } Test(int val) { Init(); // Call to common object initializer mVal= val; } private: int mVal; String* mpName; void Init() { mVal = 0; mpName= 0; } } Since the number of member variables is small, this might be better written as: class Test { public: Test(int val = 0, String* name = 0) : mVal(val), mpName(name) {} private: int mVal; String* mpName; }; Initialize all Variables
Justification
Minimize InlinesMinimize inlining in declarations or inlining in general. As soon as you put your C++ code in a shared library which you want to maintain compatibility with in the future, inlined code is a major pain in the butt. It's not worth it, for most cases.Think About What Work to do in ConstructorsShould you do work that can fail in constructors? If you have a compiler that does not support exceptions (or thread safe exceptions if it matters to you) then the answer is definitely no. Go directly to Do Work in Open. If your compiler supports exception then go to Do Work in Constructor. There are still reasons to use an Open method even with exceptions.Use Open Reasons
Do Work in ConstructorWith exceptions work done in the constructor can signal failure so it is fine to perform real work in the constructor. This is the guru endorced approach as a matter of fact. But there are reasons to still use an open style approach.The constructor code must still be very careful not to leak resources in the constructor. It's possible to throw an exception and not destruct objects allocated in the constructor. There is a pattern called Resource Acquisition as Initialization that says all initialization is performed in the constructor and released in the destructor. The idea is that this is a safer approach because it should reduce resource leaks. Do Work in OpenDo not do any real work in an object's constructor. Inside a constructor initialize variables only and/or do only actions that can't fail.Exampleclass Device { public: Device() { /* initialize and other stuff */ } int Open() { return FAIL; } }; Device dev; if (FAIL == dev.Open()) exit(1); Don't Over Use OperatorsC++ allows the overloading of all kinds of weird operators. Unless you are building a class directly related to math there are very few operators you should override. Only override an operator when the semantics will be clear to users.JustificationThin vs. Thick Class InterfacesHow many methods should an object have? The right answer of course is just the right amount, we'll call this the Goldilocks level. But what is the Goldilocks level? It doesn't exist. You need to make the right judgment for your situation, which is really what programmers are for :-)The two extremes are thin classes versus thick classes. Thin classes are minimalist classes. Thin classes have as few methods as possible. The expectation is users will derive their own class from the thin class adding any needed methods. While thin classes may seem "clean" they really aren't. You can't do much with a thin class. Its main purpose is setting up a type. Since thin classes have so little functionality many programmers in a project will create derived classes with everyone adding basically the same methods. This leads to code duplication and maintenance problems which is part of the reason we use objects in the first place. The obvious solution is to push methods up to the base class. Push enough methods up to the base class and you get thick classes. Thick classes have a lot of methods. If you can think of it a thick class will have it. Why is this a problem? It may not be. If the methods are directly related to the class then there's no real problem with the class containing them. The problem is people get lazy and start adding methods to a class that are related to the class in some willow wispy way, but would be better factored out into another class. Judgment comes into play again. Thick classes have other problems. As classes get larger they may become harder to understand. They also become harder to debug as interactions become less predictable. And when a method is changed that you don't use or care about your code will still have to be recompiled, possibly retested, and rereleased. Short MethodsJustification
In a Source file Indicate if a Method is Static or VirtualIn a source file you can't tell a method is static or virtual because this information is in the header file. Knowing this information in a source file is useful and can be communicated using comments:/*virtual*/ void Class::method() { } /*static*/ void Class::method() { }
ProcessUse a Design Notation and ProcessProgrammers need to have a common language for talking about coding, designs, and the software process in general. This is critical to project success.Any project brings together people of widely varying skills, knowledge, and experience. Even if everyone on a project is a genius you will still fail because people will endlessly talk past each other because there is no common language and processes binding the project together. All you'll get is massive fights, burnout, and little progress. If you send your group to training they may not come back seasoned experts but at least your group will all be on the same page; a team. There are many popular methodologies out there. The point is to do some research, pick a method, train your people on it, and use it. Take a look at the top of this page for links to various methodologies. You may find an Agile methodology to your liking. For more information see http://www.possibility.com/epowiki/Wiki.jsp?page=agile. You may find the CRC (class responsibility cards) approach to teasing out a design useful. Many others have. It is an informal approach encouraging team cooperation and focusing on objects doing things rather than objects having attributes. There's even a whole book on it: Using CRC Cards by Nancy M. Wilkinson. Using Use CasesA use case is a generic description of an entire transaction involving several objects. A use case can also describe the behaviour of a set of objects, such as an organization. A use case model thus presents a collection of use cases and is typically used to specify the behavior of a whole application system together with one or more external actors that interact with the system.Requirements CaptureUse cases attempt to capture the requirements for a system in an understandable form. The idea is by running through a set of use case we can verify that the system is doing what it should be doing.Have as many use cases as needed to describe what a system needs to accomplish. The Process
Using StoriesA user story consists of just a phrase or a few sentences written down, announcing something the user wants to do. The user story is not used as a requirements specification, but as a marker for a future conversation.
A Story Is
How It All Fits TogetherThere are a lot of entrants in this part of the development process. We have user stories, use cases, task analysis, task cases, usage scenarios, etc and etc.
User Stories Need to be Fleshed OutUser Stories are symbolic of the stuff that needs to get done. They are like the reminder notes you make to yourself. In the detailed design these can be expanded out to uses cases, to more detailed notes, state machines, etc. Or TestDrivenDesign practices could be used to flesh out the detailed implementation.For more information see http://www.possibility.com/epowiki/Edit.jsp?page=UserStory.
Unified Modeling LanguageThe Unified Modeling Language is too large to present here. Fortunately you can see it at Rational's web site. Since you do need a modeling language UML is a safe choice. It combines features from several methods into one unified language. Remember all languages and methods are open to local customization. If their language is too complex then use the parts you and your project feel they need and junk the rest.Code ReviewsIf you can make a formal code review work then my hat is off to you. Code reviews can be very useful. Unfortunately they often degrade into nit picking sessions and endless arguments about silly things. They also tend to take a lot of people's time for a questionable payback.My god he's questioning code reviews, he's not an engineer! Not really, it's the form of code reviews and how they fit into normally late chaotic projects is what is being questioned. First, code reviews are way too late to do much of anything useful. What needs reviewing are requirements and design. This is where you will get more bang for the buck. Get all relevant people in a room. Lock them in. Go over the class design and requirements until the former is good and the latter is being met. Having all the relevant people in the room makes this process a deep fruitful one as questions can be immediately answered and issues immediately explored. Usually only a couple of such meetings are necessary. If the above process is done well coding will take care of itself. If you find problems in the code review the best you can usually do is a rewrite after someone has sunk a ton of time and effort into making the code "work." You will still want to do a code review, just do it offline. Have a couple people you trust read the code in question and simply make comments to the programmer. Then the programmer and reviewers can discuss issues and work them out. Email and quick pointed discussions work well. This approach meets the goals and doesn't take the time of 6 people to do it.
Create a Source Code Control System Early and Not OftenA common build system and source code control system should be put in place as early as possible in a project's lifecycle, preferably before anyone starts coding. Source code control is the structural glue binding a project together. If programmers can't easily use each other's products then you'll never be able to make a good reproducible build and people will piss away a lot of time. It's also hell converting rogue build environments to a standard system. But it seems the right of passage for every project to build their own custom environment that never quite works right.
Source Code Control SystemsSome options for source code control systems are:
There are many other options out there. It doesn't matter which one you pick as much as it does that you pick one and use it.
Create a Bug Tracking System Early and Not OftenThe earlier people get used to using a bug tracking system the better. If you are 3/4 through a project and then install a bug tracking system it won't be used. You need to install a bug tracking system early so people will use it.Programmers generally resist bug tracking, yet when used correctly it can really help a project:
FYI, it's not a good idea to reward people by the number of bugs they fix :-)
Bug Tracking SystemsSome options for bug tracking systems are:
As for source code control systems there are many available bug tracking systems. It's more important that you use one than which one you use.
RCS Keywords, Change Log, and History PolicyWhen using RCS directly this policy must change, but when using other source code control systems like CVS that support RCS style keywords:
Justification
Create a Wiki System Early and Not OftenThe heart of software development is information. Where do you put all your documentation? Where do we put your coding guidelines? Where you put all your process documents? Where do you put your design documents? Where do you put all the 1000s of bits of information that hold a project together?A wiki is perfect support for software development. I've written up my hard one advice for using wikis at Getting Your Wiki Adopted.
Honor ResponsibilitiesResponsibility for software modules is scoped. Modules are either the responsibility of a particular person or are common. Honor this division of responsibility. Don't go changing things that aren't your responsibility to change. Only mistakes and hard feelings will result.Face it, if you don't own a piece of code you can't possibly be in a position to change it. There's too much context. Assumptions seemingly reasonable to you may be totally wrong. If you need a change simply ask the responsible person to change it. Or ask them if it is OK to make such-n-such a change. If they say OK then go ahead, otherwise holster your editor. Every rule has exceptions. If it's 3 in the morning and you need to make a change to make a deliverable then you have to do it. If someone is on vacation and no one has been assigned their module then you have to do it. If you make changes in other people's code try and use the same style they have adopted. Programmers need to mark with comments code that is particularly sensitive to change. If code in one area requires changes to code in an another area then say so. If changing data formats will cause conflicts with persistent stores or remote message sending then say so. If you are trying to minimize memory usage or achieve some other end then say so. Not everyone is as brilliant as you. The worst sin is to flit through the system changing bits of code to match your coding style. If someone isn't coding to the standards then ask them or ask your manager to ask them to code to the standards. Use common courtesy. Code with common responsibility should be treated with care. Resist making radical changes as the conflicts will be hard to resolve. Put comments in the file on how the file should be extended so everyone will follow the same rules. Try and use a common structure in all common files so people don't have to guess on where to find things and how to make changes. Checkin changes as soon as possible so conflicts don't build up. As an aside, module responsibilities must also be assigned for bug tracking purposes.
Process AutomationIt's a sad fact of human nature that if you don't measure it or check for it: it won't happen. The implication is you must automate as much of the development process as possible and provide direct feedback to developers on specific issues that they can fix.Process automation also frees up developers to do real work because they don't have to babysit builds and other project time sinks.
Automated Builds and Error AssignmentCreate an automated build system that can create nightly builds, parse the build errors, assign the errors to developers, and email developers their particular errors so they can fix them.This is the best way to maintain a clean build. Make sure the list of all errors for a build is available for everyone to see so everyone can see everyone elses errors. The goal is replace a blaim culture with a culture that tries to get things right and fixes them when they are wrong. Immediate feedback makes this possible.
Automated Code CheckingAs part of the automated build process you can check for coding standard violations and for other problems. If you don't check for it people will naturally do their own thing. Code reviews aren't good enough to keep the code correct. With a tool like Abraxis Code Check you can check the code for a lot of potential problems.This feature like the automated error assignment makes problems immediately visible and immediately correctable, all without a lot of blame and shame. Documentation ExtractionRelated to this principle is the need to automatically extract documentation from the source code and make it available on line for everyone to use. If you don't do this documentation will be seen as generally useless and developers won't put as much effort into it. Making the documentation visible encourages people to do a better job.Connect Source Code Control System and Bug Tracking System
Tools AgreementThe reality of different tool preferences is something to deal with explicitly and openly. Tools include IDEs, languages, editors, make program, source code control, bug system, debuggers, test framework, etc. Some tool decisions by their nature must be project wide, other decisions can be customized per developer.A split might also be done by who is performing the build. For example, an IDE should be able to used in local builds, but the make program would be used for nightly and release builds. Certain things are easy/trivial/useful with one tool, but hard/complicated/stupid with another tool. Unstated tool assumptions can be the source of a lot of confusion. "Get a better editor" is not always a workable response, though sometimes that's all there is to it!
Non-Blocking SchedulingSchedules are lies.  Yes, yes, yes. But we still need them.The most effective scheduling rule i've used is to schedule so as to unblock others. The idea is to complete the portions of a feature that will unblock those dependent on you. This way development moves along smoothly because more lines of development can be active at a time. For example, instead of implementing the entire database, implement the simple interface and stub it out. People can work for a very long time this way using that portion of the feature that caused others not to block. Plus it's a form of rapid prototyping because you get immediate feedback on these parts. Don't worry about the quality of implementation because it doesn't matter yet. Using PersonasPersonas are a powerful design tool, especially when combined with responsibility driven design. Cooper's personas are:.simply pretend users of the system you're building. You describe them, in a surprising amount of detail, and then design your system for them. I have a standard set of personas that i consider when creating a design/architecture that don't seem to be common. When you write code their are a lot of personas looking over your shoulder:
You are much more careful and more thorough when you really thing about all the personas, all the different people and all their different roles and purposes. Use a Continuous Build SystemSetup a continuous build system for your group. It should build all new check-ins and run the unit tests for each change. If you have the resources run a smoke test for each build as well.If there's a failure email should go out to the developer's who made the check-ins.
Code in the Dominant StyleLet's say someone invites you into your home as a guest. How do you act? Do you act as you do at home or do you try and fit in with the household in which you are staying? You try to fit in of course.
Run Unit Tests Before Every Check-inBefore every check-in developers must run unit tests to verify all unit tests should pass. This prevents letting any errors creep in.
FormattingBraces {} PolicyBrace PlacementOf the three major brace placement strategies two are acceptable, with the first one listed being preferable:
Justification
When Braces are NeededAll if, while and do statements must either have braces or be on a single line.
Always Uses Braces FormAll if, while and do statements require braces even if there is only a single statement within the braces. For example:if (1 == somevalue) { somevalue = 2; } JustificationIt ensures that when someone adds a line of code later there are already braces and they don't forget. It provides a more consistent look. This doesn't affect execution speed. It's easy to do.One Line Formif (1 == somevalue) somevalue = 2; JustificationIt provides safety when adding new lines while maintainng a compact readable form.Add Comments to Closing BracesAdding a comment to closing braces can help when you are reading code because you don't have to find the begin brace to know what is going on.while(1) { if (valid) { } // if valid else { } // not valid } // end forever Consider Screen Size LimitsSome people like blocks to fit within a common screen size so scrolling is not necessary when reading code.Indentation/Tabs/Space Policy
Justification
Examplevoid func() { if (something bad) { if (another thing bad) { while (more input) { } } } } Parens () with Key Words and Functions Policy
Justification
Exampleif (condition) { } while (condition) { } strcpy(s, s1); return 1; A Line Should Not Exceed 78 Characters
Justification
If Then Else FormattingLayoutIt's up to the programmer. Different bracing styles will yield slightly different looks. One common approach is:if (condition) // Comment { } else if (condition) // Comment { } else // Comment { }If you have else if statements then it is usually a good idea to always have an else block for finding unhandled cases. Maybe put a log message in the else even if there is no corrective action taken.
Condition FormatAlways put the constant on the left hand side of an equality/inequality comparison. For example:if ( 6 == errorNum ) ... One reason is that if you leave out one of the = signs, the compiler will find the error for you. A second reason is that it puts the value you are looking for right up front where you can find it instead of buried at the end of your expression. It takes a little time to get used to this format, but then it really gets useful.
switch Formatting
Exampleswitch (...) { case 1: ... // FALL THROUGH case 2: { int v; ... } break; default: } Use of goto,continue,break and ?:GotoGoto statements should be used sparingly, as in any well-structured code. The goto debates are boring so we won't go into them here. The main place where they can be usefully employed is to break out of several levels of switch, for, and while nesting, although the need to do such a thing may indicate that the inner constructs should be broken out into a separate function, with a success/failure return code.
for (...) { while (...) { ... if (disaster) goto error; } } ... error: clean up the mess When a goto is necessary the accompanying label should be alone on a line and to the left of the code that follows. The goto should be commented (possibly in the block header) as to its utility and purpose. Continue and BreakContinue and break are really disguised gotos so they are covered here.Continue and break like goto should be used sparingly as they are magic in code. With a simple spell the reader is beamed to god knows where for some usually undocumented reason. The two main problems with continue are:
Consider the following example where both problems occur: while (TRUE) { ... // A lot of code ... if (/* some condition */) { continue; } ... // A lot of code ... if ( i++ > STOP_VALUE) break; }Note: "A lot of code" is necessary in order that the problem cannot be caught easily by the programmer. From the above example, a further rule may be given: Mixing continue with break in the same loop is a sure way to disaster.
?:The trouble is people usually try and stuff too much code in between the ? and :. Here are a couple of clarity rules to follow:
Example(condition) ? funct1() : func2(); or (condition) ? long statement : another long statement;
One Statement Per LineThere should be only one statement per line unless the statements are very closely related.The reasons are:
One Variable Per LineRelated to this is always define one variable per line:Not: char **a, *x; Do: char** a= 0; // add doc char* x= 0; // add docThe reasons are:
Alignment of Declaration BlocksJustification
ExampleDWORD mDword DWORD* mpDword char* mpChar char mChar mDword = 0; mpDword = NULL; mpChar = NULL; mChar = 0; Include static and virtual Key Words in Source FileIf a method is made static or virtual in the header file then also include this information as a short comment in the source file. For example:In .h file: class PopcornPopper { public: virtual void Pop(void); static PopcornPopper* Singleton(); }; In .cpp file: /*virtual*/ void PopcornPopper::Pop(void) { }// Pop /*static*/ PopcornPopper* PopcornPopper::Singleton() { }// Singleton
Document Null StatementsAlways document a null body for a for or while statement so that it is clear that the null body is intentional and not missing code.while (*dest++ = *src++) ; // VOID
ExceptionsCreate One Exception for Each LibraryCreating very elaborate exception hierarchies is a waste of time. Nobody ends of caring and all the effort goes to waste. Instead, create one exception per library or namespace and have an exception reason within that exception to indicate the type of the exception.For example, for your OS encapsulation libary, make an exception called OsencapException. Make sure to document that an exception is being thrown in you method comment header. Include a stack trace of where the exception happened so you can log the stack trace. THROW_NAMESPACE_EX_IF(cond, msg1, msg2, reason);The condition causes the exception to be thrown when true. Msg1 and msg2 are local context. Reason is the specific error code for the exception, if you think you need it.
Selecting Between Exceptions And AssertsIf there is reason to believe that an important test could fail in the released product, it should not be tested with an assert, use an exception instead.Two useful questions to ask yourself are:
Exception DefinitionThere are as many definitions of exception as there are programmers:
The Clean Code DefinitionWrite a function as if everything worked. Any error handling that prevents the code from looking like this is an exception. The Design by Contract DefinitionWhen an operation is invoked with it's pre-condition satisfied, yet it cannot return with its post-condition satisfied.
Design-by-Contract (DBC)A design technique developed by Bertrand Meyer for producing "bug free" systems.
AssertionA boolean statement that should never be false and, therefore, will only be false because of a bug. Typically assertions are checked only during debug and are not checked during production execution, although they can be left in when performance and memory size are not issues.
Pre-conditionA statement of how we expect the world to be before we execute an operation. We might design a pre-condition of the "square" operation as this >= 0. Such a pre-condition says that it is an error to invoke "square" on a negative number.
Post-conditionA statement of what the world should look like after execution of an operation. For example, if we define the operation "square" on a number, the post-condition would take the form result = this *this. The post-condition is a useful way of saying what we do without saying how we do it- in other words, of separating interface from implementation.
InvariantAn invariant is an assertion about a class. For instance, an Account class may have an invariant that says that balance == sum(entries.amount()). The invariant is always true for all instances of the class. "Always" means whenever the object is available for an operation to be invoked. During an operation invariants may not be satisfied, but invariants must hold when an operation has finished.
Is pop'ing an empty stack an exception?When using a stack data structure is calling pop on an empty stack an exception? This is the standard use case for the endless discussions on what is and what isn't an exception. The upshot is there is not a "right" answer. In practice, as long as the library designer completely documents their choice the library user shouldn't make a mistake.Let's apply our definition of exception.
The Clean Code ViewIf you write your application assuming everything works then is pop returning null something you wouldn't expect? It seems reasonable that if you ask for something it may not be there.So don't use an exception. Pop returns data so it should return null when empty.
The Design by Contract ViewShould the library designer have as a pre-condition that pop shouldn't be called when the stack is empty? From an implementor point of view this could seem reasonable. After all, why should an operation be called when there's nothing there? So, pop could assert.
Be Careful Throwing Exceptions in DestructorsAn object is presumably created to do something. Some of the changes made by an object should persist after an object dies (is destructed) and some changes should not. Take an object implementing a SQL query. If a database field is updated via the SQL object then that change should persist after the SQL objects dies. To do its work the SQL object probably created a database connection and allocated a bunch of memory. When the SQL object dies we want to close the database connection and deallocate the memory, otherwise if a lot of SQL objects are created we will run out of database connections and/or memory.The logic might look like: Sql::~Sql() { delete connection; delete buffer; } Let's say an exception is thrown while deleting the database connection. Will the buffer be deleted? No. Exceptions are basically non-local gotos with stack cleanup. The code for deleting the buffer will never be executed creating a gaping resource leak. Special care must be taken to catch exceptions which may occur during object destruction. Special care must also be taken to fully destruct an object when it throws an exception. Usign RAII can help prevent many of not most of these type of errors.
Working With Libaries Using All Sorts of Different PoliciesOn many projects we have to work with C libraries that use error return codes, old C++ libraries that use error return codes, and newer C++ libraries that use exceptions. How should all these different approaches work together?
TemplatesTemplates have never come up as an issue on project I've worked on, so my advice on templates isn't very useful.Template meta programming is too elite for me so I'll leave that to other people.
NamespacesCreate Unique Name Space NamesA namespace isn't of much use if it's not globally unique.On way to make name spaces unique is to root tham at some naming Personally that always seemed overkill to me, but does work in the large. For externally visible code you'll probably need to the full domain style namespace just to be safe.
Don't Globally Define usingDon't place using namespace directive at global scope in a header file. This can cause lots of magic invisible conflicts that are hard to track. Keep using statements to implementation files.#include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o class Calendar { public: boost::gregorian::date GetEventDate(void) const; void SetEventDate(boost::gregorian::date dateOfTheEvent); };Clearly these are long names and are noisy and are pain to use. So you are tempted to put at the top of you class file: using namespace boost::gregorian; // make namespace global for this fileThis would mean you could just use "date" instead of "boost::gregorian::date". That's nice. But you can't do that. If you do you are making the decision for everyone who uses your class as well. They may have a conflict, "date" is a very common name afterall.
Create Shortcut NamesYou can use using to create aliases or shortcuts, that is names that are more convenient to access than long namespace names.namespace alias = a::very::long::namespace; class YourClass: public alias::TheirClass { ... }Clearly this makes code both harder to read and easier to read. The code is harder to read because you as a programmer have to compile the alias directive in your head and know what it means whenever it is used in the code.
MiscellaneousThis section contains some miscellaneous do's and don'ts.
Be Const CorrectC++ provides the const key word to allow passing as parameters objects that cannot change to indicate when a method doesn't modify its object. Using const in all the right places is called "const correctness."It's hard at first, but using const really tightens up your coding style. Const correctness grows on you. If you don't use const correctness from the start it can be nightmare to add it in later because it causes a chain reaction of needing const everywhere. It's better to start being const correct from the start or you probably won't be. You can always cast aways constness when necessary, but it's better not to. For more information see Const Correctness in the C++ FAQ.
Use StreamsProgrammers transitioning from C to C++ find stream IO strange preferring the familiarity of good old stdio. Printf and gang seem to be more convenient and are well understood.
Type SafetyStdio is not type safe, which is one of the reasons you are using C++, right? Stream IO is type safe. That's one good reason to use streams.
Standard InterfaceWhen you want to dump an object to a stream there is a standard way of doing it: with the << operator. This is not true of objects and stdio.Interchangeablity of StreamsOne of the more advanced reasons for using streams is that once an object can dump itself to a stream it can dump itself to any stream. One stream may go to the screen, but another stream may be a serial port or network connection. Good stuff.Streams Got BetterStream IO is not perfect. It is however a lot better than it used to be. Streams are now standardized, acceptably efficient, more reliable, and now there's lots of documentation on how to use streams.Check Thread SafetySome stream implementations are not yet thread safe. Make sure that yours is.But Not PerfectFor an embedded target tight on memory streams do not make sense. Streams inline a lot of code so you might find the image larger than you wish. Experiment a little. Streams might work on your target.No Magic NumbersA magic number is a bare naked number used in source code. It's magic because no-one has a clue what it means including the author inside 3 months. For example:
if (22 == foo) { start_thermo_nuclear_war(); } else if (19 == foo) { refund_lotso_money(); } else if (16 == foo) { infinite_loop(); } else { cry_cause_im_lost(); }In the above example what do 22 and 19 mean? If there was a number change or the numbers were just plain wrong how would you know? Instead of magic numbers use a real name that means something. You can use #define or constants or enums as names. Which one is a design choice. For example: #define PRESIDENT_WENT_CRAZY (22) const int WE_GOOFED= 19; enum { THEY_DIDNT_PAY= 16 }; if (PRESIDENT_WENT_CRAZY == foo) { start_thermo_nuclear_war(); } else if (WE_GOOFED == foo) { refund_lotso_money(); } else if (THEY_DIDNT_PAY == foo) { infinite_loop(); } else { happy_days_i_know_why_im_here(); }Now isn't that better? The const and enum options are preferable because when debugging the debugger has enough information to display both the value and the label. The #define option just shows up as a number in the debugger which is very inconvenient. The const option has the downside of allocating memory. Only you know if this matters for your application.
Error Return Check Policy
To Use Enums or Not to Use EnumsC++ allows constant variables, which should deprecate the use of enums as constants. Unfortunately, in most compilers constants take space. Some compilers will remove constants, but not all. Constants taking space precludes them from being used in tight memory environments like embedded systems. Workstation users should use constants and ignore the rest of this discussion.In general enums are preferred to #define as enums are understood by the debugger. Be aware enums are not of a guaranteed size. So if you have a type that can take a known range of values and it is transported in a message you can't use an enum as the type. Use the correct integer size and use constants or #define. Casting between integers and enums is very error prone as you could cast a value not in the enum. A C++ WorkaroundC++ allows static class variables. These variables are available anywhere and only the expected amount of space is taken.Exampleclass Variables { public: static const int A_VARIABLE; static const int B_VARIABLE; static const int C_VARIABLE; } MacrosDon't Turn C++ into PascalDon't change syntax via macro substitution. It makes the program unintelligible to all but the perpetrator.Replace Macros with Inline FunctionsIn C++ macros are not needed for code efficiency. Use inlines.Example#define MAX(x,y) (((x) > (y) ? (x) : (y)) // Get the maximum The macro above can be replaced for integers with the following inline function with no loss of efficiency: inline int max(int x, int y) { return (x > y ? x : y); } Be Careful of Side EffectsMacros should be used with caution because of the potential for error when invoked with an expression that has side effects.ExampleMAX(f(x),z++); Always Wrap the Expression in ParenthesisWhen putting expressions in macros always wrap the expression in parenthesis to avoid potential communitive operation ambiguity.Example#define ADD(x,y) x + y must be written as #define ADD(x,y) ((x) + (y)) Make Macro Names UniqueLike global variables macros can conflict with macros from other packages.
Do Not Default If Test to Non-ZeroDo not default the test for non-zero, i.e.if (FAIL != f())is better than if (f())even though FAIL may have the value 0 which C considers to be false. An explicit test will help you out later when somebody decides that a failure return should be -1 instead of 0. Explicit comparison should be used even if the comparison value will never change; e.g., if (!(bufsize % sizeof(int))) should be written instead as if ((bufsize % sizeof(int)) == 0) to reflect the numeric (not boolean) nature of the test. A frequent trouble spot is using strcmp to test for string equality, where the result should never ever be defaulted. The preferred approach is to define a macro STREQ.
#define STREQ(a, b) (strcmp((a), (b)) == 0) Or better yet use an inline method: inline bool StringEqual(char* a, char* b) { return strcmp(a, b) == 0; } Note, this is just an example, you should really use the standard library string type for doing the comparison. The non-zero test is often defaulted for predicates and other functions or expressions which meet the following restrictions:
The Bull of Boolean TypesAny project using source code from many sources knows the pain of multiple conflicting boolean types. The new C++ standard defines a native boolean type. Until all compilers support bool, and existing code is changed to use it, we must still deal with the cruel world.The form of boolean most accurately matching the new standard is: typedef int bool; #define TRUE 1 #define FALSE 0 or const int TRUE = 1; const int FALSE = 0;Note, the standard defines the names true and false not TRUE and FALSE. The all caps versions are used to not clash if the standard versions are available. Even with these declarations, do not check a boolean value for equality with 1 (TRUE, YES, etc.); instead test for inequality with 0 (FALSE, NO, etc.). Most functions are guaranteed to return 0 if false, but only non-zero if true. Thus, if (TRUE == func()) { ...must be written if (FALSE != func()) { ...
Usually Avoid Embedded AssignmentsThere is a time and a place for embedded assignment statements. In some constructs there is no better way to accomplish the results without making the code bulkier and less readable.
while (EOF != (c = getchar())) { process the character } The ++ and -- operators count as assignment statements. So, for many purposes, do functions with side effects. Using embedded assignment statements to improve run-time performance is also possible. However, one should consider the tradeoff between increased speed and decreased maintainability that results when embedded assignments are used in artificial places. For example, a = b + c; d = a + r;should not be replaced by d = (a = b + c) + r;even though the latter may save one cycle. In the long run the time difference between the two will decrease as the optimizer gains maturity, while the difference in ease of maintenance will increase as the human memory of what's going on in the latter piece of code begins to fade.
Reusing Your Hard Work and the Hard Work of OthersReuse across projects is almost impossible without a common framework in place. Objects conform to the services available to them. Different projects have different service environments making object reuse difficult.Developing a common framework takes a lot of up front design effort. When this effort is not made, for whatever reasons, there are several techniques one can use to encourage reuse:
Ask! Email a Broadcast Request to the GroupThis simple technique is rarely done. For some reason programmers feel it makes them seem less capable if they ask others for help. This is silly! Do new interesting work. Don't reinvent the same stuff over and over again.If you need a piece of code email to the group asking if someone has already done it. The results can be surprising. In most large groups individuals have no idea what other people are doing. You may even find someone is looking for something to do and will volunteer to do the code for you. There's always a gold mine out there if people work together. Tell! When You do Something Tell EveryoneLet other people know if you have done something reusable. Don't be shy. And don't hide your work to protect your pride. Once people get in the habit of sharing work everyone gets better.Don't be Afraid of Small LibrariesOne common enemy of reuse is people not making libraries out of their code. A reusable class may be hiding in a program directory and will never have the thrill of being shared because the programmer won't factor the class or classes into a library.One reason for this is because people don't like making small libraries. There's something about small libraries that doesn't feel right. Get over it. The computer doesn't care how many libraries you have. If you have code that can be reused and can't be placed in an existing library then make a new library. Libraries don't stay small for long if people are really thinking about reuse. If you are afraid of having to update makefiles when libraries are recomposed or added then don't include libraries in your makefiles, include the idea of services. Base level makefiles define services that are each composed of a set of libraries. Higher level makefiles specify the services they want. When the libraries for a service change only the lower level makefiles will have to change.
Keep a RepositoryMost companies have no idea what code they have. And most programmers still don't communicate what they have done or ask for what currently exists. The solution is to keep a repository of what's available.In an ideal world a programmer could go to a web page, browse or search a list of packaged libraries, taking what they need. If you can set up such a system where programmers voluntarily maintain such a system, great. If you have a librarian in charge of detecting reusability, even better. Another approach is to automatically generate a repository from the source code. This is done by using common class, method, library, and subsystem headers that can double as man pages and repository entries.
Commenting Out Large Code BlocksSometimes large blocks of code need to be commented out for testing.Using #if 0The easiest way to do this is with an #if 0 block:void example() { great looking code #if 0 lots of code #endif more code } You can't use /**/ style comments because comments can't contain comments and surely a large block of your code will contain a comment, won't it? Don't use #ifdef as someone can unknowingly trigger ifdefs from the compiler command line. Use Descriptive Macro Names Instead of 0The problem with #if 0 is that even day later you or anyone else has no idea why this code is commented out. Is it because a feature has been dropped? Is it because it was buggy? It didn't compile? Can it be added back? It's a mystery.Use Descriptive Macro Names Instead of #if 0#if NOT_YET_IMPLEMENTED #if OBSOLETE #if TEMP_DISABLED Add a Comment to Document WhyAdd a short comment explaining why it is not implemented, obsolete or temporarily disabled.
Use #if Not #ifdefUse #if MACRO not #ifdef MACRO. Someone might write code like:#ifdef DEBUG temporary_debugger_break(); #endifSomeone else might compile the code with turned-of debug info like: cc -c lurker.cpp -DDEBUG=0Alway use #if, if you have to use the preprocessor. This works fine, and does the right thing, even if DEBUG is not defined at all (!) #if DEBUG temporary_debugger_break(); #endifIf you really need to test whether a symbol is defined or not, test it with the defined() construct, which allows you to add more things later to the conditional without editing text that's already in the program: #if !defined(USER_NAME) #define USER_NAME "john smith" #endif Creating a C Function in C++extern "C" void a_c_function_in_cplusplus(int a) { } __cplusplus Preprocessor DirectiveIf you have code that must compile in a C and C++ environment then you must use the __cplusplus preprocessor directive. For example:
#ifdef __cplusplus extern "C" some_function(); #else extern some_function(); #endif Mixing C and C++In order to be backward compatible with dumb linkers C++'s link time type safety is implemented by encoding type information in link symbols, a process called name mangling. This creates a problem when linking to C code as C function names are not mangled. When calling a C function from C++ the function name will be mangled unless you turn it off. Name mangling is turned off with the extern "C" syntax. If you want to create a C function in C++ you must wrap it with the above syntax. If you want to call a C function in a C library from C++ you must wrap in the above syntax. Here are some examples:
Calling C Functions from C++extern "C" int strncpy(...); extern "C" int my_great_function(); extern "C" { int strncpy(...); int my_great_function(); }; No Data Definitions in Header FilesDo not put data definitions in header files. for example:/* * aheader.h */ int x = 0;
Make Functions ReentrantFunctions should not keep static variables that prevent a function from being reentrant. Functions can declare variables static. Some C library functions in the past, for example, kept a static buffer to use a temporary work area. Problems happen when the function is called one or more times at the same time. This can happen when multiple tasks are used or say from a signal handler. Using the static buffer caused results to overlap and become corrupted.Use the Resource Acquisition is Initialization (RAII) IdiomRAII is a pattern useful in making sure allocated resources get freed. What kind of resources? Memory usually. Could be file descriptors or locks too. Anything that is allocated at one point and needs to be deleted at another point in your code.See http://www.hackcraft.net/raii/ for a better explanation of RAII.
PortabilityUse Typedefs for TypesIt's a good idea to typedef int8, int16, int32, int64, float32, float64, uint8, uint16, uint32, uint64, etc., instead of assuming it'll be done with int, long, float, and short.Alignment of Class MembersThere seems to be disagreement on how to align class data members. Be aware that different platforms have different alignment rules and it can be an issue. Alignment may also be an issue when using shared memory and shared libraries.The real thing to remember when it comes to alignment is to put the biggest data members first, and smaller members later, and to pad with char[] so that the same structure would be used no matter whether the compiler was in "naturally aligned" or "packed" mode. For the Mac there's no blanket "always on four byte boundaries" rule -- rather, the rule is "alignment is natural, but never bigger than 4 bytes, unless the member is a double and first in the struct in which case it is 8". And that rule was inherited from PowerOpen/AIX. Compiler Dependent ExceptionsUsing exceptions across the shared library boundary could cause some problems if the shared library and the client module are compiled by different compiler vendors.Compiler Dependent RTTIDifferent compilers are not guaranteed to name types the same.Popular MythsPromise of OOOO has been hyped to the extent you'd figure it would solve world hunger and usher in a new era of world peace. Not! OO is an approach, a philosophy, it's not a recipe which blindly followed yields quality.Robert Martin put OO in perspective:
You can't use OO and C++ on Embedded SystemsOh yes you can. I've used C++ on several embedded systems as have many others. And if you can't why not? Please don't give in to vague feelings and prejudice. An attitude best shown with a short exchange:Rube: Our packet driver is slow. We're only getting 100 packets per second. Me : Good thing you didn't do it in C++ huh? Rube: Oh yah, it would have been really slow then! Me : (smiled secretly to myself)My initial response was prompted by a general unacceptance of C++ in the project and blaming C++ for all problems. Of course all the parts written in C and assembly had no problems :-) Embedded systems shops tend to be hardware driven companies and tend not to know much about software development, thus any new fangled concepts like OO and C++ are ridiculed without verbally accessible reasons. Counter arguments like code that is fast and small and reusable don't make a dent. Examples like improving the speed of a driver by inlining certain methods and not hacking the code to death gently roll into the bit bucket.
TechniquesOf course C++ can be a disaster for an embedded system when used incorrectly, which of course is true of any tool. Here's some ideas to use C++ safely in an embedded system:
Original HeaderI altered the coding standard to fit the requirements of my project but the original was made by Todd Hoff which saved me a lot of work. Below you will find the original header. The following license applies to the original text: © Copyright 1995-2006. Todd Hoff. All rights reserved.
Last Modified<EMAIL_ADDRESS>/ http://www.possibility.com/Tmh
© Copyright 2007. Dinand Vanvelzen. All rights reserved. |


Open Parking is a web-visualisation of parking data in the Netherlands. Cities, private companies and other interested parties can easily find out which city provides the best data and which cities/facilities are lacking in that department. With this web-visualisation, we can also show the many uses of open data. The user will be able to easily check real-time data about parking facilities all over the Netherlands and search for the data of specific parking facilities.
Get Started!Open Parking is a project made by a team of 4 students during Open Summer of Code 2018.


Notable changes
Changed
Added
- Expose parameter status messages (GUC_REPORT) to the user PR 1435
- Add automatic module name to manifest for jdk9+ PR 1538
- Log ignoring rollback when no transaction in progress PR 1549
- Map inet type to InetAddress PR 1527 issue 1134
Fixed
- fix issue 1547 As long as peek returns some bytes do not reset the timeout, this allows us to continue checking until any async notifies are consumed PR 1548
- fix: issue 1466 In logical decoding the if the backend was requesting a reply we… PR 1467
- fix: issue 1534 Proleptic java.time support PR 1539
- fix Ensure isValid() will not last more than timeout seconds PR 1557
Commits by author
Adrien (1):
- Ensure isValid() will not last more than timeout seconds PR 1557 b2eaefe
Craig Ringer (2):
- Expose parameter status messages (GUC_REPORT) to the user PR 1435 ce8333a
- Make ConnectTimeout test accept NoRouteToHostException PR 1526 08d8129
Dave Cramer (8):
- note that waffle 1.9.x is only supported in jre8 version Update README to point to new maven coordinates 58804e9
- add automatic module name to manifest for jdk9+ PR 1538 0600990
- fix issue 1547, as long as peek returns some bytes do not reset the timeout, this allows us to continue checking until any async notifies are consumed PR 1548 36a75cb
- fix: In logical decoding the if the backend was requesting a reply we… PR 1467 f89e62c
- Log ignoring rollback when no transaction in progress PR 1549 bda74d7
- fix assertion message PR 1553 ba82948
- remove failing tests for PostgreSQL version 8.3 add in tests for 11 89464a5
- Fix travis parsing issue 634ac7d
Hajar Razip (2):
- docs: add note on behavior of ResultSet.getString() PR 1286 (#1528) c30556c
- docs: update resultset.md in head to reflect 94 PR 1528 (#1536) fc8efc9
Matteo Melli (1):
Myo Wai Thant (1):
Pavel Raiskup (2):
- fix parent version in pgjdbc/pom.xml as well 3db55da
- rpm: remove karaf plugin 8495127
Philippe Marschall (1):
Sehrope Sarkuni (2):
Steinar Bang (1):
- Add an apache karaf feature for the PostgreSQL JDBC driver to fix PR 1552 (#1554) e2f6e9f
Tim Ward (1):
- Check that JDBC Connections that are closed by the server do not report as valid PR 1533 56399ef
Vsevolod Kaimashnikov (1):
Contributors to this release
We thank the following people for their contributions to this release.
Adrien
Craig Ringer
Dave Cramer
Hajar Razip
Matteo Melli
Myo Wai Thant
Pavel Raiskup
Philippe Marschall
Sehrope Sarkuni
Steinar Bang
Tim Ward
Vsevolod Kaimashnikov


My Cart Your cart is currently empty. Product Item Price Quantity Remove Price Uncaged 03 Embroidered Patch $10.00 X $10.00 Subtotal: $10.00 Check Out


Home
All Recipes
Team
Most Viable Potato
Recipes based on the ingredients selected:
Ingredients
Please select up to 10 ingredients you would like from the dropdown:
Choose ingredient
Remove Items!


Cape Coral police arrest woman for driving under the influence with 9-year-old in the car
by WFTX Digital TeamCAPE CORAL, Fla. — Cape Coral police arrested a woman for driving under the influence with a 9-year-old in the front passenger seat.
Police say Amie Hancock, 36, of Cape Coral was stopped for speeding and failing to maintain a single lane at the 700 block of Veterans Memorial Parkway West. Upon contact Hancock showed signs of impairment, and a DUI investigation ensued. She performed poorly on the field sobriety exercises and was arrested.
Hancock is facing charges for driving under the influence and driving under the influence with passenger under 18 years of age.


{% extends "_post.html" %}
{% hyde
title: "Clam"
snip: "A Vim plugin for working with shell commands."
created: 2012-04-07 20:00:01
exclude: False
%}
{% block article %}
[Clam][] is a small, lightweight Vim plugin for working with shell commands more
easily.
It's open source (MIT/X11 licensed) on [BitBucket][] and [GitHub][].
[Clam]: http://vim-doc.heroku.com/view?https://raw.github.com/sjl/clam.vim/master/doc/clam.txt
[BitBucket]: http://bitbucket.org/sjl/clam.vim/
[GitHub]: http://github.com/sjl/clam.vim/
{% endblock %}


Week 6 - Stereotype Threat
Anyone can find reasons to feel the "stereotype threat", because everybody has weak spots, defects, past mistakes, lots of failures and weird physical attributes. The moment we are living in society, we are facing the reaction of others to our imperfections.
It seems to me that "stereotype threat" is another way to call "insecurity" or "inferiority complex", and I think that the antidote for that is character building: to understand that you are always going to find obstacles in your way, that the only way to overcome them is trying again and again with creativity and perseverance, and that character is built with the sum of little and big achievements.
The inferiority complex is cured when you realize that there are not superior people, but people with a similar number of defects than you that have found the formula to build character.


Strategic corporate finance advice
Helping your business make the right move
We bring our expertise to help entrepreneurial businesses achieve their strategic objectives
We are an independent advisory firm, focussed on successful growing businesses
We provide strategic financial advice and manage transactions for a range of entrepreneurial companies and investors both in the UK and internationally.
How we can help you
Sell Side advisory
Unlock shareholder value
- Optimisation of exit strategy
- Buyer search and evaluation
- Company valuation
- Project management and negotiation
Buy Side advisory
Support growth strategy
- Research potential targets
- Evaluate against return criteria
- Target valuation
- Effective negotiation and execution
Financing structure
Optimise capital structure
- Develop financing strategy
- Evaluate funding options
- Capital raise advice and support
CFO and NED Services
Enhance Board capabilities
- Part time cost effective support
- Financial overview and improvement
- Strategic advice
- Focus on value creation
Sell Side advisory
Unlock shareholder value
- Optimisation of exit strategy
- Buyer search and evaluation
- Company valuation
- Project management and negotiation
Buy Side advisory
Support growth strategy
- Research potential targets
- Evaluate against return criteria
- Target valuation
- Effective negotiation and execution
Financing structure
Optimise capital structure
- Develop financing strategy
- Evaluate funding options
- Capital raise advice and support
CFO and NED Services
Enhance Board capabilities
- Part time cost effective support
- Financial overview and improvement
- Strategic advice
- Focus on value creation
Our achievements
£4.5bn
of completed M&A deals
£3.6bn
of successful capital raising
How we work
Paragraph of text beneath the heading to explain the heading. We'll add onto it with another sentence
and probably just keep going until we run out of words.
Complete independence of view
Focussed on your needs not on the sale of financial products.
Dedicated senior level input throughout
With much closer hands on involvement than traditional advisory model.
Flexible remuneration structure
Aligned with your interests.
Our leadership
35+
years of corporate finance experience
15+
years working in international investment banking
Chantry is wholly owned by Managing Director, David Blake FCA. David is a highly experienced corporate finance professional and company director with a broad based industry and international experience.
In his career, David has assisted many private businesses and public companies in achieving their strategic objectives. His expertise in Corporate Finance spans a broad spectrum of transactions and industry sectors, both in the UK and overseas.
Case studies
Derrick Offshore
Advised the shareholders of the leading international broker of offshore support vessels in the sale of their business to Pareto JGO Shipbrokers from Norway.
Derrick Offshore
Advised the shareholders of the leading international broker of offshore support vessels in the sale of their business to Pareto JGO Shipbrokers from Norway
£4.5bn
of completed M&A deals£3.6bn
of successful capital raisingParagraph of text beneath the heading to explain the heading. We'll add onto it with another sentence and probably just keep going until we run out of words.
Complete independence of view
Focussed on your needs not on the sale of financial products.
Dedicated senior level input throughout
With much closer hands on involvement than traditional advisory model.
Flexible remuneration structure
Aligned with your interests.
Our leadership
35+
years of corporate finance experience
15+
years working in international investment banking
Chantry is wholly owned by Managing Director, David Blake FCA. David is a highly experienced corporate finance professional and company director with a broad based industry and international experience.
In his career, David has assisted many private businesses and public companies in achieving their strategic objectives. His expertise in Corporate Finance spans a broad spectrum of transactions and industry sectors, both in the UK and overseas.
Case studies
Derrick Offshore
Advised the shareholders of the leading international broker of offshore support vessels in the sale of their business to Pareto JGO Shipbrokers from Norway.
Derrick Offshore
Advised the shareholders of the leading international broker of offshore support vessels in the sale of their business to Pareto JGO Shipbrokers from Norway
35+
15+
Chantry is wholly owned by Managing Director, David Blake FCA. David is a highly experienced corporate finance professional and company director with a broad based industry and international experience.
In his career, David has assisted many private businesses and public companies in achieving their strategic objectives. His expertise in Corporate Finance spans a broad spectrum of transactions and industry sectors, both in the UK and overseas.
Derrick Offshore
Advised the shareholders of the leading international broker of offshore support vessels in the sale of their business to Pareto JGO Shipbrokers from Norway.
Derrick Offshore
Advised the shareholders of the leading international broker of offshore support vessels in the sale of their business to Pareto JGO Shipbrokers from Norway


27
Biography
Feb. 9, 1909 - Born in Massena, St. Lawrence, New York, USA
Apr. 15, 1910 - age 1, living on Maple St. in Massena, NY in home of grandfather Henry Reed with grand parents, parents and two aunts. .....(1)
Jun. 1915 - age 6, living with parents on Main St. in Massena, NY. .....(2)
Jun. 1925 - age 16, living with parents on Main St. in Massena, NY. .....(3)
Apr. 1930 - age 21, living with parents at 35 East Orvis St. in Massena, NY. and working as rodman at Alcoa aluminum plant. .....(4)(5)
1933 - age 34, living with parents at 35 East Orvis St. in Massena, NY. .....(6)
Apr. 1940 - age 31, living with parents at 35 East Orvis St. in Massena, NY. and working as teller in State Bank with annual salary of $1,800. .....(7)
Oct. 9 1943 - age 34, enlisted in U.S. Army. Served in The Phillipines during WWII. Released from service - 16 Dec. 1945.
1963 - age 52, member of school board in Massena, NY. .....(8)
1967 - 1977 - served as president of Massena Savings & Loan Assn. .....(9)
Jun 21, 1991 - age 82, died in hospital in Syracuse NY. after suffering heart attack at his home at 12 Prospect Ave. in Massena, NY. Buried in Old Pine Grove Cemetery in Massena, NY. .....(10)(11)
Links
(1) Census US 1910 - Massena, New York
(2) Census NY 1915 - Massena, New York
(3) Census NY 1925 - Massena, New York
(4) Census US 1930 - Massena New York
(5) Directory City Massena 1930
(6) Directory City Massena 1933
(7) Census US 1940 - Massena New York
(8) Massena School Board Photo 1963
(9) History Massena Savings and Loan
Family


Welcome to Ambiance Music
Enter name to access your account
Go
Proceed to The Ambiance,Mood Based Music