1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
|
Coding rules
============
Packages
--------
In order to structure the code of the project, the various elements
(classes, functions, libraries, data) are logically organized in
packages. This chapter describes the rules to be followed for the
definition, management and use of these packages.
| The code is mainly located in a single library. This library is
organized as a set of modules. However, there may be several
interacting libraries in the future.
| The library is interfaced with Python through a Python module
exposing almost all the classes and operators.
For the moment, the entire set of classes is located in **libOT.so** for
the dynamic part and in **libOT.a** for the static part.
Example showing the import of modules via the **openturns** Python
package:
::
import openturns
import openturns.base
import openturns.uncertainty
Example showing the direct import of module operators or classes via
the **openturns** Python package:
::
from openturns import Point
from openturns.base import Sample
from openturns.uncertainty import RandomVector
File names
----------
The definition of filenames obeys a few rules described below, according
to the programming languages used. A general rule is preliminarily
defined in order to facilitate the automatic generation of the
**Makefile** files. The file names consist of sequences of characters
separated by a dot. The first part of the name is called the *base* and
the second is called the *suffix* (or *extension*).
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **Extension** | **Description** |
+=====================+===========================================================================================================+
| **.hxx .hh .hpp** | Header file containing the declaration of functions and classes and the definition of templates for C++ |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.cxx .cc .cpp** | Source code file containing the definition (implementation) of C++ functions and classes |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.c** | Source code file containing the definition of C functions |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.h** | Header file containing the declaration of functions in C |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.py** | Python file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.R** | R file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.cmake** | CMake script |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.sh** | Shell script |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.bat** | DOS script |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.conf** | configuration file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.csv** | Comma Separated Value file (for samples) |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.i** | SWIG interface file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.in** | Template file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.log** | Output log file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.mws** | Maple script file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.nsi** | Windows installer file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.sce** | Scilab script file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.a** | Archive file containing statically linked objects |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.so** | Shared object file containing dynamically linked objects |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.txt** | Text file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.xml** | XML file (mainly for wrapper description file) |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.ll** | Lex scanner file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
| **.yy** | Yacc parser file |
+---------------------+-----------------------------------------------------------------------------------------------------------+
For example, it is not recommended to give the following names to two
files in the same directory:
::
matrix.cxx
Matrix.cxx
C++ Files
~~~~~~~~~
Example: one file per class:
::
Sample.hxx declares class Sample
Matrix.hxx declares class Matrix
...
Incorrect example: one file for all classes of a model:
::
Model.hxx # contains all the declaration of all the classes of the internal model
The preceding rule has one exception: in order to facilitate the use of
several related classes, the header files belonging to the same module
are grouped in a single header file, which bears the same name as the
module and is prefixed by **OT**.
Example: using all the classes of the Base module:
::
#include "openturns/OTBase.hxx"
Header files
~~~~~~~~~~~~
The header files are used to declare functions and classes (they are
sometimes called *interface definition* or *interface specification*).
Example for a file named **Sample.hxx**:
::
#ifndef OPENTURNS_SAMPLE_HXX
#define OPENTURNS_SAMPLE_HXX
...
#endif /* OPENTURNS_SAMPLE_HXX */
Example of header file inclusion:
::
#include "openturns/OSS.hxx"
#include "openturns/Point.hxx"
Example for the inclusion of system function or external library header
files:
::
#include <cstring>
#include <boost/python.hpp>
Example for the inclusion of non standard system function header files:
::
extern "C" (
#include <nonstandard.h>
)
Test files
~~~~~~~~~~
Example of names for test files:
::
t_Matrix_construction.cxx
t_Matrix_assignment.cxx
t_Matrix_bug7654.cxx
t_Matrix_vectorMultiplication.cxx
C++
---
This section deals with coding rules for the C++ language.
Compilation flags
~~~~~~~~~~~~~~~~~
It is helpful to enable some compilation warnings to avoid questionable constructions.
You may also want to enable debug symbols for further use with a debugger.
GCC compilation:
::
mkdir -p build && cd build
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_CXX_FLAGS="-Wall -Wextra -D_GLIBCXX_ASSERTIONS" ..
make
Namespaces
~~~~~~~~~~
Example of **OpenTURNS** namespace definition for simple types:
::
/ **
* @file OTtypes.hxx
* ...
* /
namespace OT
{
/* < Declarations of simple types > * /
/* < Declarations of objects and functions > * /
};
// Alias for the direct use of XXX
namespace OpenTURNS = OT;
Example of use by making all the definitions contained in the namespace
available:
::
#include "openturns/OT.hxx"
using namespace OT;
void f(Scalar n);
Names
~~~~~
Names of classes, variables and methods consist of concatenated ful words.
Each word begins with an uppercase, except for the first one.
The first word begins with a lowercase except for class names and static methods or variables.
No abbreviations are allowed, except if it is found in the literature, for example FORM.
Example:
::
class Sample {
...
}; /* end class Sample */
Example:
::
int main() {
Bool myCondition = false;
...
}
Example:
::
class Environment : public Object {
...
private:
Scalar density_; //<! material density in environment (g/cm3)
...
}; /* end class Environment */
NB: It is common for the underscore to be used as a prefix for private
attribute names. However, this method may trigger conflicts with
internal variables or definitions used by the compilers. For this
reason, the underscore is used as a suffix.
Example:
::
class Object {
...
private:
static String ClassName_;
...
}; /* end class Object */
Example:
::
class Object
{
public:
//* returns a class identifier based on its name
static String GetClassName(); ...
}; /* end class Object */
Example:
::
int
initializeConversion()
{
static Bool IsInitialized = false;
if (! IsInitialized) {
...
IsInitialized = true;
}
};
Example:
::
const UnsignedInteger MaximumOfRetries = 5;
Example:
::
int main()
{
Scalar reactionRate = 0.0;
...
}
Example:
::
class Sample
{
UnsignedInteger getDimension () const;
...
}; /* end class Sample */
Example:
::
class Sample {
}; /* end class Sample */
void removeElement(const UnsignedInteger index);
Point meanValue;
Example of tolerated notations:
::
UnsignedInteger i; // loop indices i, j and k are common
UnsignedInteger j;
UnsignedInteger k;
UnsignedInteger nbMaxElements; // usual abbreviations: nb, Max
void
addPoint(Point pt) { // no confusion in the context
add(pt);
}
Incorrect examples:
::
Scalar a, k, l, m1, m2, m3;
Scalar zzz, zz2;
const char *foo, *hello, tempo, bogus;
void adElt(Point pt);
UnsignedInteger numSmplPt;
Class declaration
~~~~~~~~~~~~~~~~~
Example:
::
class Buffer {
public :
static AThing GetThing();
protected:
private :
static AThing TheThing_;
public :
Scalar getValue() const;
protected :
Scalar theValue_;
private :
/* ... */
}; /* end class Buffer */
Example:
::
class AnyClass {
public :
/** Default constructor */
AnyClass();
/** Copy constructor */
AnyClass(const AnyClass & other);
/** Destructor */
virtual ~AnyClass();
/** Copy operator */
AnyClass& operator = (const AnyClass & other);
/** Comparison operator */
Bool operator == (const AnyClass & other) const;
/** Stream converter */
String repr() const;
String str() const;
/* other public methods ... */
private :
UnsignedInteger size_;
DataType * data_;
/* other private methods ... */
}; /* end class AnyClass */
Example:
::
class AnyClass {
public :
/* ... */
private :
UnsignedInteger size_;
DataType * data_;
}; /* end class AnyClass */
Example:
::
class Vector {
public :
Vector (Bool someProperty, UnsignedInteger size, Scalar elt = 0.);
private :
Bool property_;
Collection<Scalar> data_;
};
Example of a correct definition:
::
Vector::Vector (Bool someProperty, UnsignedInteger size, Scalar elt)
: property_(someProperty)
, data_(size, elt)
{ }
Examples of incorrect definitions:
::
Vector::Vector (Bool someProperty, UnsignedInteger size, Scalar elt)
: data_(size, elt)
, property_(someProperty) // order of initialization
{ }
Vector::Vector (Bool someProperty, UnsignedInteger size, Scalar elt)
{
property_ = someProperty;
data_ = Collection<Scalar>(size, elt);
// requires an assignment after the construction
// processing is longer for complex objects!
}
Example: declaration of a pure virtual class A and of class B, derived
from A:
::
class A {
public :
A(); // constructor
virtual ~A(); // destructor
virtual const char * getClassName() = 0; // pure virtual method
};
class B : public A {
public :
const char * getClassName() { return "B"; }
};
Incorrect definitions leading to an execution error:
::
A::A() {
cout << getClassName() << " created" << endl; // B does not exist yet!
}
A::~A() {
cout << getClassName() << " destroyed" << endl; // B no longer exists!
}
B::B() : A()
{ }
Write method for the **name** attribute:
::
void setName (SimpleType);
void setName (const ComposedType &);
Read method for the **name** attribute:
::
SimpleType getName() const;
const ComposedType & getName() const;
Example:
::
class Sample {
public :
//* return the dimension of the sample
UnsignedInteger getDimension() const;
//* return the i-th element
Point operator[] (UnsignedInteger i);
const Point & operator[] (UnsignedInteger i) const;
};
Example:
::
class Sample {
public :
//* return the number of the rod
inline UnsignedInteger getDimension() const { return dimension_; }
//* compute the mean point of the sample
inline Point computeMeanValue() const;
};
//* inline methods
Point computeMeanValue() const;
{
/* ... some non trivial processing */
return meanValue;
}
Explicit keyword
~~~~~~~~~~~~~~~~
Marking a single argument class constructors with the *explicit* keyword
allows one to avoid unwanted conversions.
It is relevant for constructors that have a single-argument, and also for
constructors that have a single mandatory argument plus optional arguments.
Single argument:
::
class A {
public :
explicit A(const Point value);
};
Optional argument:
::
class A {
public :
explicit A(UnsignedInteger max = 6);
};
Mandatory argument and optional argument:
::
class A {
public :
explicit A(const Point value, UnsignedInteger max = 6);
};
Inheritance
~~~~~~~~~~~
Example: the Point class derives from the Vector class:
::
class Point : public std::vector<double> {
public:
Point(Scalar x,
Scalar y,
Scalar z);
};
Point::Point(Scalar x, Scalar y,
Scalar z)
: std::vector<double>(3)
{
(*this)[0] = x;
(*this)[1] = y;
(*this)[2] = z;
}
Example:
::
class Object {
public :
Object();
virtual ~Object();
};
Function and method declaration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::
/** @brief <short description>
*
* <Long description>
* @param argument_1 <description>
* @param argument_2 <description>
* @return <description>
* @throw <description>
*/
ReturnType
functionName (
TypeArgument_1 argument_1,
TypeArgument_2 argument_2
);
Correct example:Correct
::
void send(const String & message);
Incorrect example:
::
void send(String message);
Correct example:
::
Buffer & append(UnsignedInteger);
Buffer & append(const String &);
Buffer & append(Scalar);
Incorrect example:
::
Buffer & append(const char *fmt, ...);
Buffer & append(const char *str = 0, double d = 0., int i = 0);
Variable declaration
~~~~~~~~~~~~~~~~~~~~
An atomic variable type (integer, bool, pointer, ...) must be always
initialized to a value to avoid undefined behavior.
This includes initialization of class attributes.
Correct example:
::
String filename (""); // library file name
UnsignedInteger nbElements = 0; // number of elements into the data file
UnsignedInteger i = 0;
Scalar f = 0.0;
Accepted example:
::
UnsignedInteger i = 0, j = 0, k = 0; // indices
Incorrect example:
::
/ * Multiple declarations and different types * /
UnsignedInteger i, j, tab[20], **l, *numberOfElements;
String filename, *yourname, myname;
Constant declaration
~~~~~~~~~~~~~~~~~~~~
The const keyword must be used as much as possible.
Float constants must include the decimal separator and a at least a digit to
explicitly distinguish them from integers.
Example:
::
const Scalar f = 6.0;
const UnsignedInteger maximumIterations = 32;
const char printFormat[] = "%s:line %d, %s";
Incorrect example:
::
#define MAXIMUM_ITERATIONS 32;
#define PRINT_FORMAT "%s:line %d, %s"
Comments and internal documentation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::
/**
* @brief short description
*
* <LGPL copyright>
*
* Copyright 2005-20YY Airbus-EDF-IMACS-ONERA-Phimeca
*/
These comments should avoid:
- mentioning the names of variables;
- being a simple transcription of the code into English.
Memory allocation and deallocation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This section discusses general rules for allocating and freeing memory.
It will later be supplemented by rules regarding the use of basic
classes in order to manage the lifecycle of objects in memory.
Example to favor:
::
{
Scalar sections1[MAX]; // a fixed size array
vector<Scalar> sections2; // an extensible vector
list<Volume> volumes; // a list of volumes
/* ... */
}
Example to avoid:
::
{
Scalar *sections = new Scalar[MAX];
list<Volume> *volumes = new list<Volume>;
/* ... */
delete [ ] sections;
delete volumes;
}
Correct example:
::
{
Volume *volume = new Volume; // memory allocation +
// constructor call
/* ... */
delete volume; // destructor call +
volume = 0; // memory deallocation
}
Incorrect example:
::
{
Volume *volume = (Volume*)malloc(sizeof(Volume));
// memory allocation but
// no constructor call
/* ... */
free(volume); // no destructor call before
volume = 0; // memory deallocation
}
Example:
::
A * a = new A[40]; // calls the constructor 40 times
...
::
delete a; // incorrect: the table is freed,
// the ~A destructor isn't called
::
delete [] a; // correct: the table is freed,
// the ~A destructor is called 40 times
List of declaration files for the smart pointer:
::
#include "openturns/Pointer.hxx"
Assignment and initialization
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Complex types (class types) must use copy constructors if available instead of
using the default constructor and then the copy operator for performance.
Atomic types (integer, bool, ...) can use the copy operator for readability.
Example:
::
Point p2(p1);
Bool a = b;
Example to avoid:
::
String message;
message = "Computation complete"; // assignment after construction
String message(); // declaration of a function prorotype
Instructions
~~~~~~~~~~~~
Example:
::
i = 0;
while (i < MAX) {
++i;
f(i);
}
Examples to avoid if possible:
::
a = b = c = 0;
// multiple assignments
f(++i);
// readability
v = *i++;
// performance and understandability
for(i = 1, j = 2, k = 3; i < N; j++, i++);
// understandability and readability
Incorrect examples:
::
buffer += "test", cout << buffer; i = 1;
// heterogeneous processing &
// different objects
while(f(++i), i < MAX);
// processing carried out before the test
Prohibited example:
::
void foo() {
for(...) {
phase1 :
/* ... */
phase2 :
if(errno != 0)
goto erreur;
if (/* a test */)
goto phase2;
}
erreur :
/* error handling */
}
Note: error handling can be easily replaced with exception handling,
and the use of **goto** for the needs of algorithms can always be
replaced with a conditional structure or a loop.
Example: error handling
::
Scalar
compute(UnsignedInteger n) {
Scalar result;
if(n < MIN || n > MAX) {
char msg[BUFSIZ];
// automatic allocation for the processing
snprintf (msg, BUFSIZ,
"n = %d is out of range, valid range is [%d, %d]",
n, MIN, MAX);
throw Exception(msg);
}
/* ... */
return result;
}
Examples to avoid:
::
Scalar
compute(UnsignedInteger n) {
Scalar result;
Char msg[BUFSIF]; // allocation unnecessary if no
// error
if(n < MIN || n > MAX)
...
}
Correct example:
::
switch (errno) {
case ENOENT :
msg = " ... ";
::
break;
case EACCESS :
msg = " ... ";
break;
default :
msg = "unknown error";
break;
}
Accepted example - processing multiple targets with the same block:
::
switch (errno) {
case ENOENT :
case EACCESS :
msg = " impossible to access file ";
break;
default :
/* ... */
break;
}
Incorrect example:
::
switch (errno) {
case 1 : // it is a value
msg = " ... "; //
// "break" is missing,
// processing continues in ENOENT
case ENOENT :
msg = " ... ";
break;
default : // "break" is missing at the
// end of the "default" case
msg = "unknown error";
}
Incorrect example - use of the switch as a goto:
::
switch (phase) {
case PHASE1 :
doPhaseOne();
case PHASE2 :
doPhaseTwo();
break;
default :
/* ... */
}
Example:
::
int
main (int argc, char *argv[])
{
/* ... */
return EXIT_SUCCESS;
}
Exceptions
~~~~~~~~~~
The ability to raise and handle exceptions is one of the strongest
features of C++. However, writing functions and methods that guarantee a
safe behavior when faced with exceptions remains a difficult aspect of
programming.
This chapter describes how to define and use exceptions in the source
code.
Example of **Exception** use:
::
class Exception {
public :
Exception (const char *description, const char * comment = 0);
virtual ~Exception() throw();
/* ... */
friend ostream & operator<< (ostream &, const Exception & e);
};
Example of specialization of **Exception** in order to report an
off-range error:
::
class OutOfBoundException : public Exception {
public:
OutOfBoundException(/* ... */)
: Exception(/* ... */) { }
};
Example of specialization of **Exception** in order to report an
off-range error with a macro-instruction:
::
NEW_EXCEPTION(OutOfBoundException);
Incorrect example:
::
try {
// phase 1
// phase 2
if (result != OK)
throw GotoPhase4();
// phase 3
::
/* ... */
catch (GotoPhase4 e) {
/* ... */
}
// phase 4
Exception handling
~~~~~~~~~~~~~~~~~~
An exception should be thrown when the library encounters conditions
under which it cannot operate.
When coding a new functionality, define a **sufficient** condition
under which the functionality will work correctly,
and have it throw an Exception if this condition is not met.
Correct example:
.. code:: cpp
// Throw if a probability does not belong to [0,1]
if (!( (proba >= 0.0) && (proba <= 1.0) ))
throw InvalidArgumentException(HERE) << "Error: a probability should belong to [0,1]"
<< " but is " << proba;
Typically, it is easier to think about conditions that are sufficient
to make the functionality **not** work correctly,
but this way of thinking has two drawbacks:
- It can lead the programmer to forget situations in which the functionality does not work.
- If the test is performed on a floating point number (Scalar), a possible NaN value will not be caught.
NaN (*Not a Number*) is a value that can be taken by floating point numbers to represent
a missing value or the result of an illicit arithmetical operation (:code:`0/0` for example).
It has the following properties:
- When standard functions like :code:`sqrt` and :code:`max` are passed NaN as one of their arguments, they return NaN.
- All comparison operators except :code:`!=` return :code:`False` if either operand is NaN.
The boolean :code:`a!=b` is :code:`True` if either :code:`a` or :code:`b` (or even both) is NaN.
Because of this second property, the following example fails to catch a possible NaN value.
Incorrect example:
.. code:: cpp
// Throw if a probability is lower than 0 or larger than 1
if ( (proba < 0.0) || (proba > 1.0) )
throw InvalidArgumentException(HERE) << "Error: a probability should belong to [0,1]"
<< " but is " << proba;
Because only floating point numbers can be NaN, this rule is only imperative
for Exception checks involving floating point numbers.
You are free to disregard the rule for Exception checks that only involve integers.
When the sufficient condition under which the functionality works is an equality,
use :code:`a!=b` as a shorthand for :code:`!(a==b)`.
Example:
.. code:: cpp
// The covariance must be null
if (covariance(i, j) != 0.0)
throw InvalidArgumentException(HERE) << "Error: covariance(" << i << ", " << j << ") should be null.";
When the sufficient condition under which the functionality works is that
some number must be *different* from some value, find a way to express this
that does not involve the :code:`!=` operator, because :code:`!(a!=b)`
is equivalent to :code:`a==b`. Both are :code:`False` if either :code:`a`
or :code:`b` is NaN.
For example, if you want to write that some nonnegative scalar should not be zero,
then write that is must be positive instead.
Incorrect example:
.. code:: cpp
// Generalized number of degrees of freedom must not be zero.
if (nu == 0.0) throw InvalidArgumentException(HERE) << "Nu MUST be positive";
Correct example:
.. code:: cpp
// Generalized number of degrees of freedom must be positive.
if (!(nu > 0.0)) throw InvalidArgumentException(HERE) << "Nu MUST be positive";
Error messages
~~~~~~~~~~~~~~
Example:
::
String message;
Log::Debug(message);
Log::Info(message);
Log::User(message);
Log::Warning(message);
Log::Error(message);
These rules refer to the classes and methods in the Python layer using
the services of the internal model and the solvers.
C++ 11
~~~~~~
The library requires the C++ 11 standard.
Some useful features include:
- std::atomic
- std::vector::data()
- std::shared_ptr
- constructor delegation
- default member initializers
- list initialization
- override keyword
Example: constructor delegation:
::
class Foo
{
Foo (int a, int b), a_(a), b_(b)
Foo () : Foo(4, 6)
int a_, b_;
};
Example: default member initializers:
::
class Foo
{
Foo();
int a_ = 0;
};
Example: list initialization:
::
const Indices indices = {1, 2, 3};
const Description desc = {"mu", "sigma"};
Python
------
Modules and packages
~~~~~~~~~~~~~~~~~~~~
Example of tolerated notations:
::
import matplotlib
from matplotlib import pylab
import numpy as np
Incorrect examples:
::
from scipy import *
Names
~~~~~
Examples: RandomVector, Sample.
Examples:
::
rv = RandomVector()
dim = rv.getDimension()
Comments and internal documentation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Example of documentation string for the class
**AnotherSample**:
::
#
# <detailed description for documentation tools such as HappyDoc>
#
class AnotherSample :
"""
this class is designed to ...
"""
#
# <detailed description for developers and documentation tools>
def __init__(self, name, type, range = None, doc = "") :
"""constructor -- """
...
#
# <detailed description for developers and documentation tools>
def computeSomething(self, value):
"""run the well-known Schmoll Algorithm...
"""
Indentation
~~~~~~~~~~~
The python code should use 4 spaces per indentation level.
For more information about python formatting,
refer to `PEP8 <http://www.python.org/dev/peps/pep-0008/>`_.
|