Best practices tekx

Embed Size (px)

DESCRIPTION

Tutorial delivered by Matthew Weier O'Phinney and Lorna Mitchell at TEK-X in Chicago, May 2010

Citation preview

  • 1. Best Practices Matthew Weier O'Phinney Zend Framework Lorna Jane Mitchell Ibuildings @lornajane @weierophinney

2. The Plan

  • Source Control

3. Coding Standards 4. Design Patterns 5. Documentation 6. Testing 7. Quality and Continuous Integration 8. Deployment 9. Source Control 10. Source Control Features

  • Version history of all files

11. Collaboration tool 12. Authoritative version of a project 13. Integration point 14. Using Source Control

  • Create a repository, add project

15. Check out project 16. Make changes 17. Update to get other changes 18. Commit changes to repo 19. svn log ------------------------------------------------------------------------ r3 | lornajane | 2010-04-25 10:32:09 +0100 (Sun, 25 Apr 2010) | 1 line adding documentation notes ------------------------------------------------------------------------ r2 | lornajane | 2010-04-22 09:07:56 +0100 (Thu, 22 Apr 2010) | 1 line outlining source control and design patterns sections ------------------------------------------------------------------------ r1 | weierophinney | 2010-03-30 17:37:27 +0100 (Tue, 30 Mar 2010) | 1 line Added readme with outline ------------------------------------------------------------------------ 20. svn diff Index: README.txt =================================================================== --- README.txt(revision 3) +++ README.txt(revision 4) @@ -31,12 +35,20 @@ to share ideas to raise profile to be told you're doing it wrong! +(pulling up examples off our own blogs, if connection allows) Testing (Matthew) QA tools and CI including code analysis, mess detection, etc (Lorna - QA tools; Matthew - CI) +Static analysis +code sniffer +demo examples, find a suitable small codebase (joindin?) +mess detector +demo examples +what else? + Deployment 21. Source Control Tools

  • Subversion (svn)
  • http://subversion.apache.org/

Git (git)

  • http://git-scm.com/

Bazaar (bzr)

  • http://bazaar.canonical.com/

Mercurial (hg)

  • http://mercurial.selenic.com/

22. Accessing Source Control

  • IDE Plugins

23. Trac ( http://trac.edgewall.org/ ) 24. TortoiseSVN

  • TortoiseGit

25. TortoiseBzr 26. TortoiseHg 27. Centralised Source Control user repo user user user 28. Centralised Source Control

  • Single repo (repository)

29. Always commit to central 30. Can branch centrally 31. Repository Structure (Feature Branches) 32. Repository Structure (Long-Lived Branches) 33. Repository Structure (Release Branches) 34. Distributed Source Control repo repo repo repo repo 35. Distributed Source Control

  • Many repos

36. Commit to local repo 37. Share changes between anywhere 38. No central point 39. The Changing Landscape

  • Very active development area

40. Today's conclusions not valid for long! 41. Bridges

  • git-svn
  • http://www.kernel.org/pub/software/scm/git/docs/git-svn.html

bzr-svn

  • https://launchpad.net/bzr-svn

Check out from SVN to local repo 42. Make as many changes/branches as you like 43. Push back to SVN 44. Hosted Solutions GitHub http://github.com/ git Bitbucket http://bitbucket.org/ hg Google Code http://code.google.com/ svn, hg Launchpad https://launchpad.net/ bzr SourceForge http://sourceforge.net/ svn, bzr, hg, git (and cvs) 45. What If I Don't Have Source Control?

  • Get some :)

46. Install subversion 47. Use a hosted solution 48. Resources

  • Talks at TEK-X
  • Subversion in a Distributed World, Lorna Mitchell

49. Getting Git, Travis Swicegood (who literally wrote the book) 50. Both Wednesday afternoon Subversion book

  • http://svnbook.red-bean.com/

Comparison of tools

  • http://en.wikipedia.org/wiki/Comparison_of_revision_control_software

51. Coding Standards 52. You don't have a standard when

  • You always reformat code you get from others

53. Code you wrote 6 months ago looks different than what you wrote today 54. Modifying old code often introduces new syntax errors 55. Answer the following questions:

  • Can you read your own code?

