You are on page 1of 37

Coding Standard

Revision o!"." Created on! #$% ov%#&"' (ast )odi*ied on! "&%+ul%#&"'

For PHP

www.einterviewquestions.com | The Remote Development Company

Coding Standard
Table of Contents " ,uthorisation............................................................................................................................... # Revision History.......................................................................................................................... . ' PHP File Formatting..................................................................................................................... . - Class ames............................................................................................................................... / ames....................................................................................................... 0

. )ethod and Function / Class (i1rary 0 )ethod

ames................................................................................................................... 2

ames............................................................................................................................ 2 ames................................................................................................................. $ ames........................................................................................................... $

2 Class ,ttri1ute

$ )ethod ,rgument "& 3aria1le

ames......................................................................................................................... $

"" ,rray 4lement......................................................................................................................... "& "# Single or Dou1le 5uotes.......................................................................................................... "" "' Re*erence 3aria1les and Functions Returning Re*erences......................................................"" "- 6lo1al 3aria1les...................................................................................................................... "" ". De*ine ames 7 6lo1al Constants............................................................................................ "#

"/ Static 3aria1les....................................................................................................................... "# "0 Function ames...................................................................................................................... "#

"2 4rror Return Chec8 Policy....................................................................................................... "# "$ 9races :; Policy...................................................................................................................... "' #& <ndentation7Ta1s7Space Policy................................................................................................ "#" Parens => with ?ey @ords and Functions Policy.......................................................................". ## Do ot do Real @or8 in A1Bect Constructors..........................................................................."/

#' <* Then 4lse Formatting........................................................................................................... "0 #- switch Formatting................................................................................................................... "2 #. Continue and 9rea8................................................................................................................. "$ #/ ,lignment o* Declaration 9loc8s............................................................................................. #" #0 Document #2 Do ull Statements..................................................................................................... #" on%Cero.......................................................................................... ##

ot De*ault <* Test to

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

Coding Standard
#$ The 9ull o* 9oolean Types....................................................................................................... ## '& Dsually ,void 4m1edded ,ssignments....................................................................................#' '" Comments on Comments........................................................................................................ #'# <nter*ace and <mplementation Documentation........................................................................#0 '' Directory Documentation........................................................................................................ #2 '- Server con*iguration................................................................................................................ #$ '. PHP File 4Etensions................................................................................................................. #$ '/ Di**erent ,ccessor Styles........................................................................................................ '" '0 (ayering.................................................................................................................................. '# '2 Code Reviews.......................................................................................................................... '# '$ Create a Source Code Control System 4arly and ot A*ten....................................................''

-& PHP Code Tags........................................................................................................................ '. -" o )agic um1ers.................................................................................................................. '/

-# Thin vs. Fat Class <nter*aces.................................................................................................... '0

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

'

Coding Standard
1 Authorisation
Prepared by Signature Name Email-id Role ate Reviewed by Approved by

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

Coding Standard
! Revision "istory

&

Revision No'

ate
=DD%)A % FFFF>

Revision

es(ription

Se(tion)s* revised

Page)s*

" #

".& "." "&%+ul%#&"'

Dra*t <ncluded in standard Template *ormat ,ll ,ll

P"P $ile $ormatting


%eneral

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

Coding Standard
For *iles that contain only PHP codeG the closing tag =HIJH> is never permitted. <t is not required 1y PHPG and omitting it prevents the accidental inBection o* trailing white space into the response. +ndentation <ndentation should consist o* - spaces. Ta1s are not allowed. ,a-imum .ine .ength The target line length is 2& characters. That is to sayG developers should strive 8eep each line o* their code under 2& characters where possi1le and practical. HoweverG longer lines are accepta1le in some circumstances. The maEimum length o* any line o* PHP code is "#& characters. .ine Termination (ine termination *ollows the DniE teEt *ile convention. (ines must end with a single line*eed =(F> character. Names ,a/e Names $it ames are the heart o* programming. <n the past people 1elieved 8nowing someoneKs true name gave them magical power over that person. <* you can thin8 up the true name *or somethingG you give yoursel* and the people coming a*ter power over the code. DonKt laughL , name is the result o* a long deep thought process a1out the ecology it lives in. Anly a programmer who understands the system as a whole can create a name that H*itsH with the system. <* the name is appropriate everything *its together naturallyG relationships are clearG meaning is deriva1leG and reasoning *rom common human eEpectations wor8s as eEpected. <* you *ind all your names could 1e Thing and Do<t then you should pro1a1ly revisit your design.

Class Names
ame the class a*ter what it is. <* you canKt thin8 o* what it is that is a clue you have not thought through the design well enough. Compound names o* over three words are a clue your design may 1e con*using various entities in your system. Revisit your design. Try a CRC card session to see i* your o1Bects have more responsi1ilities than they should. ,void the temptation o* 1ringing the name o* the class a class derives *rom into the derived classKs name. , class should stand on its own. <t doesnKt matter what it derives *rom. Su**iEes are sometimes help*ul. For eEampleG i* your system uses agents then naming something Download,gent conveys real in*ormation.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

Coding Standard
1 ,ethod and $un(tion Names
Dsually every method and *unction per*orms an actionG so the name should ma8e clear what it does! Chec8For4rrors=> instead o* 4rrorChec8=>G DumpDataToFile=> instead o* DataFile=>. This will also ma8e *unctions and data o1Bects more distinguisha1le. Su**iEes are sometimes use*ul! o o o Max % to mean the maEimum value something can have. Cnt % the current count o* a running count varia1le. Key % 8ey value.

For eEample! Retry)aE to mean the maEimum num1er o* retriesG RetryCnt to mean the current retry count. Pre*iEes are sometimes use*ul! o o o Is % to as8 a question a1out something. @henever someone sees Is they will 8now itKs a question. Get % get a value. Set % set a value.

