Niouzes

< Juillet 2017 >
Lu Ma Me Je Ve Sa Di
          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            

Citation

2014-01-23 à 11:47:38 par Patrick Boens

Les règles de codage mises en place sur Vae Soli!; Coding Standards

Nos règles de codage s'inspirent de notre expérience passée dans les langages suivants :

  • C
  • ASM
  • C++
  • Clipper
  • Visual FoxPro
  • ColdFusion
  • FMR (lire é-phé-mère)

Pour tous ces langages nous avons respecté des standards clairs basés sur les bonnes pratiques observées dans chacun d'entre eux. Au fil des années, notre application de standards s'est faite plus insistante tout en nous démarquant quelque peu des règles pré-établies pour une seule communauté. En d'autres termes, convaincus que les projets devenaient de plus en plus multi-langages, nous avons mêlé les règles en un ensemble commun cohérent.

Aujourd'hui, ce 07-09-13 09:46, nous commençons à décrire les règles de codage mises en place au cours des années mais nous avons également décidé de nous aligner, tant que faire se peut, sur les règles édictées par le framework Zend. C'est la raison pour laquelle nous publierons nos règles de codage au fur et à mesure au fil de nos besoins pour pouvoir faire appel, dans les meilleures conditions possibles, au crowdsourcing.

Enfin, au même moment, nous décidons de finalement passer à l'anglais comme langue véhiculaire de notre framework. Ce changement est nécessaire afin de capitaliser sur des documents communs que nous pouvons dès lors utiliser pour le crowdsourcing (comme TopCoder et Amazon Mechanical Turk). Ready?

Preamble

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

PHP File Formatting

General

Rule #1: For files that contain only PHP code, the closing tag (?>) MUST NOT be used.

Indentation

Rule #2: Indentation MUST consist of 4 spaces. Tabs MUST NOT be used for indentation.

Maximum Line Length

Rule #3: The target line length is 80 characters. That is to say, Vae Soli! developers SHOULD strive keep each line of their code under 80 characters where possible and practical. However, longer lines are acceptable in some circumstances. The maximum length of any line of code is 150 characters.

Line Termination

Rule #4: Lines MUST end with a carriage-return linefeed combination (CRLF) (0x0D, 0x0A).

Comments

Rule #5: comments releated to ONE line of code MUST start at column 69.

Naming Conventions

PHP Keywords

Rule #6: PHP keywords and language constructs MUST be in lowercase as in :

foreach ( $aFiles as $szFile )
{
…
}

PHP special values : true, false, null

Rule #7: the PHP special values such as true, false and null MUST be in lowercase as in :

$bFound = false;
$szRetVal = null;

General

Rule #8: Use Intention-Revealing names. Choosing good names for variables, classes, methods, functions, parameters, source files, packagages, directories, … is paramount and saves more time than it takes.

Classes

Rule #9: Class names MUST contain only alpha characters (from a to z and A to Z) and the underscore.

Rule #10: Underscores are only permitted in place of the path separator; a class named Do_Something would map to the filename Do/Something.class.php.

Rule #11: If a class name is comprised of more than one word, the first letter of each new word MUST be capitalized. Successive capitalized letters ARE allowed if they match a market convention. A class named MyClassPDF is acceptable to match Vae Soli! standards.

Rule #12: Vae Soli! classes MUST start with the LS prefix as in LSApplication.

Rule #13: Vae Soli! plug-in classes (or companions) MUST start with the LSE prefix as in LSEApplication.

Rule #14: All other classes MUST NOT start with the LS prefix.

Rule #15: The same class file MAY contain only closely related classes. The developer must do his utmost to limit her files to 1! class.

Rule #16: The name of a class file MUST correspond to its main class. The ending portion of the name of the file must be class.php. For example, the LSAutoReference class MUST be contained in a file called LSAutoReference.class.php.

Rule #17: Abstract classes MUST be suffixed with Abstract as in IslandAbstract (because this may be Vae Soli! class it is may be named LSIslandAbstract).

Rule #18: Interfaces MUST be suffixed with Interface as in IslandInterface (because this is a Vae Soli! class it is actually named LSIslandInterface)

Rule #19: When a class is actually a Data Structure it must bear the ds Data Structure Marker in the name of its class file. For example there is a class in Vae Soli! that is so generic that it bears no significant behavior: it is more a generic Data Structure than a class : LSThing coded in LSThing.ds.class.php)

Rule #20: All methods MUST be preceded with their visibility as in public function __construct( $oPage = null,$oIsland = null ).

Functions and Methods

Rule #21: Function names MUST contain only alphanumeric characters. Underscores are not permitted (except to separate the domain of the function from its name, when applicable … see below). Numbers are permitted in function names but are discouraged.

Rule #22: Function names can start with either a lower case or upper case letter. When a function name consists of more than one word, the first letter of each new word MUST be capitalized as in STR_SyntaxColoring().

