Coding conventions and C++-style



Similar documents
Moving from CS 61A Scheme to CS 61B Java

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Thyra Coding and Documentation Guidelines (TCDG) Version 1.0

Object Oriented Software Design II

Applied Informatics C++ Coding Style Guide

C++ INTERVIEW QUESTIONS

An Incomplete C++ Primer. University of Wyoming MA 5310

Computer Programming C++ Classes and Objects 15 th Lecture

C++ Programming Language

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

C++ Overloading, Constructors, Assignment operator

ECE 341 Coding Standard

Variable Base Interface

C Coding Style Guide. Technotes, HowTo Series. 1 About the C# Coding Style Guide. 2 File Organization. Version 0.3. Contents

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

The Universal Reference/Overloading Collision Conundruim

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Some Scanner Class Methods

Dinopolis Java Coding Convention

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

1 Abstract Data Types Information Hiding

Why you shouldn't use set (and what you should use instead) Matt Austern

Glossary of Object Oriented Terms

Coding Standard for Java

Install Java Development Kit (JDK) 1.8

Taxi Service Coding Policy. Version 1.2

CORBA Programming with TAOX11. The C++11 CORBA Implementation

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

The C Programming Language course syllabus associate level

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

VB.NET Programming Fundamentals

IVI Configuration Store

Visual C Tutorial

MSP430 C/C++ CODE GENERATION TOOLS Compiler Version 3.2.X Parser Error/Warning/Remark List

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Intel TSX (Transactional Synchronization Extensions) Mike Dai Wang and Mihai Burcea

Comp151. Definitions & Declarations

Vim, Emacs, and JUnit Testing. Audience: Students in CS 331 Written by: Kathleen Lockhart, CS Tutor

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

C++ Language Tutorial

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