For eEample! <sHitRetry(imit. No All 2pper Case Abbreviations @hen con*ronted with a situation where you could use an all upper case a11reviation instead use an initial upper case letter *ollowed 1y all lower case letters. Do use! 6etHtmlStatistic. Do not use! 6etHT)(Statistic. 3ustifi(ation People seem to have very di**erent intuitions when ma8ing names containing a11reviations. <tKs 1est to settle on one strategy so the names are a1solutely predicta1le. Ta8e *or eEample NetworkABCKey. otice how the C *rom ,9C and ? *rom 8ey are o matter what.

con*used. Some people donKt mind this and others Bust hate it so youKll *ind di**erent policies in di**erent code so you never 8now what to call something. E-ample class FluidAM 77 AT FluidAC 77 AT 6etHT)(Statistic class 6etHtmlStatistic Class Names

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

Coding Standard
Dse upper case letters as word separatorsG lower case *or the rest o* a word First character in a name is upper case o under1ars =KNK>

3ustifi(ation A* all the di**erent naming strategies many people *ound this one the 1est compromise.

E-ample class class ameAneTwo ame

Class .ibrary Names


ow that name spaces are 1ecoming more widely implementedG name spaces should 1e used to prevent class name con*licts among li1raries *rom di**erent vendors and groups. @hen not using name spacesG itKs common to prevent class name clashes 1y pre*iEing class names with a unique string. Two characters is su**icientG 1ut a longer length is *ine. E-ample +ohn +ohnsonKs complete data structure li1rary could use JJ as a pre*iEG so classes would 1e! class +B(in8(ist : ;

,ethod Names
Dse the same rule as *or class names.

3ustifi(ation A* all the di**erent naming strategies many people *ound this one the 1est compromise.

E-ample class : *unction Do<t=> :;O *unction Handle4rror=> :;O ; ameAneTwo

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

Coding Standard
6 Class Attribute Names
Class mem1er attri1ute names should 1e prepended with the character KmK. ,*ter the KmK use the same rules as *or class names. KmK always precedes other name modi*iers li8e KrK *or re*erence.

3ustifi(ation Prepending KmK prevents any con*lict with method names. A*ten your methods and attri1ute names will 1e similarG especially *or accessors. E-ample class : *unction 3ar,1c=> :;O *unction 4rror um1er=> :;O var Pm3ar,1cO var Pm4rror um1erO var Pmr ameO ; ameAneTwo

,ethod Argument Names


The *irst character should 1e lower case. ,ll word 1eginnings a*ter the *irst letter should 1e upper case as with class names.

3ustifi(ation Fou can always tell which varia1les are passed in varia1les.

E-ample class : *unction StartFour4ngines=QPsome4ngineG QPanother4ngine> : Pthis%JmSome4ngine R Psome4ngineO Pthis%Jm,nother4ngine R Panother4ngineO ; var PmSome4ngineO var Pm,nother4ngineO ; ameAneTwo

18 9ariable Names
use all lower case letters
$ <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

www.einterviewquestions.com Coding Standard

Coding Standard
use KNK as the word separator. 3ustifi(ation @ith this approach the scope o* the varia1le is clear in the code. ow all varia1les loo8 di**erent and are identi*ia1le in the code.

E-ample *unction Handle4rror=Perror um1er> : Perror R new As4rrorO PtimeNo*Nerror R Perror%J6etTimeA*4rror=>O PerrorNprocessor R Perror%J6et4rrorProcessor=>O ;

11 Array Element
,rray element names *ollow the same rules as a varia1le. use KNK as the word separator. donKt use K%K as the word separator

3ustifi(ation i* K%K is used as a word separator it will generate warnings used with magic quotes.

E-ample PmyarrSK*ooN1arKT R KHelloKO print HPmyarrS*ooN1arT worldHO 77 will output! Hello world PmyarrSK*oo%1arKT R KHelloKO print HPmyarrS*oo%1arT worldHO 77 warning message

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

"&

Coding Standard
1! Single or

ouble :uotes

,ccess an arrayKs elements with single or dou1le quotes. DonKt use quotes within magic quotes

3ustifi(ation Some PHP con*igurations will output warnings i* arrays are used without quotes eEcept when used within magic quotes E-ample PmyarrSK*ooN1arKT R KHelloKO PelementNname R K*ooN1arKO print HPmyarrS*ooN1arT worldHO 77 will output! Hello world print HPmyarrSPelementNnameT worldHO 77 will output! Hello world print HPmyarrSKPelementNnameKT worldHO 77 parse error print HPmyarrSHPelementNnameHT worldHO 77 parse error

1# Referen(e 9ariables and $un(tions Returning Referen(es


Re*erences should 1e prepended with KrK.

3ustifi(ation The di**erence 1etween varia1le types is clari*ied. <t esta1lishes the di**erence 1etween a method returning a modi*ia1le o1Bect and the same method name returning a non%modi*ia1le o1Bect. E-ample class Test : var PmrStatusO *unction DoSomething=QPrStatus> :;O *unction QrStatus=> :;O ;

10 %lobal 9ariables
6lo1al varia1les should 1e prepended with a KgK.

3ustifi(ation <tKs important to 8now the scope o* a varia1le.

E-ample glo1al Pg(ogO glo1al QPgr(ogO


www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"' ""

Coding Standard
11

efine Names ; %lobal Constants


6lo1al constants should 1e all caps with KNK separators.

3ustifi(ation <tKs tradition *or glo1al constants to named this way. Fou must 1e care*ul to not con*lict with other prede*ined glo1als. E-ample de*ine=H,N6(A9,(NCA ST, THG HHello worldLH>O

14 Stati( 9ariables
Static varia1les may 1e prepended with KsK.

3ustifi(ation <tKs important to 8now the scope o* a varia1le.

E-ample *unction test=> : static PmsStatus R &O ;

15 $un(tion Names
For PHP *unctions use the C 6 D convention o* all lower case letters with KNK as the word delimiter. 3ustifi(ation <t ma8es *unctions very di**erent *rom any class related names.

E-ample *unction someN1loodyN*unction=> : ;

16 Error Return Che(/ Poli(y


Chec8 every system call *or an error returnG unless you 8now you wish to ignore errors. <nclude the system error teEt *or every system error message.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

"#

Coding Standard
17 <ra(es {} Poli(y
A* the three maBor 1race placement strategies two are accepta1leG with the *irst one listed 1eing pre*era1le! ; ; Place 1race under and inline with 8eywords! i* =Pcondition> : ... : ... ; while =Pcondition>

Traditional DniE policy o* placing the initial 1race on the same line as the 8eyword and the trailing 1race inline on its own line with the 8eyword! i* =Pcondition> : ... ... ; while =Pcondition> :

3ustifi(ation ,nother religious issue o* great de1ate solved 1y compromise. 4ither *orm is accepta1leG many peopleG howeverG *ind the *irst *orm more pleasant. @hy is the topic o* many psychological studies. There are more reasons than psychological *or pre*erring the *irst style. <* you use an editor =such as vi> that supports 1race matchingG the *irst is a much 1etter style. @hyI (etKs say you have a large 1loc8 o* code and want to 8now where the 1loc8 ends. Fou move to the *irst 1race hit a 8ey and the editor *inds the matching 1race. 4Eample! i* =PveryNlongNcondition QQ PsecondNveryNlongNcondition> : ... ; else i* =...> : ... ; To move *rom 1loc8 to 1loc8 you Bust need to use cursor down and your 1race matching 8ey. o need to move to the end o* the line to match a 1race then Ber8 1ac8 and *orth.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

"'

Coding Standard
!8 +ndentation;Tabs;Spa(e Poli(y
<ndent using - spaces *or each level. Do not use ta1sG use spaces. )ost editors can su1stitute spaces *or ta1s. <ndent as much as neededG 1ut no more. There are no ar1itrary rules as to the maEimum indenting level. <* the indenting level is more than - or . levels you may thin8 a1out *actoring out code. 3ustifi(ation @hen people using di**erent ta1 settings the code is impossi1le to read or printG which is why spaces are pre*era1le to ta1s. )ost PHP applications use - spaces. )ost editors use - spaces 1y de*alt. ,s much as people would li8e to limit the maEimum indentation levels it never seems to wor8 in general. @eKll trust that programmers will choose wisely how deep to nest code. E-ample *unction *unc=> : i* =something 1ad> : i* =another thing 1ad> : while =more input> : ; ; ; ;

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

"-

Coding Standard
!1 Parens () with =ey >ords and $un(tions Poli(y
Do not put parens neEt to 8eywords. Put a space 1etween. Do put parens neEt to *unction names. Do not use parens in return statements when itKs not necessary.

3ustifi(ation ?eywords are not *unctions. 9y putting parens neEt to 8eywords 8eywords and *unction names are made to loo8 ali8e. E-ample i* =condition> : ; while =condition> : ; strcmp=PsG Ps">O return "O

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

".

Coding Standard
!! o Not do Real >or/ in ?b@e(t Constru(tors
Do not do any real wor8 in an o1BectKs constructor. <nside a constructor initialiMe varia1les only and7or do only actions that canKt *ail. Create an Apen=> method *or an o1Bect which completes construction. Apen=> should 1e called a*ter o1Bect instantiation. 3ustifi(ation Constructors canKt return an error.

E-ample class Device : *unction Device=> ;O Pdev R new DeviceO i* =F,<( RR Pdev%JApen=>> eEit=">O ,a/e $un(tions Reentrant Functions should not 8eep static varia1les that prevent a *unction *rom 1eing reentrant. : 7U initialiMe and other stu** U7 ; *unction Apen=> : return F,<(O ;

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

"/

Coding Standard
!# +f Then Else $ormatting
.ayout <tKs up to the programmer. Di**erent 1racing styles will yield slightly di**erent loo8s. Ane common approach is! i* =condition> : ; else i* =condition> : ; else : ; <* you have else if statements then it is usually a good idea to always have an else 1loc8 *or *inding unhandled cases. )ay1e put a log message in the else even i* there is no corrective action ta8en. Condition $ormat ,lways put the constant on the le*t hand side o* an equality7inequality comparison. For eEample! i* = / RR Perror um > ... Ane reason is that i* you leave out one o* the R signsG the parser will *ind the error *or you. , second reason is that it puts the value you are loo8ing *or right up *ront where you can *ind it instead o* 1uried at the end o* your eEpression. <t ta8es a little time to get used to this *ormatG 1ut then it really gets use*ul. 77 Comment 77 Comment 77 Comment

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

"0

Coding Standard
!0 switch $ormatting
Falling through a case statement into the neEt case statement shall 1e permitted as long as a comment is included. The default case should always 1e present and trigger an error i* it should not 1e reachedG yet is reached. <* you need to create varia1les put all the code in a 1loc8.

E-ample switch =...> : case "! ... 77 F,(( THRAD6H case #! : Pv R getNwee8Nnum1er=>O ... ; 1rea8O de*ault! ; 2se of continueAbreak and BC

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

"2

Coding Standard
!1 Continue and <rea/
Continue and 1rea8 are really disguised gotos so they are covered here. Continue and 1rea8 li8e goto should 1e used sparingly as they are magic in code. @ith a simple spell the reader is 1eamed to god 8nows where *or some usually undocumented reason. The two main pro1lems with continue are! <t may 1ypass the test condition <t may 1ypass the increment7decrement eEpression

Consider the *ollowing eEample where 1oth pro1lems occur! while =TRD4> : ... 77 , lot o* code ... i* =7U some condition U7> : continueO ; ... 77 , lot o* code ... i* = PiVV J STAPN3,(D4> 1rea8O ; ote! H, lot o* codeH is necessary in order that the pro1lem cannot 1e caught easily 1y the programmer. From the a1ove eEampleG a *urther rule may 1e given! )iEing continue with 1rea8 in the same loop is a sure way to disaster. BC The trou1le is people usually try and stu** too much code in 1etween the ? and :. Here are a couple o* clarity rules to *ollow! Put the condition in parens so as to set it o** *rom other code <* possi1leG the actions *or the test should 1e simple *unctions. Put the action *or the then and else statement on a separate line unless it can 1e clearly put on one line.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

"$

Coding Standard
E-ample =condition> I *unct"=> ! *unc#=>O or =condition> I long statement ! another long statementO

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

#&

Coding Standard
!4 Alignment of

e(laration <lo(/s

9loc8 o* declarations should 1e aligned.

3ustifi(ation Clarity. Similarly 1loc8s o* initialiMation o* varia1les should 1e ta1ulated. The WQX to8en should 1e adBacent to the typeG not the name.

E-ample var varQ varQ var PmDate PmrDate Pmr ame Pm ame R &O D((O D((O

PmDate

PmrDate R Pm ame R

Pmr ame R &O ?ne Statement Per .ine There should 1e only one statement per line unless the statements are very closely related. Short ,ethods )ethods should limit themselves to a single page o* code.

3ustifi(ation The idea is that the each method represents a technique *or achieving a single o1Bective. )ost arguments o* ine**iciency turn out to 1e *alse in the long run. True *unction calls are slower than notG 1ut there needs to a thought out decision =see premature optimiMation>.

!5

o(ument Null Statements


,lways document a null 1ody *or a *or or while statement so that it is clear that the null 1ody is intentional and not missing code. while =PdestVV R PsrcVV> O 77 3A<D

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

#"

Coding Standard
!6 o Not efault +f Test to Non-Dero
Do not de*ault the test *or non%MeroG i.e. i* =F,<( LR *=>> is 1etter than i* =*=>> even though F,<( may have the value & which PHP considers to 1e *alse. ,n eEplicit test will help you out later when some1ody decides that a *ailure return should 1e %" instead o* &. 4Eplicit comparison should 1e used even i* the comparison value will never changeO e.g.G if )E)FbufsiGe H strlen)Fstr*** should 1e written instead as if )8 II )FbufsiGe H strlen)Fstr*** to re*lect the numeric =not 1oolean> nature o* the test. , *requent trou1le spot is using strcmp to test *or string equalityG where the result should never ever 1e de*aulted. The non%Mero test is o*ten de*aulted *or predicates and other *unctions or eEpressions which meet the *ollowing restrictions! Returns & *or *alseG nothing else. <s named so that the meaning o* =say> a true return is a1solutely o1vious. Call a predicate <s3alid=>G not Chec83alid=>.

!7 The <ull of <oolean Types


Do not chec8 a 1oolean value *or equality with " =TRD4G F4SG etc.>O instead test *or inequality with & =F,(S4G i* true. ThusG i* =TRD4 RR *unc=>> : ... must 1e written i* =F,(S4 LR *unc=>> : ... AG etc.>. )ost *unctions are guaranteed to return & i* *alseG 1ut only non%Mero

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

##

Coding Standard
#8 2sually Avoid Embedded Assignments
There is a time and a place *or em1edded assignment statements. <n some constructs there is no 1etter way to accomplish the results without ma8ing the code 1ul8ier and less reada1le. while =Pa LR =Pc R getchar=>>> : process the character ; The VV and %% operators count as assignment statements. SoG *or many purposesG do *unctions with side e**ects. Dsing em1edded assignment statements to improve run%time per*ormance is also possi1le. HoweverG one should consider the tradeo** 1etween increased speed and decreased maintaina1ility that results when em1edded assignments are used in arti*icial places. For eEampleG Pa R P1 V PcO Pd R Pa V PrO should not 1e replaced 1y Pd R =Pa R P1 V Pc> V PrO even though the latter may save one cycle. <n the long run the time di**erence 1etween the two will decrease as the optimiMer gains maturityG while the di**erence in ease o* maintenance will increase as the human memory o* whatKs going on in the latter piece o* code 1egins to *ade. Reusing Jour "ard >or/ and the "ard >or/ of ?thers Reuse across proBects is almost impossi1le without a common *ramewor8 in place. A1Bects con*orm to the services availa1le to them. Di**erent proBects have di**erent service environments ma8ing o1Bect reuse di**icult. Developing a common *ramewor8 ta8es a lot o* up *ront design e**ort. @hen this e**ort is not madeG *or whatever reasonsG there are several techniques one can use to encourage reuse! onKt be Afraid of Small .ibraries Ane common enemy o* reuse is people not ma8ing li1raries out o* their code. , reusa1le class may 1e hiding in a program directory and will never have the thrill o* 1eing shared 1ecause the programmer wonKt *actor the class or classes into a li1rary. Ane reason *or this is 1ecause people donKt li8e ma8ing small li1raries. ThereKs something a1out small li1raries that doesnKt *eel right. 6et over it. The computer doesnKt care how many li1raries you have.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

#'

Coding Standard
<* you have code that can 1e reused and canKt 1e placed in an eEisting li1rary then ma8e a new li1rary. (i1raries donKt stay small *or long i* people are really thin8ing a1out reuse. <* you are a*raid o* having to update ma8e*iles when li1raries are recomposed or added then donKt include li1raries in your ma8e*ilesG include the idea o* servi(es. 9ase level ma8e*iles de*ine services that are each composed o* a set o* li1raries. Higher level ma8e*iles speci*y the services they want. @hen the li1raries *or a service change only the lower level ma8e*iles will have to change. =eep a Repository )ost companies have no idea what code they have. ,nd most programmers still donKt communicate what they have done or as8 *or what currently eEists. The solution is to 8eep a repository o* whatKs availa1le. <n an ideal world a programmer could go to a we1 pageG 1rowse or search a list o* pac8aged li1rariesG ta8ing what they need. <* you can set up such a system where programmers voluntarily maintain such a systemG great. <* you have a li1rarian in charge o* detecting reusa1ilityG even 1etter. ,nother approach is to automatically generate a repository *rom the source code. This is done 1y using common classG methodG li1raryG and su1system headers that can dou1le as man pages and repository entries.

#1 Comments on Comments
Comments Should Tell a Story Consider your comments a story descri1ing the system. 4Epect your comments to 1e eEtracted 1y a ro1ot and *ormed into a man page. Class comments are one part o* the storyG method signature comments are another part o* the storyG method arguments another partG and method implementation yet another part. ,ll these parts should weave together and in*orm someone else at another point o* time Bust eEactly what you did and why. o(ument e(isions

Comments should document decisions. ,t every point where you had a choice o* what to do place a comment descri1ing which choice you made and why. ,rcheologists will *ind this the most use*ul in*ormation. 2se "eaders Dse a document eEtraction system li8e ccdoc . Ather sections in this document descri1e how to use ccdoc to document a class and method. These headers are structured in such a way as they can 1e parsed and eEtracted. They are not useless li8e normal headers. So ta8e time to *ill them out. <* you do it right once no more documentation may 1e necessary.
www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"' #-

Coding Standard
Comment .ayout 4ach part o* the proBect has a speci*ic comment layout.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

#.

Coding Standard
,a/e %ot(has E-pli(it 4Eplicitly comment varia1les changed out o* the normal control *low or other code li8ely to 1rea8 during maintenance. 4m1edded 8eywords are used to point out issues and potential pro1lems. Consider a ro1ot will parse your comments loo8ing *or 8eywordsG stripping them outG and ma8ing a report so people can ma8e a special e**ort where needed. %ot(ha =eywords CT? ?C topi( )eans thereKs more to do hereG donKt *orget. C<2%C LbugidM topi( means thereKs a ?nown 1ug hereG eEplain it and optionally give a 1ug <D. C=.2 %EC @hen youKve done something ugly say so and eEplain how you would do it di**erently neEt time i* you had more time. CTR+C=JC Tells some1ody that the *ollowing code is very tric8y so donKt go changing it without thin8ing. C>ARN+N%C 9eware o* something. CPARSERC Sometimes you need to wor8 around a parser pro1lem. Document it. The pro1lem may go away eventually. CATTR+<2TEC value The general *orm o* an attri1ute em1edded in a comment. Fou can ma8e up your own attri1utes and theyKll 1e eEtracted. %ot(ha $ormatting )a8e the gotcha 8eyword the *irst sym1ol in the comment. Comments may consist o* multiple linesG 1ut the *irst line should 1e a sel*%containingG meaning*ul summary. The writerKs name and the date o* the remar8 should 1e part o* the comment. This in*ormation is in the source repositoryG 1ut it can ta8e a quite a while to *ind out when and 1y whom it was added. A*ten gotchas stic8 around longer than they should. 4m1edding date in*ormation allows other programmer to ma8e this decision. 4m1edding who in*ormation lets us 8now who to as8. E-ample 77 !TADA! tmh $/&2"&! possi1le per*ormance pro1lem 77 @e should really use a hash ta1le here 1ut *or now weKll 77 use a linear search.
www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"' #/

Coding Standard
77 !?(DD64! tmh $/&2"&! possi1le unsa*e type cast 77 @e need a cast here to recover the derived type. <t should 77 pro1a1ly use a virtual method or template. See Also See <nter*ace and <mplementation Documentation *or more details on how documentation should 1e laid out.

#! +nterfa(e and +mplementation


Class Dsers Class <mplementors

o(umentation

There are two main audiences *or documentation!

@ith a little *orethought we can eEtract 1oth types o* documentation directly *rom source code. Class 2sers Class users need class inter*ace in*ormation which when structured correctly can 1e eEtracted directly *rom a header *ile. @hen *illing out the header comment 1loc8s *or a classG only include in*ormation needed 1y programmers who use the class. DonKt delve into algorithm implementation details unless the details are needed 1y a user o* the class. Consider comments in a header *ile a man page in waiting. Class +mplementors Class implementors require in%depth 8nowledge o* how a class is implemented. This comment type is *ound in the source *ile=s> implementing a class. DonKt worry a1out inter*ace issues. Header comment 1loc8s in a source *ile should cover algorithm issues and other design decisions. Comment 1loc8s within a methodKs implementation should eEplain even more.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

#0

Coding Standard
##

ire(tory

o(umentation

4very directory should have a R4,D)4 *ile that covers! the purpose o* the directory and what it contains a one line comment on each *ile. , comment can usually 1e eEtracted *rom the attri1ute o* the *ile header. cover 1uild and install directions direct people to related resources! o o o o directories o* source online documentation paper documentation design documentation ,)4

anything else that might help someone

Consider a new person coming in / months a*ter every original person on a proBect has gone. That lone scared eEplorer should 1e a1le to piece together a picture o* the whole proBect 1y traversing a source directory tree and reading R4,D)4 *ilesG )a8e*ilesG and source *ile headers. ?pen;Closed Prin(iple The Apen7Closed principle states a class must 1e open and closed where! open means a class has the a1ility to 1e eEtended. closed means a class is closed *or modi*ications other than eEtension. The idea is once a class has 1een approved *or use having gone through code reviewsG unit testsG and other quali*ying proceduresG you donKt want to change the class very muchG Bust eEtend it. The Apen7Closed principle is a pitch *or sta1ility. , system is eEtended 1y adding new code not 1y changing already wor8ing code. Programmers o*ten donKt *eel com*orta1le changing old code 1ecause it wor8sL This principle Bust gives you an academic sounding Busti*ication *or your *ears !%> <n practice the Apen7Closed principle simply means ma8ing good use o* our old *riends a1straction and polymorphism. ,1straction to *actor out common processes and ideas. <nheritance to create an inter*ace that must 1e adhered to 1y derived classes.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

#2

Coding Standard
#0 Server (onfiguration
This section contains some guidelines *or PHP7,pache con*iguration. "TTPNON9ARS HTTPNUN3,RS are either ena1led or disa1led. @hen ena1led all varia1les must 1e accessed through PHTTPNUN3,RSS8eyT. @hen disa1led all varia1les can 1e accessed 1y the 8ey name. use HTTPNUN3,RS when accessing varia1les. use ena1led HTTPNUN3,RS in PHP con*iguration.

3ustifi(ation HTTPNUN3,RS is availa1le in any con*iguration. HTTPNUN3,RS will not con*lict with eEsisting varia1les. Dsers canKt change varia1les 1y passing values.

#1 P"P $ile E-tensions


There is lots o* di**erent eEtension variants on PHP *iles =.htmlG .phpG .php'G .php-G .phtmlG .incG .class...>. ,lways use the eEtension .php. ,lways use the eEtension .php *or your class and *unction li1raries.

3ustifi(ation The use o* .php ma8es it possi1le to ena1le caching on other *iles than .php. The use o* .inc or .class can 1e a security pro1lem. An most servers these eEtensions arenKt set to 1e run 1y a parser. <* these are accessed they will 1e displayed in clear teEt. ,is(ellaneous This section contains some miscellaneous doKs and donKts. DonKt use *loating%point varia1les where discrete values are needed. Dsing a *loat *or a loop counter is a great way to shoot yoursel* in the *oot. ,lways test *loating%point num1ers as YR or JRG never use an eEact comparison =RR or LR>. Do not rely on automatic 1eauti*iers. The main person who 1ene*its *rom good program style is the programmer him7hersel*G and especially in the early design o* handwritten algorithms or pseudo%code. ,utomatic 1eauti*iers can only 1e applied to completeG syntactically correct programs and hence are not availa1le when the need *or attention to white space and indentation is greatest. Programmers can do a 1etter Bo1 o* ma8ing clear the complete visual layout o* a *unction or *ileG with the normal attention to detail o* a care*ul programmer =in other wordsG some o* the visual layout is dictated 1y intent rather than syntaE and 1eauti*iers cannot read minds>. Sloppy programmers should learn to 1e care*ul programmers instead o* relying on a 1eauti*ier to ma8e their code reada1le.
www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"' #$

Coding Standard
FinallyG since 1eauti*iers are non%trivial programs that must parse the sourceG a sophisticated 1eauti*ier is not worth the 1ene*its gained 1y such a program. 9eauti*iers are 1est *or gross *ormatting o* machine%generated code. ,ccidental omission o* the second ZZRKK o* the logical compare is a pro1lem. The *ollowing is con*using and prone to error. i* =Pa1oolR P11ool> : ... ; Does the programmer really mean assignment hereI A*ten yesG 1ut usually no. The solution is to Bust not do itG an inverse 1e*ore doing the test! Pa1oolR P11oolO i* =Pa1ool> : ... ; i8e philosophy. <nstead use eEplicit tests and avoid assignment with an implicit test. The recommended *orm is to do the assignment

2se if )8* to Comment ?ut Code <lo(/s Sometimes large 1loc8s o* code need to 1e commented out *or testing. The easiest way to do this is with an i* =&> 1loc8! *unction eEample=> : great loo8ing code i* =&> : lots o* code ; more code ; Fou canKt use ;OO; style comments 1ecause comments canKt contain comments and surely a large 1loc8 o* your code will contain a commentG wonKt itI

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

'&

Coding Standard
#4 ifferent A((essor Styles
+mplementing A((essors There are two maBor idioms *or creating accessors. %et;Set class [ : *unction 6et,ge=> *unction Set,ge=Page> var Pm,geO ;O 6et7Set is ugly. 6et and Set are strewn throughout the code cluttering it up. 9ut one 1ene*it is when used with messages the set method can transparently trans*orm *rom native machine representations to networ8 1yte order. Attributes as ?b@e(ts class [ : *unction *unction var var ; PE R new [O 77 4Eample " Page R PE%J,ge=>O PrNage R QPE%J,ge=>O 77 Re*erence 77 4Eample # Pname R PE%J ame=>O PrNname R QPE%J ame=>O 77 Re*erence ,ttri1utes as A1Bects is clean *rom a name perspective. @hen possi1le use this approach to attri1ute access. ,ge=> ame=> Pm,geO Pm ameO : return Pthis%Jm,geO ; : return Pthis%Jm ameO ; : return Pthis%Jm,geO ; : Pthis%Jm,ge R PageO ;

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

'"

Coding Standard
#5 .ayering
(ayering is the primary technique *or reducing compleEity in a system. , system should 1e divided into layers. (ayers should communicate 1etween adBacent layers using well de*ined inter*aces. @hen a layer uses a non%adBacent layer then a layering violation has occurred. , layering violation simply means we have dependency 1etween layers that is not controlled 1y a well de*ined inter*ace. @hen one o* the layers changes code could 1rea8. @e donKt want code to 1rea8 so we want layers to wor8 only with other adBacent layers. Sometimes we need to Bump layers *or per*ormance reasons. This is *ineG 1ut we should 8now we are doing it and document appropriately.

#6 Code Reviews
<* you can ma8e a *ormal code review wor8 then my hat is o** to you. Code reviews can 1e very use*ul. Dn*ortunately they o*ten degrade into nit pic8ing sessions and endless arguments a1out silly things. They also tend to ta8e a lot o* peopleKs time *or a questiona1le pay1ac8. )y god heKs questioning code reviewsG heKs not an engineerL ot reallyG itKs the *orm o* code reviews and how they *it into normally late chaotic proBects is what is 1eing questioned. FirstG code reviews are way too late to do much o* anything use*ul. @hat needs reviewing are requirements and design. This is where you will get more 1ang *or the 1uc8. 6et all relevant people in a room. (oc8 them in. 6o over the class design and requirements until the *ormer is good and the latter is 1eing met. Having all the relevant people in the room ma8es this process a deep *ruit*ul one as questions can 1e immediately answered and issues immediately eEplored. Dsually only a couple o* such meetings are necessary. <* the a1ove process is done well coding will ta8e care o* itsel*. <* you *ind pro1lems in the code review the 1est you can usually do is a rewrite a*ter someone has sun8 a ton o* time and e**ort into ma8ing the code Hwor8.H Fou will still want to do a code reviewG Bust do it o**line. Have a couple people you trust read the code in question and simply ma8e comments to the programmer. Then the programmer and reviewers can discuss issues and wor8 them out. 4mail and quic8 pointed discussions wor8 well. This approach meets the goals and doesnKt ta8e the time o* / people to do it.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

'#

Coding Standard
#7 Create a Sour(e Code Control System Early and Not ?ften
, common 1uild system and source code control system should 1e put in place as early as possi1le in a proBectKs li*ecycleG pre*era1ly 1e*ore anyone starts coding. Source code control is the structural glue 1inding a proBect together. <* programmers canKt easily use each otherKs products then youKll never 1e a1le to ma8e a good reproduci1le 1uild and people will piss away a lot o* time. <tKs also hell converting rogue 1uild environments to a standard system. 9ut it seems the right o* passage *or every proBect to 1uild their own custom environment that never quite wor8s right. Some issues to 8eep in mind! Shared source environments li8e C3S usually wor8 1est in largish proBects. <* you use C3S use a reference tree approach. @ith this approach a master 1uild tree is 8ept o* various 1uilds. Programmers chec8out source against the 1uild they are wor8ing on. They only chec8out what they need 1ecause the ma8e system uses the 1uild *or anything not *ound locally. Dsing the I and ! *lags ma8es this system easy to setup. Search locally *or any *iles and li1raries then search in the re*erence 1uild. This approach saves on dis8 space and 1uild time. 6et a lot o* dis8 space. @ith dis8 space as cheap it is there is no reason not to 8eep plenty o* 1uilds around. )a8e simple things simple. <t should 1e dead simple and well documented on how to! o o o o o o o chec8 out modules to 1uild how to change *iles how to add new modules into the system how to delete modules and *iles how to chec8 in changes what are the availa1le li1raries and include *iles how to get the 1uild environment including all compilers and other tools ew programmers shouldnKt have to go

)a8e a we1 page or document or whatever.

around 1egging *or 1uild secrets *rom the old timers. An chec8ins log comments should 1e use*ul. These comments should 1e collected every night and sent to interested parties. Sour(es <* you have the money many proBects have *ound Clear Case a good system. Per*ectly wor8a1le systems have 1een 1uilt on top o* 6 D ma8e and C3S. C3S is a *reeware 1uild environment 1uilt on top o* RCS. <ts main di**erence *rom RCS is that is supports a shared *ile model to 1uilding so*tware.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

''

Coding Standard
Create a <ug Tra(/ing System Early and Not ?ften The earlier people get used to using a 1ug trac8ing system the 1etter. <* you are '7- through a proBect and then install a 1ug trac8ing system it wonKt 1e used. Fou need to install a 1ug trac8ing system early so people will use it. Programmers generally resist 1ug trac8ingG yet when used correctly it can really help a proBect! Pro1lems arenKt dropped on the *loor. Pro1lems are automatically routed to responsi1le individuals. The li*ecycle o* a pro1lem is trac8ed so people can argue 1ac8 and *orth with good in*ormation. )anagers can ma8e the 1ig schedule and sta**ing decisions 1ased on the num1er o* and types o* 1ugs in the system. Con*iguration management has a hope o* matching patches 1ac8 to the pro1lems they *iE. 5, and technical support have a communication medium with developers. ot seEy thingsG Bust good solid proBect improvements. Source code control should 1e lin8ed to the 1ug trac8ing system. During the part o* a proBect where source is *roMen 1e*ore a release only chec8ins accompanied 1y a valid 1ug <D should 1e accepted. ,nd when code is changed to *iE a 1ug the 1ug <D should 1e included in the chec8in comments. "onor Responsibilities Responsi1ility *or so*tware modules is scoped. )odules are either the responsi1ility o* a particular person or are common. Honor this division o* responsi1ility. DonKt go changing things that arenKt your responsi1ility to change. Anly mista8es and hard *eelings will result. Face itG i* you donKt own a piece o* code you canKt possi1ly 1e in a position to change it. ThereKs too much conteEt. ,ssumptions seemingly reasona1le to you may 1e totally wrong. <* you need a change simply as8 the responsi1le person to change it. Ar as8 them i* it is A? to ma8e such%n%such a change. <* they say A? then go aheadG otherwise holster your editor. 4very rule has eEceptions. <* itKs ' in the morning and you need to ma8e a change to ma8e a delivera1le then you have to do it. <* someone is on vacation and no one has 1een assigned their module then you have to do it. <* you ma8e changes in other peopleKs code try and use the same style they have adopted. Programmers need to mar8 with comments code that is particularly sensitive to change. <* code in one area requires changes to code in an another area then say so. <* changing data

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

'-

Coding Standard
*ormats will cause con*licts with persistent stores or remote message sending then say so. <* you are trying to minimiMe memory usage or achieve some other end then say so. everyone is as 1rilliant as you. The worst sin is to *lit through the system changing 1its o* code to match your coding style. <* someone isnKt coding to the standards then as8 them or as8 your manager to as8 them to code to the standards. Dse common courtesy. Code with common responsi1ility should 1e treated with care. Resist ma8ing radical changes as the con*licts will 1e hard to resolve. Put comments in the *ile on how the *ile should 1e eEtended so everyone will *ollow the same rules. Try and use a common structure in all common *iles so people donKt have to guess on where to *ind things and how to ma8e changes. Chec8in changes as soon as possi1le so con*licts donKt 1uild up. ,s an asideG module responsi1ilities must also 1e assigned *or 1ug trac8ing purposes. ot

08 P"P Code Tags


PHP Tags are used *or delimit PHP *rom html in a *ile. There are serval ways to do this. YIphp IJG YI IJG Yscript languageRHphpHJ Y7scriptJG Y\ \JG and YIRPnameIJ. Some o* these may 1e turned o** in your PHP settings. Dse YIphp IJ

3ustifi(ation YIphp IJ is always avalia1le in any system and setup.

E-ample YIphp print HHello worldHO IJ 77 @ill print HHello worldH YI print HHello worldHO IJ 77 @ill print HHello worldH Yscript languageRHphpHJ print HHello worldHO Y7scriptJ 77 @ill print HHello worldH Y\ print HHello worldHO \J 77 @ill print HHello worldH YIRPstreetIJ 77 @ill print the value o* the varia1le Pstreet

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

'.

Coding Standard
01 No ,agi( Numbers
, magic num1er is a 1are%na8ed num1er used in source code. <tKs magic 1ecause no%one has a clue what it means including the author inside ' months. For eEample! i* =## RR P*oo> : startNthermoNnuclearNwar=>O ; else i* ="$ RR P*oo> : re*undNlotsoNmoney=>O ; else i* ="/ RR P*oo> : in*initeNloop=>O ; else : cryNcauseNimNlost=>O ; <n the a1ove eEample what do ## and "$ meanI <* there was a num1er change or the num1ers were Bust plain wrong how would you 8nowI Heavy use o* magic num1ers mar8s a programmer as an amateur more than anything else. Such a programmer has never wor8ed in a team environment or has had to maintain code or they would never do such a thing. <nstead o* magic num1ers use a real name that means something. Fou should use de*ine=>. For eEample! de*ine=HPR4S<D4 TN@4 TNCR,CFHG H##H>O de*ine=H@4N6AAF4DHG H"$H>O de*ine=HTH4FND<D TNP,FHG H"/H>O i* =PR4S<D4 TN@4 TNCR,CF RR P*oo> : startNthermoNnuclearNwar=>O ; RR P*oo> : re*undNlotsoNmoney=>O ; RR P*oo> : in*initeNloop=>O ; : happyNdaysNiN8nowNwhyNimNhere=>O ;

else i* =@4N6AAF4D else i* =TH4FND<D TNP,F else ow isnKt that 1etterI

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

'/

Coding Standard
0! Thin vs' $at Class +nterfa(es
How many methods should an o1Bect haveI The right answer o* course is Bust the right amountG weKll call this the 6oldiloc8s level. 9ut what is the 6oldiloc8s levelI <t doesnKt eEist. Fou need to ma8e the right Budgment *or your situationG which is really what programmers are *or !%> The two eEtremes are thin classes versus thi(/ classes. Thin classes are minimalist classes. Thin classes have as *ew methods as possi1le. The eEpectation is users will derive their own class *rom the thin class adding any needed methods. @hile thin classes may seem HcleanH they really arenKt. Fou canKt do much with a thin class. <ts main purpose is setting up a type. Since thin classes have so little *unctionality many programmers in a proBect will create derived classes with everyone adding 1asically the same methods. This leads to code duplication and maintenance pro1lems which is part o* the reason we use o1Bects in the *irst place. The o1vious solution is to push methods up to the 1ase class. Push enough methods up to the 1ase class and you get thi(/ classes. Thic8 classes have a lot o* methods. <* you can thin8 o* it a thic8 class will have it. @hy is this a pro1lemI <t may not 1e. <* the methods are directly related to the class then thereKs no real pro1lem with the class containing them. The pro1lem is people get laMy and start adding methods to a class that are related to the class in some willow wispy wayG 1ut would 1e 1etter *actored out into another class. +udgment comes into play again. Thic8 classes have other pro1lems. ,s classes get larger they may 1ecome harder to understand. They also 1ecome harder to de1ug as interactions 1ecome less predicta1le. ,nd when a method is changed that you donKt use or care a1out your code will still have to 1e retestedG and rereleased.

www.einterviewquestions.com Coding Standard <ssue o. ! ".& <ssued Date ! "&%+ul%#&"'

'0