Rule #23: Function and method names should be as verbose as possible so that it can fully describe their purpose and behavior. Great care MUST be granted to this rule as it often determines the overall success of a function or method, despite its intrisinc usefulness.

Rule #24: Functions SHOULD be grouped per domain. For example, string functions in Vae Soli! are all grouped in LSStrings.functions.php.

Rule #25: Functions belonging to a group or domain must bear the domain name in their name (or have a good indication of). The domain of the function SHOULD be restricted to 3 or 4 characters. The underscore is used to separate the domain and the name of the function as in STR_ltrim().

Rule #26: The name of a function file MUST end with functions.php. For example, the string functions of Vae Soli! are all contained in a file called LSStrings.functions.php; the file functions are all contained in LSFiles.functions.php, …

Rule #27: Constructor methods MUST be named __construct(). They all MUST be declared public explicitely.

Manifest Constants

Rule #28: Manifest constants names MAY contain both alphanumeric characters and underscores as in LS_PAGE_ERROR_CANNOT_START_PAGE.

Rule #29: Manifest constants MUST be all capitalized and all words MUST be separated by an underscore character as in LS_PAGE_ERROR_CANNOT_START_PAGE.

Rule #30: Magic numbers MUST be coded with manifest constants as in const integer SECONDS_PER_DAY = 86400.

Variables

Many of the rules presented in this section have been enforced as to counterfight the fact that PHP is a weakly typed language as opposed to strongly typed language. Huh!

Rule #31: Variables that hold strings MUST be prefixed with 'sz' (old convention from C habits – stands for "string zero terminated" as in $szName = 'Patrick Boens'.

Rule #32: Variables that hold integers MUST be prefixed with 'i' as in $iWidth = 15.

Rule #33: Variables that hold floats (or doubles) MUST be prefixed with 'f' as in $fWidth = 5.3.

Rule #34: Variables that hold objects MUST be prefixed with 'o' as in $oRef = new LSAutoReference().

Rule #35: Variables that hold arrays MUST be prefixed with 'a' as in $aFiles = FIL_aFiles(...).

Rule #36: Variables that hold dates/times specified as strings MUST be prefixed with 'd' as in $dDate = '2013-09-07' or $dDateTime = '2013-09-07 16:11:52'. Such variables MUST adopt the YYYYMMDD format for the date (with or without visual separators).

Rule #37: Variables that hold date/times values MUST be prefixed with 't' as in $tCreated = time(). This type is actually an int whose inner meaning is to express a time value.

Rule #38: Variables that hold booleans MUST be prefixed with 'b' as in $bEnclose = false.

Rule #39: Variables that hold resources MUST be prefixed with 'r' as in $rHandle = FIL_Open( $szFile,'r' ).

Rule #40: Variables that can hold mixed types MUST be prefixed with 'x' as in $xReturn = SomeFunction(). The very same approach applies to variables that can change types.

Rule #41: Developers MUST not use global variables. All variables MUST have a local scope. This is true for ALL variables EXCEPT one: oApp is the ONLY global variable permitted and if it exists it MUST be an instantiation of the LSApplication class.

Special Variables

The variables that are listed below are variables that are found in many different systems, yet in Vae Soli! they are standardized.

Concept Standard variable name Example
Person
Last name$szLastNameBoens
First name$szFirstNamePatrick
Middle initial$szMiddleNameY
First and last name$szNamePatrick Boens (first name then last name)
Full name$szFullNamePatrick Y. Boens
Nickname$szNicknameThe Golfer
Date of birth$dBirthDate19591118031500 (string that represents a date and time)
Date of death$dDeathDate20391231235959 (string that represents a date and time)
Address
Street$szStreetRue Bois des Mazuis
Street continuation #1$szStreet1Building 2F
Street continuation #2$szStreet2Blahblahblah
Street number$szStreetNo47B
Postal Code$szPostalCode5070
City$szCityVitrival
Country$szCountryBelgium. You can also provide the two-letter ISO 3166-1 alpha-2 country code.
State, province, ...$szRegionNamur
Geocoordinates
Elevation$fElevation213.00 (always expressed in meters)
Latitude$fLat50.385200
Longitude$fLong4.660500
Date & Time
Now$iNow1500821481
Today$dToday20170723 (string that represents a date w/o time)
Month$iMonth7
Day$iDay23
Year$iYear2017
Month name$szMonthJuly
Day name$szDaySun
Creation date & time$tCreated1500821481 (an integer that represents a time)
Last update date & time$tLupdate1500821481 (an integer that represents a time)
Duration$tDuration3600 (an integer that represents a time difference in seconds as a result of a computation)
Duration$dDuration116:30:15 (a string that represents hours, minutes, seconds)
Contact
Phone$szPhone+32 71 71 17 43 (compatible with RFC 3966)
Fax$szFax+32 71 71 17 43 (compatible with RFC 3966)
URL$szURLhttp://www.vaesoli.org
Email$szEmailpatrick.boens@vaesoli.org
Contact type$szContactTypeInvoicing
Organization
Legal Name$szLegalNameLato Sensu Management
Legal Form$szLegalFormSPRL
Founders$aFoundersAn array of LSPerson, LSNaturalPerson or LSLegalPerson (mixed types permitted)
Founding date$dFounding20051210 (string that represents a date w/o time)
VAT$szVatIDBE 0878.127.142
Is State
Open$IsOpen or $bOpentrue
Closed$IsClosed or $bClosedfalse
Active$IsActive or $bActivefalse
Visibility$IsVisible or $bVisibletrue
DOM
DOM document$oDom$oDom = new LSDom()
DOM node list$oNodeListforeach( $oNodeList as $oNode )
DOM node$oNodeforeach( $oNodeList as $oNode )
XPath$oXPath$oXPath = new LSXPath( $oDom )
Count and Position
Count$iRecCount$iRecCount = $oCursor->Reccount()
Position in a collection$iRecNo$iRecNo = $oCursor->RecNo()
Position$iPos$iPos = STR_iPos( $szHaystack,$szNeedle )
Application (code)
Application variable$oApp$oApp = new LSApplication(…)