56. Can others read your code? 57. Can you read other's code? 58. Can you switch between code bases easily? 59. Analogy "Elements of Style" :: Writing Coding Standard :: Development 60. In sum, coding standards assist in:

  • Maintainability

61. Collaboration 62. How CS aids maintainability: Code is structured predictably 63. How CS aids collaboration

  • Any developer can pick up and easily read existing code

64. which in turn means they can maintain it 65. which de-centralizes who is responsible for the code 66. which means issues and reature requests are resolved faster 67. Itdemocratizescode maintenance 68. Two pillars of a Coding Standard:

  • Consistency offile systemlayout

69. Consistency ofcodelayout 70. Ancillary goal:

  • Consistency in naming

71. Use Public Standards

  • NIH has no place with CS
  • You and your project's needs are not unique

72. What if you need to consume and potentially help maintain 3rd party libraries? 73. Benefit from collective knowledge and empirical discoveries 74. Need more reasons?

  • Objectivity
  • Choices are no longer based on subjective preferences, but on empirical experience.

Requirement when hiring or outsourcing

  • Easily judge the candidate's experience and code quality.

Compatibility

  • Use a standard that follows that of the libraries you use.

75. Choices

  • Horde/PEAR/Zend Framework
  • Also: Solar, AdoDB, Doctrine 2, Symfony 2, and more...

eZcomponents/ZetaComponents 76. PHPLIB 77. Example leaf'); 192. Create assertions indicating the expected results $this->assertEquals("//child/leaf", $test); 193. How to test

  • Run the tests
  • Success?Move on to the next behavior

194. Failure?

  • Check your test assumptions and assertions

195. Check your code and correct it 196. Re-run the tests to verify 197. Other Testing Topics

  • Test Doubles
  • Stubs Replacing an object with another so that the system under test can continue down a path.

198. Mock Objects Replacing an object with another and defining expectations for it. 199. Other Testing Topics

  • Test Coverage What lines were executed, and how many times?

200. Conditional tests Testing only when certain environmental conditions are met. 201. Functional and Integration tests Testing that the systems a unit interacts with all respond as expected. 202. Adding tests to existing,untested projects

  • Create tests:
  • Whenever you introduce new features, for those features

203. Whenever you attempt to fix a bug

  • Capture the desired behavior in a unit test

204. Fix the bug Whenever you refactor 205. Test-Driven Development

  • Capture behaviors individually and iteratively in unit tests

206. Write code to make the tests pass 207. Allows for playing with APIs before you've committed to coding them 208. Often hard to get into the rhythm; once you do, often hard to quit 209. Takeaways

  • Testing is easy

classCss2XpathTestextendsPHPUnit_Framework_TestCase { public function testShouldAllowWSInDescendentSctrExpressions() { $test = Css2Xpath::transform( 'child > leaf' ); $this ->assertEquals( "//child/leaf" , $test ); } } 210. Takeaways

  • Test whenever you can -- preferablyALWAYS

211. Automate your test suite (next topic!) 212. Quality and CI 213. Static Analysis

  • Analysing code without execution