N3458: Simple Database Integration in C++11

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Binary compatibility for library developers. Thiago Macieira, Qt Core Maintainer LinuxCon North America, New Orleans, Sept. 2013

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector {

Java Interview Questions and Answers

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

PL / SQL Basics. Chapter 3

A deeper look at Inline functions

CODING STANDARDS AND GUIDELINES

Binary storage of graphs and related data

CRM Setup Factory Installer V 3.0 Developers Guide

Sources: On the Web: Slides will be available on:

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

C++FA 3.1 OPTIMIZING C++

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

Java Program Coding Standards Programming for Information Technology

Note: Syntactically, a ; is needed at the end of a struct definition.

Goals for This Lecture:

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

The GenomeTools Developer s Guide

EP241 Computer Programming

CSI33 Data Structures

OpenCL Static C++ Kernel Language Extension

El Dorado Union High School District Educational Services

Hands-on Exercise 1: VBA Coding Basics

UML for C# Modeling Basics

C++ for Safety-Critical Systems. DI Günter Obiltschnig Applied Informatics Software Engineering GmbH

Coding Conventions for C++ and Java applications

Official Android Coding Style Conventions

Bridging Python to C++ - and vice-versa

C Compiler Targeting the Java Virtual Machine

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Symbian OS C++ coding standards

sqlite driver manual

C++ Crash Kurs. C++ Object-Oriented Programming

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Parallel and Distributed Computing Programming Assignment 1

Moving from C++ to VBA

1 Using CWEB with Microsoft Visual C++ CWEB INTRODUCTION 1

General Software Development Standards and Guidelines Version 3.5

URI and UUID. Identifying things on the Web.

Introduction to Data Structures

Object Oriented Software Design II

Code convention document Argus-viewer

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Volume I, Section 4 Table of Contents

The programming language C. sws1 1

Reading and Writing PCD Files The PCD File Format The Grabber Interface Writing a Custom Grabber PCL :: I/O. Suat Gedikli, Nico Blodow

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Input Output. 9.1 Why an IO Module is Needed? Chapter 9

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Transcription:

Chapter 1 Coding conventions and C++-style This document provides an overview of the general coding conventions that are used throughout oomph-lib. Knowledge of these conventions will greatly facilitate the use of the library. Contributors to the library are expected to adhere to these standards. 1.1 Naming conventions 1.1.1 File names All C++ source files end with the standard extensions.h and.cc..h: Contains the class definitions and any inline functions..cc: Contains all non-inline member functions that can be compiled once and for all. This includes member functions of classes that do not have any template parameters member functions of templated classes for which it is known a priori which instantiations are required. Examples are classes that are templated by the spatial dimension. In this case we re unlikely to require instantiations for any values other than 0,1,2 and 3..template.cc: Contains any non-inline member function of templated classes. This file must be included (together with the corresponding.h file) when a specific instantiation of a templated class is required. For instance, most specific Mesh classes are templated by the element type and the mesh writer can obviously not predict which element types his/her specific mesh is going to be used with. 1.1.2 General variables General variables are all lowercase Variables that contain multiple words contain underscores to separate them, e.g. FiniteElement* surface_element_pt; 1.1.3 Classes Classes start with capital letter, e.g.

2 Coding conventions and C++-style class Shape If the class name contains multiple words, the first letter of any subsequent word also gets capitalised, e.g. class AlgebraicElement Note: No underscores in class names. 1.1.4 Private data and access functions to private data Use a capital first letter for private data, and the all-lowercase equivalent for the access functions. Examples: This is a declaration for a private data member: private: /// Pointer to boundary node Node* Boundary_node_pt; Here are two public access functions to the private data member: public: /// Access to boundary node (const version) Node* boundary_node_pt() const return Boundary_node_pt; /// Access to boundary node Node*& boundary_node_pt() return Boundary_node_pt; Note: Do not use public data ever! Make it private and and provide an access function even if it seems "perfectly obvious" at the time of writing the class that the internal storage for the data item is "never going to be changed". 1.1.5 Pointers Pointers and access functions to pointers are identified explicitly by the postfix _pt to the variable names, as shown in the previous examples. 1.1.6 Access functions to containers Many classes have member functions that provide access to data in private containers (e.g. vectors); they are usally accompanied by a member function that returns the number of entries in that container. Naming conventions: Use singular for the access function to the container, i.e. /// Return pointer to e-th element FiniteElement* element_pt(const unsigned& e); rather than elements_pt(...)

1.2 Layout etc. 3 Use a prefix n for the access function for the number of entries in the container, i.e. /// Total number of elements unsigned nelement(); Notes: (i) No underscore betweeen the "n" and the container s name. (ii) No trailing _pt in the function that returns the number of objects in the container. 1.1.7 Template parameters Template parameters are all caps, e.g. template<unsigned DIM> class NavierStokesEquations public: [...] ; 1.1.8 Use descriptive function/variable names Make sure you choose descriptive names for functions and variables, even if the names become long. 1.2 Layout etc. 1.2.1 Position of include statements Place include statements at the beginning of each file. 1.2.2 Layout of blocks Braces on separate lines (unless the content is extremely short) for (unsigned i=0;i<10;i++) [...] std::cout << "doing something" << std::endl; [...] 1.2.3 Indentation Indentation of blocks etc. should follow the emacs standards.

4 Coding conventions and C++-style 1.2.4 Layout of functions, classes, etc. Precede all functions by a comment block, enclosed between lines of === // ============================================================= /// \short (add \short to make sure that multi-line descriptions /// appear in doxygen s short documentation. Include lists with items /// - first item /// - second item /// - first item of sublist /// - second item of sublist ///. //end of sublist ///. //end of main list // ============================================================= void SomeClass::some_function() for (unsigned i=0;i<10;i++) std::cout << "doing something" << std::endl; Note the triple slash "///" in the comment block that preceeds the function definition comments contained in such lines are automatically extracted by doxygen and inserted into the code documentation. 1.2.5 The oomph-lib namespace oomph-lib is contained in its own namespace, oomph, to avoid clashes of class names with those of other (third-party) libraries. If there is no danger of name clashes, the entire oomph namespace may be imported at the beginning of each driver code by placing the statement using namespace oomph; at the beginning of the source code (after the included header files). Any additions to the library (this includes the instantiation of templated oomph-lib classes inside a driver code!) must be included into the oomph namespace by surrounding the code by namespace oomph // Additions to the library go here... [...] 1.2.6 Namespace pollution To avoid namespace pollution, the namespace std must not be included globally in any header files. The statement using namespace std; may only be used in driver codes, in.cc files, or inside specific functions in a.h file.

1.2 Layout etc. 5 1.2.7 Layout of class definitions and include guards. Here is an example of a complete header file, including include guards and library includes. #ifndef OOMPH_SOME_CLASS_HEADER #define OOMPH_SOME_CLASS_HEADER // Assuming that the file is // called some_class.h // Include generic oomph-lib library #include "generic.h" // Add to oomph-lib namespace namespace oomph // ============================================================= /// Waffle about what the class does etc. /// // ============================================================= template<class T> class SomeClass : public SomeBaseClass public: /// Constructor: Pass coefficients n1 and n2 SomeClass(const unsigned& n1, const T& n2) : N1(n1), N2(n2) /// Access function to coefficient inline unsigned n1() const return N1; /// Access function to other coefficient inline T& n2() const return N2; ; protected: /// Coefficient unsigned N1; private: #endif /// Second coefficient T N2; Order of public/protected/private may be reversed but the declarations should always be explicit (even though everything is private by default). Note the prefix OOMPH_ in the include guard. This is to avoid clashes with include guards of other libraries.

6 Coding conventions and C++-style 1.3 Debugging etc. 1.3.1 The PARANOID flag and error handling Implement optional validation routines, self-tests, and other sanity checks via conditional compilation, using the compiler flag PARANOID, so that the relevant statements are only activated if -DPARANOID is specified as a compilation flag for the C++ compiler. If errors are detected, a meaningful diagnostic should be issued, by throwing an OomphLibError. If the code is compiled without the PARANOID flag, all sanity checks are bypassed good for the overall execution speed, bad for error handling... The user can choose. Here s an example: //Has a global mesh already been built? if(mesh_pt!=0) std::string error_message = "Problem::build_global_mesh() called,\n"; error_message += " but a global mesh has already been built:\n"; error_message += "Problem::Mesh_pt is not zero!\n"; throw OomphLibError(error_message, "Problem::build_global_mesh()", OOMPH_EXCEPTION_LOCATION); oomph-lib also has an object that allows warning messages to be issued in a uniform format. Here s an example of its use: // Was it a duplicate? unsigned nel_now=element_set_pt.size(); if (nel_now==nel_before) std::ostringstream warning_stream; warning_stream <<"WARNING: " << std::endl <<"Element " << e << " in submesh " << imesh <<" is a duplicate \n and was ignored when assembling " <<"global mesh." << std::endl; OomphLibWarning(warning_stream.str(), "Problem::rebuild_global_mesh()", OOMPH_EXCEPTION_LOCATION); 1.3.2 Range checking Most access functions that provide indexed access to a private container, do, in fact, access a private STL vector. Explicit range checking for these (frequent!) cases can be avoided by changing to container to Vector class instead. Vectors performs automatic range checking, if the generic library is compiled with the RANGE_CHECKING flag, i.e. if -DRANGE_CHECKING is specified as a compilation flag for the C++ compiler. Note: While it is generally a good idea to compile with PARANOID while developing code, RANGE_CHECKING is very expensive and is therefore activated via a second independent flag. We only tend to active this flag as a last resort, typically to track down particularly stubborn segmentation faults. 1.3.3 Self test routines Every sufficiently complex class should come with its own

1.4 Other conventions 7 unsigned self_test() routine which returns 1 for failure, 0 for successful test. 1.4 Other conventions 1.4.1 Const-ness Use const whereever applicable (arguments, member functions,...) Always provide const and non-const overloaded subscript operators. Example: // Return i-th coordinate of Point double& operator[](const unsigned& i)return x[i]; // Return i-th coordinate of Point -- const version const double& operator[](const unsigned& i) const return x[i]; 1.4.2 Only use int if a variable can actually take negative values Just as the name of a variable gives some indication of its likely use, its type does too. For instance this code fragment // Create a counter int counter=0; immediately raises the question why the programmer anticipates circumstances in which the counter might be negative. Are negative values used to indicate special cases; etc? If the name of the variable was chosen correctly (i.e. if the variable really is used as a counter) then // Create a counter unsigned counter=0; is much clearer and therefore preferable, even if the two versions of the code would, of course, give the same result. 1.4.3 Only use "pass by reference" Arguments to functions should only be passed "by reference", not "by value". Use "pass by constant reference" if you want to ensure the const-ness of any (input) arguments. To "encourage" this behaviour, most oomph-lib objects have (deliberately) broken copy constructors and assignment operators, making a "pass by value" impossible. The only exceptions are cases in which we could see a good reason why a fully-functional, non-memory-leaking copy/assignment operator might be required.

8 Coding conventions and C++-style 1.4.4 Provide fully-functional or deliberately-broken copy constructors and assignment operators For the reasons mentioned above, "passing by value" is discouraged and we have only implemented copy constructors for very few classes. To make the use of C++ s default copy constructor impossible (as their accidental use may lead to serious memory leaks) all classes should either have a deliberately-broken copy constructor or provide a "proper" implementation (as in the case of oomph-lib s Vector class). The same applies to assignment operators. The namespace BrokenCopy provides two helper functions, BrokenCopy::broken_copy(...) and BrokenCopy::broken_assign(...) that issue a suitable error message and then throw an OomphLibError. The name of the class should be passed to these functions as a string, as in this example from the Mesh class: /// Broken copy constructor Mesh(const Mesh& dummy) BrokenCopy::broken_copy("Mesh"); /// Broken assignment operator void operator=(const Mesh&) BrokenCopy::broken_assign("Mesh"); 1.4.5 Order of arguments If values are returned from a function, put them at the end of the argument list. "Time" arguments always come first, e.g. /// \short Return FE interpolated coordinate x[i] at local coordinate s /// at previous timestep t (t=0: present; t>0: previous timestep) virtual double interpolated_x(const unsigned& t, const Vector<double> &s, const unsigned &i) const; 1.4.6 Access to elements in containers Avoid access via square brackets (i.e. via operators) and write access functions instead, as they can be overloaded more easily. 1.4.7 Macros Don t use macros! There is a single exception to this rule: We use the macro OOMPH_- EXCEPTION_LOCATION to make the file name and line number available to the OomphLib- Exception object the object that is thrown if a run-time error is detected. 1.4.8 Inlining Inline all simple set/get functions by placing them into the.h file. Careful: Inlined functions should not contain calls to member functions of classes that are defined in other files as this can lead to triangular dependencies.

1.5 PDF file 9 1.5 PDF file A pdf version of this document is available.