Strings

Rule #42: If a string is not intended to be used in conjunction with dynamic substitutions (variable parsing) it MUST be specified in single quotes as in $szName = 'Patrick Boens'.

Rule #43: If a string is intended to be used in conjunction with dynamic substitutions (variable parsing) the variable MUST be embraced in opening and closing curly braces as in "My name is {$szName}".

Rule #44: String concatenation MUST be achieved with the . operator. A space MUST always be added before and after the operator to improve readability as in : $szName = szFirstName . ' ' . $szLastName;.

Functions

Rule #45: Function calls MUST be written using a leading and a trailing space. The leading space MUST be used right after the opening parenthese and the trailing space MUST be inserted right before the closing parenthese as in $szName = trim( $szFirstName . ' ' . $szLastName );.

Rule #46: The arguments of a function CAN be written with a trailing space after each comma even though the preferred form is NOT to use spaces at all except for the leading and trailing spaces. Preferred form: $szName = STR_AddCode( $szFirstName,$szLastName,14 );; Acceptable form: $szName = STR_AddCode( $szFirstName, $szLastName, 14 );.

Rule #47: Opening braces for functions and methods MUST go on one of the next lines (immediate or after separation markers), and closing braces MUST go on the next line after the body as in :

function StartPage( $szPage = null )
/*--------------------------------*/
{}  /* End of StartPage() */

Rule #48: A terminating mark MUST appear on the same line as of the the closing brace of the body of the function/method as in :

function StartPage( $szPage = null )
/*--------------------------------*/
{
…
}  /* End of StartPage() */

Rule #49: Functions MUST not exceed 100 lines of code. Ideally, they SHOULD be contained in less than 50 lines of code.

Rule #50: Functions MUST do ONE thing; fonctions SHOULD tell a unique story They must express ONE level of abstraction.

Rule #51: Functions MUST NOT contain inner return statements. There SHOULD be one point of return, not many. In case functions/methods are very small, multiple return statements have an obvious benefit and are permitted.

Rule #52: Functions and methods SHOULD restrict the number of mandatory parameters to 3.

Rule #53: Functions that are grouped in a function file MUST share a common Last Errors pattern.

Rule #54: Functions that are very much interdependent SHOULD be close to each other.

Rule #55: Functions that are called (callee functions) by other functions (caller functions) SHOULD appear AFTER the callers if possible (contrary to what MUST be done in C).

Classes

Rule #56: Each class MUST expose a "presence" manifest constant whose goal is to easily test the availability of the class (other than class_exists()). Each word must be separated with an underscore and the CLASS_PWH suffix must be added. Examples :
class LSDecisiondefine( 'LS_DECISION_CLASS_PWH','PWH' )
class LSGroupdefine( 'LS_GROUP_CLASS_PWH','PWH' )
class LSLanguageSwitchersdefine( 'LS_LANGUAGE_SWITCHERS_CLASS_PWH','PWH' ).

Rule #57: Opening braces for classes MUST go on one of the next lines (immediate or after separation markers), and closing braces MUST go on the next line after the body as in :

class LSPage extends LSMotherNature
/*===============================*/
{}   /* End of class LSPage */

Rule #58: A terminating comment MUST appear on the same line as of the the closing brace of the body of the class as in :

class LSPage extends LSMotherNature
/*===============================*/
{
…
}   /* End of class LSPage */

Files

Rule #59: Source code files SHOULD NOT exceed 1000 lines.

Language Control Structures

Rule #60: goto statements MUST be used ONLY in code that implements finite or infinite state machines or to jump to the exit point of a function/method (in which case they favorably replace inner return statements as to assure proper housekeeping). No other usage of goto is permitted.

Rule #61: continue statements SHOULD be avoided as much as possible.

Rule #62: break statements are permitted without limitation.

Rule #63: source code MUST be indented using the Allman style.