214. Evaluating code properties and patterns 215. Common tools

  • Lines of code ( http://github.com/sebastianbergmann/phploc )

216. Code sniffer ( http://pear.php.net/PHP_CodeSniffer ) 217. Mess detector ( http://phpmd.org/ ) 218. Lines of Code

  • Born from PHPUnit

219. Available via PHPUnit's PEAR channel 220. Shows lots of stats about a codebase 221. Methods, lines per method 222. Cyclomatic complexity: a measure of branching points in code 223. E.g. when applied to wordpress: 224. Lines of Code Example * phploc 1.3.2 by Sebastian Bergmann. Directories:29 Files:295 Lines of Code (LOC):138661 Cyclomatic Complexity / Lines of Code:0.19 Comment Lines of Code (CLOC):43498 Non-Comment Lines of Code (NCLOC):95163 * example fromhttp://techportal.ibuildings.com/2010/01/28/phploc-php-lines-of-code/ 225. Lines of Code Example Interfaces:0 Classes:168 Abstract:0 (0.00%) Concrete:168 (100.00%) Lines of Code / Number of Classes:377 Methods:1973 Scope: Non-Static:1972 (99.95%) Static:1 (0.05%) Visibility: Public:1964 (99.54%) Non-Public:9 (0.46%) Lines of Code / Number of Methods:32 Cyclomatic Complexity / Number of Methods:5.44 Functions:1599 Constants:272 Global constants:272 Class constants:0 226. Code Sniffer

  • Associated with coding standards

227. Configurable "sniffs" to look for different properties 228. Code Sniffer Example * 1< ?php 23class recipe 4{ 56protected $_id ; 78public $name ; 910public $prep_time ; 1112function getIngredients () { 13$ingredients = Ingredients :: fetchAllById ( $this -> _id ); 14return $ingredients ; 15} 16} * example from http://techportal.ibuildings.com/2009/10/12/usphp_code_sniffer/ 229. Code Sniffer Example FILE: /home/lorna/phpcs/recipe.php ------------------------------------------------------------------- FOUND 8 ERROR(S) AND 0 WARNING(S) AFFECTING 5 LINE(S) ------------------------------------------------------------------- 2 | ERROR | Missing file doc comment 3 | ERROR | Class name must begin with a capital letter 3 | ERROR | Missing class doc comment 6 | ERROR | Protected member variable "_id" must not be prefixed|| with an underscore 12 | ERROR | Missing function doc comment 12 | ERROR | Opening brace should be on a new line 13 | ERROR | Line indented incorrectly; expected at least 8|| spaces, found 1 13 | ERROR | Spaces must be used to indent lines; tabs are not|| allowed ------------------------------------------------------------------- output of running recipe.php through PEAR sniffs 230. Mess Detector

  • Uses some "rule of thumb" metrics

231. Tells you about the codebase, at a macro level 232. Can catch

  • long class/method names and parametere lists

233. complex code 234. classes with too many public methods 235. other "bad smells" Under development 236. Continuous Integration (CI) 237. Continu what?

  • Originally, automated build systems for compiled languages

238. Used in PHP to run unit tests, build documentation, etc. 239. Basically, any documentation or QA tool we've talked about can and should be automated 240. Basics

  • System typically monitors commits
  • Have a post-receive/commit hook trigger a build

241. Have cron/sleep processes that periodically wake up and check for new commits A PHP Build

  • Runs tests,

242. Runs QA tools (mess detection, etc.), 243. Builds documentation 244. Solutions

  • Ant:http://ant.apache.org/
  • Not CI by itself, but a build system

245. Solutions

  • Phing:http://phing.info/trac/
  • PHP Ant clone; again, not CI, but a build tool

246. Solutions

  • CruiseControl:http://cruisecontrol.sourceforge.net/
  • Uses Ant under the hood

247. Solutions

  • CruiseControl

248. Solutions

  • phpUnderControl:http://www.phpundercontrol.org/
  • Superset of CruiseControl with built-in support for PHPUnit, CodeSniffer,and more.

249. Solutions

  • Hudson:http://hudson-ci.org/
  • Oracle OSS project, written in Java, under active development.

250. Also uses Ant for build configuration 251. PHPUnit support via a generic xUnit plugin 252. Support for other PHP tasks via a Phing plugin 253. Solutions

  • Bamboo:http://www.atlassian.com/software/bamboo/
  • Commercial Java CI solution

254. Can use Ant or Maven 255. Most PHP QA tools export logs to formats compatible with equivalent Java tools; Bamboo simply uses these logs. 256. Takeaways

  • Automate your QA tasks
  • Find issues early

257. Fix them before deployment Use continuous integration solutions to perform the automation 258. Resources

  • Sebastian Bergmann's talk "The State of QA Tools in PHP"

259. http://phpqatools.org 260. http://phpqabook.com 261. Deployment 262. Why You Need A Process

  • Many steps for live deploy

263. Wrap into one step, you won't miss anything 264. It'll be done the same way by everyone 265. You can roll back

  • (if you build that into your process)

266. Deployment Tools

  • Hand-spun scripts

267. Phing

  • http://phing.info/trac/

Capistrano (Ruby)

  • http://www.capify.org/index.php/Capistrano

268. Further Reading

  • http://phpdeveloper.org

269. http://devzone.zend.com 270. http://techportal.ibuildings.com 271. Thanks

  • http://joind.in/1563