Main Content
Code and code maintainance efficiency Archive - Originally posted on "The Horse's Mouth" - 2005-06-08 05:36:35 - Graham Ellis
Three maxims of coding and system development; I'm reminded of these this week as I run a PHP course which is heavily biased towards good coding standards / writing robust and maintainable web sites, but they apply to other languages / coding systems too!
"If you find yourself repeating something, then there must be a better way of doing it".
Have you even copied and pasted a block of code? I know I have, and then I've probably modified the duplicate. If you're copying and pasting, think again. Perhaps you should be incorporating the block of code into a loop, or perhaps it should become a function? If you're copying and pasting, but then altering the copy, you can still use a loop or a function - the bits that you change will become the loop control variables, or the parameters to the function.
"If you think to your self 'surely someone else has done this before', they probably have"
Don't re-invent the wheel! You'll very rarely be the first person ever to want to do "x" or "y", so have a look for a function / procedure / command that does what you want. In the Open Source world especially, where code develops with a multitude of enthusiastic contributors, you'll find rich picking by browsing the manuals in the area around what you're looking for. On our Python course , I tell a story against myself. In a live application, I wanted to re-arrange a list into a random order. Great - wrote the code, tested it, and it worked well. Then I discovered that there's already a shuffle method in the random module that's a part of the standard distribution ...
And in PHP we have a saying - "There's a function to do that" .
"Each component should perform a single task"
Keep each logical task in its own component. Why? Because, later on, you may wish to use that task again and if it comes bundled with a second task with which it's not logically connected, it may be non-trivial to separate out. Again, an example; the images on the left hand side of our web site are 132 x 300 pixels, and they're all bundled with a white band 8 pixels wide on the right to separate off the text from the margin. Great ... until I want to change the colour of the band. Because I've bundled the band and the picture in the same image file, there's no easy way.
Some other articles
Y116 - Applying OO design techniques and best practise Defining an object that is a modified standard type in Python How to avoid too many recalculations within an object We not only teach PHP and Python - we teach good PHP and Python Practice! Really Simple Class and Inheritance example in Python Inheritance, Composition and Associated objects - when to use which - Python example Tips for writing a test program (Ruby / Python / Java) Plan your application before you start How do I set up a constant in Python? Testing code in Python - doctest, unittest and others Alpaca Case or Camel Case Good Programming practise - where to initialise variables Code quality counts Build on what you already have with OO Python - block insets help with documentation Think about your design even if you don't use full UML This article Y105 - Functions, Modules and Packages From and Import in Python - where is the module loaded from? Embedding more complex code into a named block Nesting decorators Recursion in Python - the classic example What are callbacks? Why use them? An example in Python What is the difference between a function and a method? Reading command line parameters in Python A good example of recursion - a real use in Python Python - even named code blocks are objects Multiple yields and no loops in a Python generator? Python functions - an introduction to how they work Python varables - checking existance, and call by name or by value? Exception, Lambda, Generator, Slice, Dict - examples in one Python program vargs in Python - how to call a method with unknown number of parameters Optional positional and named parameters in Python Default local - a good choice by the author of Python Static variables in Python? Python timing - when to use a list, and when to use a generator Functions are first class variables in Lua and Python Finding all the unique lines in a file, using Python or Perl Python Packages - groupings of modules. An introduction Static variables in functions - and better ways using objects Passing optional and named parameters to python methods Catching the fishes first? Passing parameters to Python functions - the options you have Returning multiple values from a function call in various languages - a comparison Using an exception to initialise a static variable in a Python function / method Python - some common questions answered in code examples Passing a variable number of parameters in to a function / method Program for reliability and efficiency - do not duplicate, but rather share and re-use Optional and named parameters to Python functions/methods Python - access to variables in the outer scope Global and Enable - two misused words! Good example of recursion in Python - analyse an RSS feed Sample code with errors in it on our web site Optional parameters to Python functions Multiple returns from a function in Python Conversion of OSI grid references to Eastings and Northings Dynamic code - Python Optional and named parameters in Python What to do with a huge crop of apples Anonymous functions (lambdas) and map in Python Sharing variables with functions, but keeping them local too - Python Global - Tcl, PHP, Python Python Script - easy examples of lots of basics Returning multiple values from a function (Perl, PHP, Python) A better alternative to cutting and pasting code Function / method parameters with * and ** in Python It's the 1st, not the 1nd 1rd or 1th. Sludge off the mountain, and Python and PHP Python - A list of methods Recursion in Python Python - function v method Dynamic functions and names - Python Do not duplicate your code Cottage industry or production line data handling methods Python modules. The distribution, The Cheese Shop and the Vaults of Parnassus. Python - block insets help with documentation Python's Generator functions Difference between import and from in Python What is a callback? This article Call by name v call by value Lambdas in Python Python generator functions, lambdas, and iterators Distance Learning Variable Scope H115 - Designing PHP-Based Solutions: Best Practice Real life PHP application using our course training MVC example Using an MVC structure - even without a formal framework Learning to program - comments, documentation and test code We not only teach PHP and Python - we teach good PHP and Python Practice! Even early on, separate out your program from your HTML! Filtering PHP form inputs - three ways, but which should you use? PHP sessions - a best practice teaching example Injection Attacks - PHP, SQL, HTML, Javascript - and how to neutralise them Separating program and artwork in PHP - easier maintainance, and better for the user How to build a test harness into your PHP Not just a PHP program - a good web application Adding a newsfeed for your users to a multipage PHP application Improving the structure of your early PHP programs Refactoring - a PHP demo becomes a production page Defensive coding techniques in PHP? PHP Techniques - a workshop Short and sweet and sticky - PHP form input Software to record day to day events and keep an action list Efficient PHP applications - framework and example A story about benchmarking PHP Ordnance Survey Grid Reference to Latitude / Longitude Converting from postal address to latitude / longitude Controlling and labelling Google maps via PHP Using a MySQL database to control mod_rewrite via PHP Easy handling of errors in PHP Resetting session based tests in PHP Drawing hands on a clock face - PHP Painting a masterpiece in PHP Good Programming practise - where to initialise variables Back button - ensuring order are not submitted twice (PHP) Learning to write secure, maintainable PHP Maintainable code - some positive advice Code quality counts Global, Superglobal, Session variables - scope and persistance in PHP PHP - good coding practise and sticky radio buttons Reporting on the 10 largest files or 10 top scores Giving the researcher power over database analysis Merging pictures using PHP and GD Robust checking of data entered by users A year on - should we offer certified PHP courses This article Putting a form online Crossfertilisation, PHP to Python Short underground journeys and a PHP book H105 - Functions Coding efficiency - do not repeat yourself! Passing a variable number of parameters in to a function / method Improving your function calls (APIs) - General and PHP Adding extensions to PHP Open Source applications - callbacks Static variables and ampersands in PHP A variable number of arguments in a PHP function Global - Tcl, PHP, Python Static variables in PHP Clean my plate, but keep my wine bottle. (PHP; Static) is there a lookup function in php? Returning multiple values from a function (Perl, PHP, Python) A better alternative to cutting and pasting code PHP - static declaration Global, Superglobal, Session variables - scope and persistance in PHP A lazy programmer is a good programmer Do not duplicate your code Don't repeat code - use loops or functions Functions and commands with dangerous names This article Passing information into and out of PHP functions Call by name v call by value There is a function in PHP to do that Variable Scope H104 - Control Statements Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) While, for, foreach or something else to loop. Flowchart to program - learning to program with Well House Does a for loop evaluate its end condition once, or on every iteration? How a for loop works Java, Perl and other languages Predictions for the seagull population Extracting real data from an exported file in PHP or Perl Question Mark - Colon operator (Perl and PHP) Saying NOT in Perl, PHP, Python, Lua ... Decisions - small ones, or big ones? for loop - how it works (Perl, PHP, Java, C, etc) Testing for one of a list of values. Smart English Output - via PHP and Perl ? : operator Breaking a loop - Ruby and other languages Double and Triple equals operator in PHP The ternary operator in Python Don't repeat code - use loops or functions Assignment, equality and identity in PHP Wimbledon Neck This article