PHP Programming Standard (English Version) 2004-06-29 http://xjtusky.net/Article/Article.php/529
PHP Programming Standard (ENGLISH VERSION)
PHP Programming Standard (ENGLISH VERSION) Date: 2000-11-16 PHP programming standard is based on Todd Hoff, based on "C Programming Standard" for PHP, the author is Fredrik Kristiansen,
Use this standard if you want to copy a copy of your own use, it is completely free, this is why we make it. If you find any errors or any improvements, please send an email to the author so that the author will merge them to the latest update. table of Contents
Introduction
Standardized importance to explain the four stages of the identity point of view
Suitable name abbreviations Don't use your uppercase alphabet Name Class Library Name Method Named Class Properties Named Method Named Citup Variables and Functions Return to Reference Global Variable Definition Name / Global Constant Static Variable Function Name PHP File Extension Document Rule
Evaluation Comments Comments SHOULD TELL A Story Document Decisions Using Headers Description Make Gotchas Explicit Interface and Implementation Documentation Directory Document Complex Management Rule
Layering Open / Closed PrinciPle Design by Contract
DiffERENT Accessor Styles Don't do actual work in the object architecture Thin VS. FAT Class Interfaces Short Method Process Rules
Use a Design Notation and Process Using Use Cases Code Reviews Create a Source Code Control System Early and Not Often Create a Bug Tracking System Early and Not Often RCS keywords, change records and history formatting rules of Honor Responsibilities
Big bracket {} rules indent / tablet / space rules small parentheses, keywords and function rules If the ELSE format Switch format Continue, Break and? The use of each row a statement declaration block positioning popular mythology
Promise of OO miscellaneous
Don't be incredible NUMF Return Detection rules Do not use default values to test non-zero-worth Boolean logic types typically avoid embedded assignment reuse and other people's hard work use if (0) to comment Other miscellaneous
Introduction of the importance of standardization, standardization, let everyone headache in some respects, let people feel that everyone is in the same situation. This helps these recommendations continue to evolve in many projects, and many companies have spent many weeks to compete with the words. Standardization is not a special personal style, which is completely open to local improvement. Advantages When a project tries to comply with the public standard, there will be the following benefits:
The programmer can understand any code, and the case where the program can make new people can quickly adapt the environment to prevent the new contact of PHP from the need to save time, and to develop a living-ended habit to prevent new contact with PHP. Supreme mistakes In the consistent environment, people can reduce the chances of making mistakes have a consistent enemy :-) Disadvantages are now in the bad place:
Because the standard is made by some people who don't know PHP, the standard usually looks very stupid because the standard is different from me, so the standard usually looks very stupid standard to reduce the creativity standards in a long-term cooperation. The necessary standard forced too many formats In summary, people ignore the standard Discussion Many projects can draw this conclusion: Using programming standards can make the project more smoothly. Is the standard of success? of course not. But they can help us, and we need all the help we can get! Honestly, most of the arguments for a detail standard are mainly derived from their own ideas. A little decision to a reasonable standard can be said to be a lack of technical, that is just the reason for the taste. Therefore, to be flexible to control your own mind, remember, any project depends on the efforts of teamwork. Interpretation of the practice is referred to in this document that all items that use this specification need to comply with the prescribed standards. The role of using "should" is to guide the details of the project custom project. Because the project must be appropriately included, Exclude or Tailor requirement. The role of using "can" is similar to "should" because it indicates optional requirements. Standard implementation should first identify all the most important elements inside the development team, maybe standard is not appropriate for your situation. It may have already summarized an important issue, or some people have a strong opposition to some of them. No matter what circumstances, as long as the final is smooth, people understand that this standard is reasonable, then other programmers will find its rationality and feel that it is worthwhile to follow this standard. of. If there is no voluntary cooperation, you can make a demand: standard must pass the test. If there is no test, this solution is just a large group of funny people built on an inaccurate basis. I don't know this in the point of view; maybe it is possible, but it is neither practical and bored; this is true, and I also told you; this is what I thought first; it should be like this. If you look at things about things with your negative, please keep an open idea. You can still make it a nonsense conclusion, but how to conclude is that you have to be able to accept different ideas. Please give yourself a little time to do it. Four stages of the project
Database structure design data layer HTML layer
The right naming naming name naming is the core of the program plan. The ancients believe that just know that a real name will get an incredible force over the individual. As long as you think of the right name for things, you will bring you and later people to stronger than the code. Do not laugh! The name is a long and far-reaching result in the ecological environment it. Overall, only the programmer of the system can take the most appropriate name for the system. If all namings are suitable for nature, the relationship is clear, and the meaning can be derived, and the average person's idea can also be unexpected. If you find that your name is only a small amount that matches its corresponding things, it is best to look at your design. Class name
Let's first know what it is for class (Class) naming. If you can't afford this category, then your design is not good enough. More than three words consisting of mixed names are easy to confuse the system's individual entities, then look at your design, try to use (CRC SSION CARD) to see if the entity corresponding to the naming has so much function. The name of the derived class should avoid temptation to bring his parent class name, and a class name is only related to itself, and it is independent of its parent class. Sometimes it is useful, for example, if your system uses a proxy (agent), then name the part name "Download Agent" to real transmission information. Methods and function naming usually each method and function is executing a action, so what they are naming should be clearly explained: instead of ErrorCheck () with DumpDataTofile () with DumpDataTOfile (). This can also make functions and data into a more distinctive object. Sometimes the suffix name is useful:
MAX - Meaning the maximum value that can be given to an entity. CNT - The current value of a count variable in a run. Key - key value. For example: Retrymax represents the maximum number of retries, Retrycnt represents the current number of retries. Sometimes the preamble name is useful:
IS - meaning to ask a question about a sample. Whenever you see IS, you will know that this is a problem. GET - meaning is a value. SET - Meaning to set a value, for example: IshitRetrylimit. Necklement words don't use uppercase letters
In any case, when you encounter the following, you can use the surplus letter lowercase to replace all the usual-write letters. Use: gethtmlstatistic. Do not use: gethtmlstatistic. Reason
People seem to have a very different intuition when naming an acrony word. The unified provisions are the best, so that the meaning of naming is completely predicted. For an example of NetWorkabcKey, note that C should be C. C is still in Key in the ABC, which is very puzzled. Some people don't care about these, others are very annoying. So you will see different rules in different codes, making you don't know how to call it. For example, Class Fluidoz / / Don't write into a Fluidoz class gethtmlstatistic / / Don't write into gethtmlstatistic
Class name
Use uppercase letters as the word separation, other letters use lowercase names, do not use undertaking ('_') reasons
Based on a lot of naming methods, most people think this is the best way. For example, Class Nameonetwo Class Name
Class library name
The current naming space is increasingly adopted to avoid conflicts between different manufacturers and group libraries. When you have not used namespace, in order to avoid class conflicts, the general approach is to add a unique prefix before the class name, and two characters can be better. Of course, some will be better. For example, John Johnson's data structure class library can be used as a prefix with JJ, as follows: Class JjlinkList {}
Method naming
Rule reasons for use with class named
Most people who use all different rules have found this is the best compromise. For example Class Nameonetwo {function doit () {}; function handleError ()};
Class properties named
Attribute naming should prefix with character 'm'. The prefix 'm' is used in the rules of the class named. 'M' always modifies the beginning of the name, just like the beginning of 'R'. Reasons The prefix 'm' prevents class properties and method names. Your method name and attribute name are often similar, especially accessing elements. For example, Class NameOtherTwo {Function Varabc () {}; function errornumber () {}; var mvarabc; var mrname;
Name in the method
The first character uses lowercase letters. All words after the first character are capitalized in accordance with the class naming rules. reason
You can always know that variable corresponding to that variable. You can use the name similar to the class name and not to produce a researcher. For example, Class Nameonetwo {Function Startyouregines (& $ RSOMEENGINE, & $ RANOTHENGINE);
Variable name
All letters use lowercase use '_' as the boundary of each word. reason
With this way, the scope of the variable in the code is clear. All variables look different in the code, easy to identify. For example, Function HandleError ($ ErrorNumber) {$ error = oserr (); $ time_of_error = oserr-> gettimeoferror; $ error_processor = oserr-> getErrorProcessor;}
Reference variables and functions return reference
Quote must be with 'r' prefix
Make the variables that make the type easily identify which method returns to change objects, which method returns the object. For example Class test {var mrstatus; function dosomething (& $}) {}; function &} () {};
Global variable
The global variable should have a prefix 'g'. reason
It is very important to know the role of a variable. For example, Global $ GLOG; GLOBAL & $ GRLOG;
Define naming / global constant
The global constant separated each word with '_'. Reasons This is a tradition of naming global constants. Be careful not to conflict with other definitions. For example, Define ("A_Global_Constant", "Hello World!");
Static variable
Static variables should have a prefix 's'. reason
It is very important to know the role of a variable. For example, function test () {static $ msstatus = 0;}
Function name
The function name uses C GNU practices, all letters use lowercase letters, use the '_' segmentation words. reason
This makes it easier to distinguish between associated class names. Such as Function Some_bloody_function () {}
Error return detection rule
Check the error message for all system calls unless you want to ignore the error. Define system error text for each system error message so that INCLUDE.
Big bracket {} rules are within three main braces, there are two kinds of acceptable, as follows the best:
Place the braces under the same column below the keyword: if ($ condition) while ($ condition) {{...}} Traditional UNIX's parentheses rules are, first brackets and keywords, tail brackets Keywords: IF ($ condition) {while ($ condition) {...}}
The issue of non-principled discrimination can be solved by compromise, and any of two ways can be accepted, but for most people like the first one. The reason is something that psychologically study study areas. There are more reasons for more like the first kind. If you use the character editor to support parentheses (for example, VI), the most important thing is to have a good style. why? We said that when you have a large piece of program and want to know where this big program is over. You move forward to the starting parentheses, press the button editor to find the end parentheses, for example: if ($ VERY_LONG_CONDITION & SECOND_VERY_LONG_CONDITION) {...} else f (...) {...} Move from a block to another, you only need to match the cursor and your parentheses match button, you don't need to move back to the end to the line to find the matching parentheses. Ind retaining / tab / space rules
Use the tab to vent. Use three to four spaces to indent every level. It is no longer used as long as a method of replacing it is required. In the maximum number of indented layers, there is no fixed rule. If the number of indenges is greater than four or five layers, you can consider the factoring factoring (Factoring Out Code). reason
Many programmers support tab. Tabs Was Invented For A Rason will make the reading code very laborious when people use the tabular standards that differ greatly. Such a number is willing to limit the maximum number of indented layers, which usually has never been seen as a work. We believe that programmers will be wise to select the nesting depth. For example, function func () {if (aNother Thing Bad) {while (more input) {}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
Brand, keyword and function rules
Don't close the small brackets and keywords, you have to separate them with spaces. Don't close the parentheses and function names. Do not use parentheses in return returns in Return returns unless necessary. reason
Keywords are not functions. If parentheses close to function names and keywords, both are easy to be considered one. For example, if (condition) {} while (condition) {} strcmp ($ S, $ S1); RETURN 1;
RCS Keywords, Change Records, and History Rules The rules that directly use the RCS keyword must be changed, including the source code control system that supports RCS style keywords using CVS:
Don't use RCS keywords within your documents. Don't save history modifications records in your file. Don't save authors in your document. reason
The Reasoning is your source control system alleady keeps all this information. There is no reference to clutter Up Source Files with duplicate information That:
makes the files larger makes doing diffs difficult as non source code lines change makes the entry into the file dozens of lines lower in the file which makes a search or jump necessary for each file is easily available from the source code control system and does not need Embedding in The File When Files The Comments May Contain Internal Details That Should Not Be Exposed to Outsiders. Don't do actual work in the object architecture to do real work in the object architecture, initialization variables in architectural period And / or do something that will not have a mistake. When the object architecture is completed, an OPEN () method is established for the object, and the open () method should be named in an object entity. reason
The construct cannot return an error. For example, Class device {function device () {/ * Initialize and other stuff * /} function open () {return fail;}}; $ dev = new device; if (fail == $ dev-> open ()) EXIT () exit 1);
If thein else format layout This is determined by the programmer. Different curly parenthesis patterns will have some different samples. A general way: if (condition 1) // Note {} else if (condition 2) // Note {} else // Note {} If you use the else if statement, it usually has an else block for use Other situations that have not been processed are processed. If you can put a record information comment at else, even in Else doesn't have any action. The conditional format always puts the constant to the left side of the equal number / do not equal, for example: if (6 == $ error) ... one reason is that if you are leaking a equal sign in the equation, the syntax checkter will report to you. . The second reason is that you can find a value immediately instead of finding it at the end of your expression. It takes a little time to habits this format, but it is really useful.
Switch format
Falling Throgh A Case Statement INTO The Next Case Statement Shall Be Permitted As long as a comment is incompaded. Default case should always exist, it should not be reached, however it triggers an error if it reaches it. If you want to create a variable, put all the code in the block. For example, Switch (...) {Case 1: ... // Fall Through Case 2: {$ V = get_week_number (); ...} Break; default:}
Continue, Break, and • Continue and Break Continue and Break are actually a hidden GOTO method. Continue and Break are like goto, they have magic in the code, so you have to use them with you (as little as possible). This simple magic is used, and the reader will be oriented to only God know because of some undisclosed reasons. Continue has two main issues:
It can bypass test conditions. It can bypass the like / unequal expressions. Take a look at the example below, consider where there is a problem: while (true) {... // a lot of code ... if (/ * some condition * /) {Continue;} ... // a Lot of code ... if ($ i > stop_value) Break;} Note: "a lot of code" is required, this is to make programmers can't find errors so easy. Through the above example, we can draw a further rule: Continue and Break mixing are the correct way to cause disasters. ?: The trouble is that the people often try it? He is full of many code. The following is some clear connection rules: put the conditions in parentheses to separate it from other code. If possible, the action can use a simple function. Place the action, "?", ":" In different rows, unless they can be clearly placed in the same line. For example (condition)? Funct1 (): func2 (); or (condition)? Long statement: another long stat;
Declaration block
The declaration code block needs to be aligned. Justification
Clear. A variable initialized similar code block should list. THE? TOKEN SHOULD BE Adjacent to the Type, NOT The Name., Var $ MDATE VAR & $ MNAME $ MDATE = 0; $ mrdate = null; $ mRName = 0; $ mname = NULL;
Each row is a statement unless these statements have very close contact, otherwise only one statement is written.
Short method
Method code should be limited to one page. reason
This idea is that each method represents a technology that completes a separate purpose. In the long run, excessive invalid parameters are wrong. The calling function is slower than the call, but this requires a decision to make a decision (see Premature Optimization is not perfect).
Record all empty statements always record for the blank sprite statement to clearly know that the code is missing, or not to write. While ($ DEST = $ SRC ); // void
Do not test the default method to test the non-zero value, do not use the default value to test the non-zero value, which is: if (fail! = F ()) better than the following method: if (f ()) even if Fail can contain 0 values That is, PHP thinks that FALSE is expressed. When someone decides to use -1 instead of 0 as a failure return value, an explicit test can help you. Even if the value does not change, it should also use an explicit comparison; for example: if (! ($ Bufsize% strlen))) should be written: IF (($ bufsize% strlen) == 0) Taking the value (not a Boolean) type tested. A regular problem is to use strcmp to test a character equation, and the result will never be equal to the default. Non-zero testing uses default-to-value practices, then other functions or expressions are subject to the following limitations:
Can only return 0 to fail, and cannot be / other values. Naming so that a true return value is absolutely obtable, calling a function isvalid () instead of Checkvalid ().
Boolean logic type Most functions return 0 when False, but the non-0 value represents True, so do not use 1 (True, Yes, such as this), etc., should be detected by 0 (False, NO, etc.) The inequality is instead: if (true == func ()) {... should be written: if (false! = Func ()) {... usually avoid embedded assignments Sometimes we can see in some places. Embedded assignment statements, those structures are not a relatively good less redundant, a highly readable method. While ($ A! = ($ c = getchar ())) {process the character} and - operator Similar to assignment statements. Therefore, for many purposes, side effects are generated when using functions. It is possible to use embedded assignments to improve runtime performance. In any case, programmers need to consider weighing between growth and reduced maintainability when using embedded assignment statements. For example: A = B C; D = A R; do not write: D = (a = b c) R; although the latter can save a cycle. However, in the long run, as the maintenance cost of the program grows, the writer of the program gradually forgotten the code, and will reduce the optimization of maturity.
Reusing you and other people's hard work across engineering reuse is almost impossible without a universal structure. Objects meet their existing service needs, different processes have different service demand environment, which makes object reuse difficult. Developing a general structure requires a lot of effort to design. When the effort is unsuccessful, there are several ways to recommend using: ask! It is rarely used by email for group groups. Because some of the programmers feel that if he helps others, it will look low level, this is more stupid! Do a new and interesting job, don't make someone else have done it over again. If you need some of the source code for some matter, if you already have someone else, email helps to the group. The result will be very surprised! In many large groups, individuals often don't know what others are doing. You can even find someone to do something, and voluntarily write code, if people work together, there is always a gold mine. tell! When you do things, tell everyone that if you have done anything reusable, let others know. Don't be shy, don't hide your work in order to protect your pride. Once the habit of sharing the results of sharing work, everyone will get more. Don't Be Afraid of Small Libraries is reused, a common problem is that people don't make libraries from their code. A reusable class may be hidden in a program directory and will never have shared excitement, because the programmer does not split the class into the library. One of this reason is that people don't like to be a small library, and there are some incorrect feelings for the small library. Overcome such a feeling, the computer doesn't care how many libraries do you have. If you have some code to be reused, and you can't put it in an existing library, you will be a new library. If people really consider reuse, the library will not be so small in a long time.
If you are afraid of having to update makefiles when libraries are recomposed or added then do not include libraries in your makefiles, include the idea of services. Base level makefiles define services that are each composed of a set of libraries. Higher level makefiles specify the services they want. When the libraries for a service change only the lower level makefiles will have to change. Keep a Repository Most companies have no idea what code they have. And most programmers still do not communicate what they have done or ask for what currently exists. The solution is to keep a repository of what's available. In an ideal world a programmer could go to a web page, browse or search a list of packaged libraries, taking what they need. If you can set up such a system where programmers voluntarily maintain such a system, great. If you have a librarian in charge of detecting reusability, even better. Another approach is to automatically generate a repository from the source code. This is Done by Using Common Class, Method, Library, And Subsystem Headers That Can Double Asman Pages and repository entries.
Evaluation comments Comments should be a story Consider your comments a story describing the system. Expect your comments to be extracted by a robot and formed into a man page. Class comments are one part of the story, method signature comments are another part of the story, method arguments another part, and method implementation yet another part. All these parts should weave together and inform someone else at another point of time just exactly what you did and why. Document Decisions Comments should document decisions. At every point where you had A Choice of What To Do Place A Comment Describing Which Choice You Made and why. Archeologists Will Find this The MOST USEFUL INFORMATION. Using the header description using a document extraction system similar to CCDOC. Other parts of this document describe how to use CCDOC to record a class and method. These header descriptions can be extracted and analyzed in such a way that they are not useless as in the general header. So spend time to fill in him. Each part of the annotation layout project has a specific annotation layout. Make Gotchas Explicit Explicitly comment variables changed out of the normal control flow or other code likely to break during maintenance. Embedded keywords are used to point out issues and potential problems. Consider a robot will parse your comments looking for keywords, stripping them out, and Making a report so people
: Todo: Topicmeans There's More To Do Here, Don't forget.: Bug: [bugid] Topicmeans There's a known bug here explain how you would do it differently next time if you had more time:. TRICKY: Tells somebody that the following code is very tricky so do not go changing it without thinking:. WARNING: Beware of something:. PHARSER: Sometimes you need .. to work around a pharser problem Document it The problem may go away eventually:. aTTRIBUTE: valueThe general form of an attribute embedded in a comment You can make up your own attributes and they'll be extracted gotcha FormattingMake the gotcha keyword.. the first symbol in the comment. Comments may consist of multiple lines, but the first line should be a self-containing, meaningful summary. The writer's name and the date of the remark should be part of the comment. This information is in the source Repository, But it can take a quite a while to f ... Ind out when and by whom it was added Often gotchas stick around longer than they should Embedding date information allows other programmer to make this decision Embedding who information lets us know who to ask Example //:. TODO: tmh 960810: possible Performance problem /// weed real, us........................... IT Should // Probably Use a Virtual Method or Template. See Also See Interface and Implementation Documentation for More Details on How Documentation Should Be Laid Out.
Interface and Implementation Documentation There are two main audiences for documentation:. Class Users Class Implementors With a little forethought we can extract both types of documentation directly from source code Class Users Class users need class interface information which when structured correctly can be extracted directly from a header file. When filling out the header comment blocks for a class, only include information needed by programmers who use the class. Do not delve into algorithm implementation details unless the details are needed by a user of the class. Consider comments in a header file a man page in waiting. class Implementors class implementors require in-depth knowledge of how a class is implemented. This comment type is found in the source file (s) implementing a class. Do not worry about interface issues. Header comment blocks In a Source File Should Cover Algorithm Issues and Other Design Decisions. Comment Blocks Withnin A Method's Implementation SHOULD EXPLAIN E Ven more.
The readme document is required in all directories of the directory document, including:
The functionality of this directory and it contains the content a pair of online instructions for each file (with link), each description, usually, should also extract some of the attribute names of the file header. Including settings, instructions how to connect people to how resources:
Source file Index Online document paper document Design document other for readers Help things, when each original engineering is gone, a newcomer who came within 6 months, the lonely scared explorer passed the whole The project source code directory tree, reading instruction file, header description of the source file, etc., he should have the ability to cross the entire project.
Use a Design Notation and Process Programmers need to have a common language for talking about coding, designs, and the software process in general. This is critical to project success. Any project brings together people of widely varying skills, knowledge, and experience. Even if everyone on a project is a genius you will still fail because people will endlessly talk past each other because there is no common language and processes binding the project together. All you'll get is massive fights, burnout, and little progress. If you send your group to training they may not come back seasoned experts but at least your group will all be on the same page;.. a team there are many popular methodologies out there The point is to do some research, pick a method, train your people on it, and use it. Take a look at the top of this page for links to various methodologies. You may find the CRC (class responsibility cards) approach to teasing out a design useful. Many others have. It is an informal Approach Encouraging Team Cooperation and Focusing On Objects Doing Things Rather Than Objects Having Attributes. There's Even A WHOLOK ON IT: USING CRC CARDS BY NANCY M. WILKINSON.
Using Use Cases A use case is a generic description of an entire transaction involving several objects. A use case can also describe the behaviour of a set of objects, such as an organization. A use case model thus presents a collection of use cases and is typically used to specify the behavior of a whole application system together with one or more external actors that interact with the system. An individual use case may have a name (although it is typically not a simple name). Its meaning is often written as an informal text description of the external actors and the sequences of events between objects that make up the transaction. use cases can include other use cases as part of their behaviour. requirements Capture use cases attempt to capture the requirements for a system in an understandable form. The idea is by Running Through a set of use case we can verify That The system is doing what it would doing. Have been as a sale what a system neseds to account mplish. The ProcessStart by understanding the system you are trying to build. Create a set of use cases describing how the system is to be used by all its different audiences. Create a class and object model for the system. Run through all the use cases TO Make Sure Your Model CAN Handle All The Case. Update Your Model and Create New Use Cases As Necessary.
Open / closed PrinciPle The Open / CLOSED PrinciPle States a class must be open and close::
open means a class has the ability to be extended. closed means a class is closed for modifications other than extension. The idea is once a class has been approved for use having gone through code reviews, unit tests, and other qualifying procedures, you don 't want to change the class very much, just extend it. The Open / Closed principle is a pitch for stability. A system is extended by adding new code not changing already working code. Programmers often do not feel comfortable changing old code by because it works! This principle just gives you an academic sounding justification for your fears :-) In practice the Open / Closed principle simply means making good use of our old friends abstraction and polymorphism. Abstraction to factor out common processes and ideas. Inheritance to Create an interface truth mustage to by contract the idea of design by Contract IS STRONGLED TO LSP. A Contract IS A FORMAL STATEMENT OF What to EXPECT FROMAL PART y. In this case the contract is between pieces of code. An object and / or method states that it does X and you are supposed to believe it. For example, when you ask an object for its volume that's what you should get. And because volume is a verifiable attribute of a thing you could run a series of checks to verify volume is correct, that is, it satisfies its contract. The contract is enforced in languages like Eiffel by pre and post condition statements that are actually part of the language. In other languages a bit of faith is needed. Design by contract when coupled with language based verification mechanisms is a very powerful idea. It makes programming more like assembling spec'd parts.
This part of other miscellaneous items contains a variety of and should not do.
Do not use floating point variables in need to use discrete values. The cyclic counter is not distressed to the foot of your foot. You always use <= or => when you test the floating point number, never use = or =>. Don't use the program automatic beautifier, the main person who benefits from a good program style is the programmer himself, especially the programmer who just opened the code, the algorithm design, using the program automatic beautifier can only be corrected according to the syntax, so It is impossible when there is a big need for gap and indent attention. Normal carefully payment details can use a clear and intuitive style to complete a function or document (in other words, some intuitive style is intentional instead of the intelligence of the program automatic beautifier can read ). Majoo programmers should learn detailed programmers, do not rely on program automatic beautifiers to increase program readability. The initial beautifier is a program that must analyze source code. The complex beautifier is not worthy of this benefit, the beautifier is best used to generate the total machine establishment (Machine-generated) format code. The second = accidentally ignored ignor is a problem, and the following is chaotic and more like an error: if ($ abool = $ bbool) {...} The programmer is really to assign a value? Generally, it is usually not the case. This avoids causing such confusion? The solution is not to do this, use explicit and implicit judgment tests, the recommended method is to assign a value before doing test: $ abool = $ bbool; if ($ abool) {...} Using IF (0) To comment the external code block sometimes need to comment the test code of the large segment, the simplest method is to use if (0): function example () {great looking code if (0) {LOTS of code} more code} You cannot use / ** / because the inside of the comment cannot contain a comment, while the large segment can contain comments, isn't it?
Different Accessor Styles Why Accessors? Access methods provide access to the physical or logical attributes of an object. We disallow direct access to attributes to break dependencies, the reason we do most things. Directly accessing an attribute exposes implementation details about the object. To see Why ask yourself:
What if the object decided to provide the attribute in a way other than physical containment? What if it had to do a database lookup for the attribute? What if a different object now contained the attribute? If any of the above changed code would break. An object makes a contract with the user to provide access to a particular attribute;... it should not promise how it gets those attributes Accessing a physical attribute makes such a promise Implementing accessors There are three major idioms for creating accessors Get / Set class X {Function Getage () {RETURN $ THIS-> Mage; Function Setage ($ MAGE;)} Var $ MAGE;} ONE Method Name Class x {function age () {return $ max function Age ($ age) {$ mAge = $ age;} var $ mAge;.} Similar to Get / Set but cleaner Use this approach when not using the Attributes as Objects approach Attributes as Objects class X {function Age () {. Return $ MAGE;} Function Rage () {Return Mname () {r eturn & $ mName;} var $ mAge; var $ mName;} X $ x; $ x-> rName () = "test";. The above two attribute examples shows the strength and weakness of the Attributes as Objects approach When using rAge (), which is not a real object, the variable is set directly because rAge () returns a reference. The object can do no checking of the value or do any representation reformatting. For many simple attributes, however, these are not horrible RESTRICTIONS.
Layering Layering is the primary technique for reducing complexity in a system. A system should be divided into layers. Layers should communicate between adjacent layers using well defined interfaces. When a layer uses a non-adjacent layer then a layering violation has occurred. A layering violation simply means we have dependency between layers that is not controlled by a well defined interface. When one of the layers changes code could break. We do not want code to break so we want layers to work only with other adjacent layers. Sometimes we NEED TO JUMP LAYERS for Performance Reasons. This is Fine, But We Should Know We are doing it and document appropriately.
Code Reviews If you can make a formal code review work then my hat is off to you. Code reviews can be very useful. Unfortunately they often degrade into nit picking sessions and endless arguments about silly things. They also tend to take a lot of people's time for a questionable payback. My god he's questioning code reviews, he's not an engineer! Not really, it's the form of code reviews and how they fit into normally late chaotic projects is what is being questioned. First, code reviews are way too late to do much of anything useful. What needs reviewing are requirements and design. This is where you will get more bang for the buck. Get all relevant people in a room. Lock them in. Go over the class design and requirements until the former is good and the latter is being met. Having all the relevant people in the room makes this process a deep fruitful one as questions can be immediately answered and issues immediately explored. Usually only a couple of such meetings are necessary. If the above process is done well coding will take care of itself. If you find problems in the code review the best you can usually do is a rewrite after someone has sunk a ton of time and effort into making the code "work." You will still want to do a code review, just do it offline. Have a couple people you trust read the code in question and simply make comments to the programmer. Then the programmer and reviewers can discuss issues and work them out. Email and quick pointed discussions Work Well. this approach meets the Goals and Doesn't Take The Time of 6 People to Do IT.
Create a Source Code Control System Early and Not Often A common build system and source code control system should be put in place as early as possible in a project's lifecycle, preferably before anyone starts coding. Source code control is the structural glue binding a project together . If programmers can not easily use each other's products then you'll never be able to make a good reproducible build and people will piss away a lot of time. It's also hell converting rogue build environments to a standard system. But it seems the right of passage for every project to build their own custom environment that never quite works right Some issues to keep in mind:... Shared source environments like CVS usually work best in largish projects If you use CVS use a reference tree approach With this approach A Master Build Tree Is Kept Of Various Builds. Program of Various CHECKOUT SOURCE AGAINST The Build The isy................................................................................................................................................................................... thing not found locally. Using the -I and -L flags makes this system easy to setup. Search locally for any files and libraries then search in the reference build. This approach saves on disk space and build time. Get a lot of disk space . With disk space as cheap it is there is no building .. make Simple things simple. It Should Be Dead Simple and Well Documented on now:
check out modules to build how to change files how to add new modules into the system how to delete modules and files how to check in changes what are the available libraries and include files how to get the build environment including all compilers and other tools Make a web page or document or whatever. New programmers should not have to go around begging for build secrets from the old timers. On checkins log comments should be useful. These comments should be collected every night and sent to interested parties. Sources If you have the money many projects have found Clear Case a good system. Perfectly workable systems have been build on top of GNU make and CVS. CVS is a freeware build environment built on top of RCS. Its main difference from RCS is that is supports a shared file MODEL TO BUILDING SOFTWARE.CREATE A BUG TRATION SYSTEM EARLY AND NOTETEN THE EARLIER PEOPLE GET Used to Using A Bug Tracking System The Better. if Are 3/4 THROUGH A Project and The Install A Bug Tr Acking System It Won't be used. You NEED TO Install A Bug TRACKING System Early So People Will Use It. Programmers Generally Resistly It Can Really Help A Project:
Problems are not dropped on the floor. Problems are automatically routed to responsible individuals. The lifecycle of a problem is tracked so people can argue back and forth with good information. Managers can make the big schedule and staffing decisions based on the number of and types of bugs in the system. Configuration management has a hope of matching patches back to the problems they fix. QA and technical support have a communication medium with developers. Not sexy things, just good solid project improvements. FYI, it's not a good idea to reward people by the number of bugs they fix :-) Source code control should be linked to the bug tracking system. During the part of a project where source is frozen before a release only checkins accompanied by a valid bug ID should be accepted. And when code is change to fix one bug id shop. Sources Several Projects Have Found Ddts a Workable System (i 'VE NOT VERIFIED This Link for this PHP RELEAS e, DDTS May Not Work for PHP. There is Also A GNU Bug Tracking System Available. Roll Your OWN Is A Popular Option But Use An Existing System Seem More Cost Effic.
Honor Responsibilities Responsibility for software modules is scoped. Modules are either the responsibility of a particular person or are common. Honor this division of responsibility. Do not go changing things that are not your responsibility to change. Only mistakes and hard feelings will result . Face it, if you do not own a piece of code you can not possibly be in a position to change it. There's too much context. Assumptions seemingly reasonable to you may be totally wrong. If you need a change simply ask the responsible person to change it. Or ask them if it is OK to make such-n-such a change. If they say OK then go ahead, otherwise holster your editor. Every rule has exceptions. If it's 3 in the morning and you need to make a change to make a deliverable then you have to do it. If someone is on vacation and no one has been assigned their module then you have to do it. If you make changes in other people's code try and use the same style they Have Adopted. Programmers Need To Mark with comments code that is particularly sensitive to change. If code in one area requires changes to code in an another area then say so. If changing data formats will cause conflicts with persistent stores or remote message sending then say so. If you are trying to minimize Memory usage or achieve some other end. NOT EVERYONE IS BRILLIANT As You. The Worst Sin Is To Flit Through The System Changing Bits of Code To Match Your Coding Style. if someone ISN '
t coding to the standards then ask them or ask your manager to ask them to code to the standards. Use common courtesy. Code with common responsibility should be treated with care. Resist making radical changes as the conflicts will be hard to resolve. Put comments in the file on how the file should be extended so everyone will follow the same rules. Try and use a common structure in all common files so people do not have to guess on where to find things and how to make changes. Checkin changes as Soon as Possible So Conflicts Don't build up. as an aside, module responsibilities Must Also Be Assigned for bug tracking purposes.php file extension I have seen many PHP file extensions (.html, .php, .php3, .php4, .phtml, .inc, .class ...)
All viewers can see the page using .html all classes, library files use .php
The extension describes that data is that the user will receive. PHP is explained to HTML.
Don't be incredible, a naked number used in the source code is an incredible number, because including the author, within three months, no one has its meaning. For example: if (22 == $ foo) {start_thermo_nuclear_war ();} else if (19 == $ foo) {refund_lotso_money ();} else if (16 == $ foo) {infinite_loop ();} else {CRY_CAUSE_IM_LOST )} What is the meaning of 22 and 19 in the previous example? If a number changes, or these numbers are just simple errors, what do you think? Using an incredible number is an important sign of the programmer is an amateur athlete. Such a programmer has never worked in a team environment, or to maintain code, otherwise they will never do such a thing. You should use define () to show you a real name of the value of something, rather than adopting naked numbers, for example: define ("President_Went_Crazy", "22"); Define ("We_Goofed", "19" ); define ( "THEY_DIDNT_PAY", "16"); if (PRESIDENT_WENT_CRAZY == $ foo) {start_thermo_nuclear_war ();} else if (WE_GOOFED == $ foo) {refund_lotso_money ();} else if (THEY_DIDNT_PAY == $ foo ) {infinite_loop ();} else {happy_days_i_know_why_im_here ();} Isn't it better now?
Promise of OO OO has been hyped to the extent you'd figure it would solve world hunger and usher in a new era of world peace. Not! OO is an approach, a philosophy, it's not a recipe which blindly followed yields quality. Robert martin put OO in perspective: OO, when properly employed, does enhance the reusability of software But it does so at the cost of complexity and design time Reusable code is more complex and takes longer to design and implement Furthermore, it often takes... two or more tries to create something that is even marginally reusable. OO, when properly employed, does enhance the software's resilience to change. But it does so at the cost of complexity and design time. This trade off is almost always a win, but it is hard to swallow sometimes. OO does not necessarily make anything easier to understand. There is no magical mapping between the software concepts and every human's map of the real world. Every person is different. What one person percieves to be a simple and elegant design, another will perceive as convoluted and opaque. If a team has been able, by applying point 1 above, to create a repository of reusable items, then development times can begin to shrink significantly due to reuse. If a team has been able , by Applying Point 2 Above, To Create Software That Is Resilient To change, The Maintenance of That Software Will Be Much Simpler and Much Less Error Prone.
Thin vs. Fat Class Interfaces How many methods should an object have? The right answer of course is just the right amount, we'll call this the Goldilocks level. But what is the Goldilocks level? It does not exist. You need to make the right judgment for your situation, which is really what programmers are for :-) The two extremes are thin classes versus thick classes. Thin classes are minimalist classes. Thin classes have as few methods as possible. The expectation is users will derive their own class from the thin class adding any needed methods. While thin classes may seem "clean" they really are not. You can not do much with a thin class. Its main purpose is setting up a type. Since thin classes have so little functionality many programmers in a project will create derived classes with everyone adding basically the same methods. This leads to code duplication and maintenance problems which is part of the reason we use objects in the first place. The obvious solution is to push methods u Push ENOUGH Methods Up to the base class and you get thick classes. thick classes Have a lot of methods. if you can think of it. why is this a problem? it May not Be. if the methods area directly related to the class kiln there
s no real problem with the class containing them. The problem is people get lazy and start adding methods to a class that are related to the class in some willow wispy way, but would be better factored out into another class. Judgment comes into play again . Thick classes have other problems. As classes get larger they may become harder to understand. They also become harder to debug as interactions become less predictable. And when a method is changed that you do not use or care about your code will still have To be rasted, and recrelesed.recent changes
2000-11-16. RELEASE
Copyright 1995-2000. Todd Hoff and Fredrik Kristiansen. All Rights Reserved.