Share your knowledge and create a knowledgebase.

Archive for the ‘Programming’ Category



PHP vs Python - What does it take to state one language better than other? One answer can be flexibility, development friendly, licensing policy (open source or commercial), community,  portability, dynamic typing, support for variable number of function arguments and ability to freeze live objects in a string representation. Documentation of course is a major player when you choose a language because you still have to sharpen your skill and you haven’t worked on that particular language yet.

Features which supports PHP

  • syntax very close to C and Perl, with curly braces and dollar signs
  • the ’switch’ statement and ‘do … while’ construct just like C
  • increment and decrement and assignment operators
  • the ternary operator/statement (… ? … : …)
  • schizophrenic tableau of function names. There are no namespaces, so functions often have prefixes to denote their source (but often not). Functions are often placed into classes to simulate namespaces.
  • a very casual language, where globals are often used to pass arguments (global variables should not be used, that is language independent)
  • commonly installed environment
  • aliases (’$a =& $b’ means that when $b changes, $a changes also) (should be “references”, not “aliases”, but are called aliases)
  • one array type that doubles as a list and a dictionary. Dictionary keys are iterated in their original order.
  • Excellent Documentation
  • Huge Community base with huge supportive codebase available online

Features which supports Python

  • namespaces and modules
  • small core
  • indentation to mark out block structure rather than curly braces, which make code look prettier
  • clear, concise, and orthogonal syntax
  • self documenting with docstrings and pydoc (PHP 5 has reflection and doc strings)
  • keyword arguments to functions and methods, easy support for default arguments
  • true object orientation and ‘first class’ classes and functions
  • classes are used extensively in the standard library
  • multiple inheritance
  • object-oriented file handling
  • method chaining
  • everything is a reference
  • ‘del’ statement for all data types
  • consistent case sensitivity (PHP does for variables, but not functions) (Functions are case insensitive)
  • simple array slicing syntax
  • iterators (PHP 5)
  • structured exception handling (PHP 5)
  • operator overloading
  • threading
  • lots of high-level data types (lists, tuples, dicts, mx.DateTimes, NumPy arrays, etc.)
  • dates that aren’t limited to UNIX timestamps (<1970, >2038)
  • support for all major GUI frameworks
  • strong internationalization and UNICODE support
  • maturity, stability and upward-compatibility
  • tends to lead to much more scalable applications

Unlike PHP, which has web development features built directly into the core language, Python’s web development capabilites are provided by add-on modules. Basic CGI capabilities are provided by the ‘cgi’ module which comes in Python’s standard library. There’s also a wide range of third-party modules available for Python; some are complementary, others compete. As a result, Python provides a more flexible base for web development.

There are some adverse side effects of this flexibility. First, the range of choices can be bewildering. Unless you are working experienced Python web developers, PHP is easier to get started with. Second, support for PHP is more common with shared-hosting companies than support for the various Python options.

Another difference is that PHP is embedded in the web server, whereas Python web applications can either be embedded in the web server like PHP or run in a separate process.

Now, lets test how fast they execute to find all the prime numbers under 10000. We will execute the test three times by optimizing the outcome

$ time ./script.php
Language Script 1 Script 2 Script 3
PHP 1.359 1.753 1.191
Python 1.894 1.636 1.634

Well, this shows that PHP runs faster than Python but here is a catch. PHP can run faster for smaller codes but when we talk in terms of scalable large system then Python will perform better. The above code was small where we were finding all prime numbers under 10000 and PHP shows why its choosen in most of the small web applications. No doubts there are few big names with PHP backing too.

Lets do one more analysis where mathematical calculations are performed

Sample script loops through a FOR statement 2,000,000 times calculating the MD5 hash of N + N, N equaling the number of passes thus far.

Results:

Round 1 - 2,000,000 Passes
PHP = 21.4227 sec
Python = 9.8737 sec

Round 2 - 2,000,000 Passes
PHP = 21.1122 sec
Python = 9.7241 sec

Round 3 - 1,000,000 Passes
PHP = 9.811 sec
Python = 4.429 sec

Round 4 - 1,000,000 Passes
PHP = 9.857 sec
Python = 4.280 sec

As you can see, Python is more than 2 times faster than PHP in performing this operation, which is more towards executing a mathematical algorithm.

Another Opinion - Python has been optimized for mathematical algorithms so in that respect it will blow PHP out of the water but if you compare which language can server more web pages in a period of time you find that PHP is noticeably faster.

Other important Aspects which make a language preferable are listed below:

Speed of Execution

Given a fairly intense problem neither language has a large advantage over the other, and each will be better for different things. We can thus rule out execution speed for 99% of what we do.

Speed of Writing

Assuming the languages in question all run at an acceptable speed (and they probably do) this becomes the second most important metric (number 1 being if they will actually run). I must be honest here and say that I have not used Python long enough to be sure how fast or slow I am for developing in it but I can say that so far it seems faster.

Maintenance

I may have not been using Python long but I can hands down say that it’s easier to maintain. I indent stuff in PHP anyway but the lack of curly braces is really nice and I prefer the scope access of Python over PHP (object.property vs $object->property) but I think that’s a matter of personal opinion that you need to decide on for yourself.

Ease of Setup/Portability

PHP wins here, you don’t need write your own HTTP headers as you do with Python, more hosts support it, it’s easier to connect it to a database and there seem to be more tutorials on it.

Support/Community

I would say PHP community and Support is better but with days passing by i have noticed large Python community helping out.

Other Sources:

I liked may comparisons but few are very good i am listing the ones below, i will keep on adding when i get time.

Summary

I would prefer Python for the sake of developing a scalable application (its not like you can’t do in PHP), but its easier in Python. Moreover, Google supports Python with its Google App Engine where web sites can be hosted on Google’s server for free, it also supports Python frameworks like Django so my bet will be on Python. PHP on the other hand still have 60% of the market share and i bet with the new release (6.0) in the corner they will certainly fill up the gap by including namespaces,high level data types etc.

If you’ve got any thoughts, comments or suggestions for things we could add, leave a comment! Also please Subscribe to our RSS for latest tips, tricks and examples on cutting edge stuff.


Nov 5, 2008 Author: Ashish | Filed under: PHP, Programming

Tiobe Softwares has released rankings of programming languages and popularity of programing languages for the month of November 2008. The index is updated once a month. The ratings are based on the number of skilled engineers world-wide, courses and third party vendors. The popular search engines Google, MSN, Yahoo!, and YouTube are used to calculate the ratings. According to Tiobe few of the major gainer and loosers are

  • Java & C Still topping the chart at 1 & 2 respectively
  • ActionScript and Logo entered in top 20
  • PHP is still stable at 5th place
  • Delphi is still in top 10
  • Visual basic looses one place to C++
  • Python is gaining popularity
  • Perl and Ruby goes down by three and two spots respectively

Programming languages last few months rankings:

The index can be used to check whether your programming skills are still up to date or to make a strategic decision about what programming language should be adopted when starting to build a new software system. The definition of the TIOBE index can be found here.

Position
Nov 2008
Position
Nov 2007
Delta in Position Programming Language Ratings
Nov 2008
Delta
Nov 2007
Status
1 1 Same Popularity of Programming Languages: November 2008 Java 20.299% -0.24% A
2 2 Same Popularity of Programming Languages: November 2008 C 15.276% +1.31% A
3 4 Up Popularity of Programming Languages: November 2008 C++ 10.357% +1.61% A
4 3 Down Popularity of Programming Languages: November 2008 (Visual) Basic 9.270% -0.96% A
5 5 Same Popularity of Programming Languages: November 2008 PHP 8.940% +0.25% A
6 7 Up Popularity of Programming Languages: November 2008 Python 5.140% +0.91% A
7 8 Up Popularity of Programming Languages: November 2008 C# 4.026% +0.11% A
8 11 Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008 Delphi 4.006% +1.55% A
9 6 Down Popularity of Programming Languages: November 2008Down Popularity of Programming Languages: November 2008Down Popularity of Programming Languages: November 2008 Perl 3.876% -0.86% A
10 10 Same Popularity of Programming Languages: November 2008 JavaScript 2.925% 0.00% A
11 9 Down Popularity of Programming Languages: November 2008Down Popularity of Programming Languages: November 2008 Ruby 2.870% -0.21% A
12 12 Same Popularity of Programming Languages: November 2008 D 1.442% -0.26% A
13 13 Same Popularity of Programming Languages: November 2008 PL/SQL 0.939% -0.24% A
14 14 Same Popularity of Programming Languages: November 2008 SAS 0.729% -0.40% A–
15 18 Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008 ABAP 0.570% -0.08% B
16 19 Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008 Pascal 0.511% -0.13% B
17 17 Same Popularity of Programming Languages: November 2008 COBOL 0.510% -0.20% B
18 25 Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008 ActionScript 0.506% +0.04% B
19 23 Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008Up Popularity of Programming Languages: November 2008 Logo 0.489% -0.04% B
20 16 Down Popularity of Programming Languages: November 2008Down Popularity of Programming Languages: November 2008Down Popularity of Programming Languages: November 2008Down Popularity of Programming Languages: November 2008 Lua 0.473% -0.27% B

Other Programming languages

The complete top 50 of programming languages is listed below. This overview is published unofficially, because it could be the case that we missed a language.

Position Programming Language Ratings
21 Lisp/Scheme 0.470%
22 MATLAB 0.466%
23 Ada 0.410%
24 Fortran 0.380%
25 FoxPro/xBase 0.320%
26 Prolog 0.314%
27 RPG (OS/400) 0.298%
28 Awk 0.256%
29 LabVIEW 0.235%
30 Tcl/Tk 0.230%
31 Erlang 0.220%
32 Bourne shell 0.220%
33 Caml 0.196%
34 Alice 0.188%
35 PL/I 0.188%
36 Haskell 0.163%
37 NXT-G 0.153%
38 Objective-C 0.149%
39 Smalltalk 0.148%
40 PowerShell 0.143%
41 Groovy 0.138%
42 ML 0.132%
43 Scala 0.120%
44 REXX 0.119%
45 Transact-SQL 0.115%
46 Forth 0.114%
47 Euphoria 0.114%
48 CL (OS/400) 0.111%
49 Natural 0.105%
50 VHDL 0.105%

Programming languages long term trends

Following chart represents the long term trends of popular top 10 programming languages

programming_lnguages_trends.png

The Next 50 Programming Languages

The following list of languages denotes #51 to #100. Since the differences are relatively small, the programming languages are only listed (in alphabetical order).

  • ABC, AD, Algol, Alpha, APL, Applescript, AspectJ, Beta, Boo, C shell, cg, Ch, Clean, cT, Curl, Dylan, Eiffel, Factor, Felix, Focus, Fortress, Icon, IDL, Inform, Io, Lingo, MAD, Magic, Maple, Mathematica, MOO, MUMPS, Oberon, Occam, Oz, PILOT, Postscript, PowerBuilder, Progress, Q, R, REALbasic, Revolution, S-lang, SIGNAL, SPSS, SuperCollider, VBScript, Verilog, XSLT

Long Term Trends for categories of programming languages

The object-oriented paradigm is at an all time high with 57.6%. The popularity of dynamically typed languages seems to be stabilizing (see trend diagram below).

Category Ratings November 2008 Delta November 2007
Object-Oriented Languages 57.9% +1.6%
Procedural Languages 38.7% -2.2%
Functional Languages 2.6% +0.4%
Logical Languages 0.8% +0.1%
Category Ratings November 2008 Delta November 2007
Statically Typed Languages 60.0% +1.2%
Dynamically Typed Languages 40.0% -1.2%

history_paradigm_type_system.png

Well many people are criticizing their rankings and algorithm used to calculate rankings so its up to you to believe. Feel free to post your comments and your 2 cents of their ranking system. Do you think its proper or its based on assumptions?

If you’ve got any thoughts, comments or suggestions for things we could add, leave a comment! Also please Subscribe to our RSS for latest tips, tricks and examples on cutting edge stuff.


Nov 3, 2008 Author: Ashish | Filed under: Programming

Tiobe Softwares has released rankings of programming languages and popularity of programing languages for the month of October 2008. The index is updated once a month. The ratings are based on the number of skilled engineers world-wide, courses and third party vendors. The popular search engines Google, MSN, Yahoo!, and YouTube are used to calculate the ratings. According to Tiobe few of the major gainer and loosers are

  • PowerShell lost its last month 19th place and dipped to 38th position
  • PHP is still stable at 5th place
  • Delphi is still in top 10
  • Ruby is stable at 10th place.
  • C++ gained more popularity than Visual Basic and PHP
  • COBOL is loosing ground

Programming languages rankings by month:

The index can be used to check whether your programming skills are still up to date or to make a strategic decision about what programming language should be adopted when starting to build a new software system. The definition of the TIOBE index can be found here.

Position
Oct 2008
Position
Oct 2007
Delta in Position Programming Language Ratings
Oct 2008
Delta
Oct 2007
Status
1 1 Same Popularity of Programming Languages: October 2008 Java 20.949% -0.67% A
2 2 Same Popularity of Programming Languages: October 2008 C 15.565% +0.97% A
3 4 Up Popularity of Programming Languages: October 2008 C++ 10.954% +1.37% A
4 3 Down Popularity of Programming Languages: October 2008 (Visual) Basic 9.811% -1.35% A
5 5 Same Popularity of Programming Languages: October 2008 PHP 8.612% -0.89% A
6 8 Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008 Python 4.565% +1.13% A
7 6 Down Popularity of Programming Languages: October 2008 Perl 4.419% -0.93% A
8 7 Down Popularity of Programming Languages: October 2008 C# 3.767% +0.03% A
9 13 Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008 Delphi 3.288% +1.75% A
10 10 Same Popularity of Programming Languages: October 2008 Ruby 2.860% +0.47% A
11 9 Down Popularity of Programming Languages: October 2008Down Popularity of Programming Languages: October 2008 JavaScript 2.670% -0.01% A
12 12 Same Popularity of Programming Languages: October 2008 D 1.333% -0.26% A
13 11 Down Popularity of Programming Languages: October 2008Down Popularity of Programming Languages: October 2008 PL/SQL 1.024% -0.94% A-
14 14 Same Popularity of Programming Languages: October 2008 SAS 0.600% -0.78% B
15 17 Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008 Lua 0.551% -0.04% B
16 21 Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008 Pascal 0.520% +0.10% B
17 22 Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008Up Popularity of Programming Languages: October 2008 ActionScript 0.506% +0.14% B
18 16 Down Popularity of Programming Languages: October 2008Down Popularity of Programming Languages: October 2008 COBOL 0.491% -0.19% B
19 18 Down Popularity of Programming Languages: October 2008 Lisp/Scheme 0.485% -0.09% B
20 15 Down Popularity of Programming Languages: October 2008Down Popularity of Programming Languages: October 2008Down Popularity of Programming Languages: October 2008Down Popularity of Programming Languages: October 2008Down Popularity of Programming Languages: October 2008 ABAP 0.445% -0.40% B

Other Programming languages

The complete top 50 of programming languages is listed below. This overview is published unofficially, because it could be the case that we missed a language.

Position Programming Language Ratings
21 Logo 0.430%
22 MATLAB 0.404%
23 Fortran 0.383%
24 Ada 0.372%
25 FoxPro/xBase 0.345%
26 RPG (OS/400) 0.304%
27 LabVIEW 0.248%
28 Prolog 0.248%
29 DC 0.242%
30 Awk 0.217%
31 PL/I 0.210%
32 Bourne shell 0.200%
33 Smalltalk 0.180%
34 Transact-SQL 0.165%
35 Focus 0.163%
36 Haskell 0.161%
37 Scala 0.147%
38 PowerShell 0.144%
39 Groovy 0.143%
40 Alice 0.136%
41 Forth 0.131%
42 Caml 0.124%
43 Euphoria 0.123%
44 REXX 0.120%
45 CL (OS/400) 0.118%
46 ML 0.116%
47 Tcl/Tk 0.116%
48 Natural 0.115%
49 Erlang 0.096%
50 Objective-C 0.086%

Programming languages long term trends

Following chart represents the long term trends of popular top 10 programming languages

tpci_trends Popularity of Programming Languages: October 2008

The Next 50 Programming Languages

The following list of languages denotes #51 to #100. Since the differences are relatively small, the programming languages are only listed (in alphabetical order).

  • ABC, AD, Algol, Alpha, APL, Applescript, AspectJ, Beta, Boo, C shell, cg, Ch, Clean, cT, Curl, Dylan, Eiffel, Factor, Felix, Fortress, Icon, IDL, Inform, Io, Lingo, MAD, Magic, Maple, Mathematica, MOO, MUMPS, NXT-G, Oberon, Occam, Oz, PILOT, Postscript, PowerBuilder, Progress, Q, R, REALbasic, Revolution, S-lang, SIGNAL, SPSS, VBScript, Verilog, VHDL, XSLT

Long Term Trends for categories of programming languages

The object-oriented paradigm is at an all time high with 57.6%. The popularity of dynamically typed languages seems to be stabilizing (see trend diagram below).

Category Ratings October 2008 Delta October 2007
Object-Oriented Languages 57.6% +4.0%
Procedural Languages 39.6% -3.1%
Functional Languages 1.9% -0.1%
Logical Languages 0.9% -0.8%
Category Ratings October 2008 Delta October 2007
Statically Typed Languages 60.4% +3.8%
Dynamically Typed Languages 39.6% -3.8%

history_paradigm_type%20system Popularity of Programming Languages: October 2008

Well many people are criticizing their rankings and algorithm used to calculate rankings so its up to you to believe. Feel free to post your comments and your 2 cents of their ranking system. Do you think its proper or its based on assumptions?

If you like this post kindly subscribe to our RSS for free updates and articles delivered to you.


Oct 9, 2008 Author: Ashish | Filed under: Programming

coding_principles.jpgCoding principles helps you to maintain good coding practice along with concrete product development. Coding principles also helps you write excellent quality of code with huge difference to overall performance and scalability of your application. Following are the most important Coding Principles which can save a lot for you when you are writing quality application for you or your client. Ensuring these coding principles you can save development time, management time and conquer lots of other bottlenecks which generally arise in later development phases.  You can also use the idea of PHP Design patterns which can speed up the development process by providing tested, proven development paradigms. This article is taken from two articles at programming4scientists.com with few modifications.

Don’t Repeat Yourself (DRY)

The concept here is that anything you use in your code should have a single, unambiguous representation.  This means if you are storing a number, only store it in a single place (don’t have PI stored in three different places).  Not only is multiple storage wasteful, but it multiplies your effort if you want to change, especially if you have to go hunting through several files to find where the numbers are defined.  Multiple representations are also a great way to generate bugs if you forget to change some of them.  This also applies to code; don’t repeat chunks of code that do the same thing - have a single version and put it in a function.

Test as you write

As much as possible, test your code as you write it.  These tests will often be quick and easy ones, such as checking that the value of pi you’re using is really what it should be, but if you perform these little checks while you’re working on (and thinking about) that piece of code, you’ll save yourself a lot more effort having to come back later and fix bugs.  You’ll find that you can perform a lot of simple tests very quickly as you go along; once you’re in the habit, you really don’t spend a lot of time doing it.  But the time you save yourself later on can be considerable. As well as informal testing, using a test harness and writing automated tests will help guarantee code you have already written keeps doing what you expect and helps prevent bugs you have already fixed from reappearing.

Reduce dependencies as much as possible

A dependency is a connection between two chunks of code, for example, using the same variable, and the more of these your code has, the more things you have to keep track of.  When writing and debugging a chunk of code, the last thing you want is arbitrary other chunks being able to interact with it, because it’ll very quickly become unmanageable. Much better would be for each chunk of code to be highly de-coupled from the rest of the code, with only very specific connections to the rest of the program.  This keeps things much simpler and easy to manage.  In practice, this means things like compartmentalising your code into chunks (which you were doing anyway, right?), avoiding global variables (with the possible exception of explicitly fixed constants such as PI) and the like.  If you’re feeling keen, writing object oriented code is excellent for this, as this has encapsulation built into the process.

Validate your data

At some point, someone will feed garbage into your carefully crafted code. In fact, part of your testing should be feed garbage input into your code to check that it recognises it! If your code is validating the data it is given then it should be able to deal intelligently with this, even if “intelligently” means “crash but tell the user what has gone wrong and why”. Assertions are an ideal way to make the program stop as soon as something is wrong. They work by ‘asserting’ that something is true and if it isn’t then the program stops.

For example:

Assert(x >= 0)

If the variable x is less than zero then the program will immediately stop at this point.

During development this kind of information is invaluable and since the program has stopped at the first point it spotted something wrong, you don’t have to work backwards from a garbage final output to find where the program failed.

Handle errors nicely

Asserts are a great way of validating data and are very useful during development, however once a program is in the hands of the users you want your error handling to be a little nicer than stopping the program immediately.  There is nothing more frustrating than a program that just dies without warning or explanation. Most modern languages have support for handling problems your code encounters using Exceptions. Exceptions are generated when something goes wrong and bubble up until they are caught and dealt with. The advantage of exceptions is that they can be used without your code having to pass around error-code results from function to function. Using exceptions properly is a complex subject, because the exception handling represents a different path through the code, but a simple rule of thumb is: ‘Throw an exception when a problem is first encountered, catch it at the first point that can deal with it’. In programs with a GUI (Graphical User Interface) this usually means there is a catch-all at the user interface layer that displays a message to the user (or something similar) before attempting to save the data and then shutting down.

Keep It Simple

The simpler your code is, the easier it is to construct and maintain.  So, subject to the constraints of our objectives, the simpler you can make your code the better.  This has a connection to premature optimisation (see this post ), because optimised code tends to be less simple.  We think a reasonable rule-of-thumb is that unless most simple way of doing something will be obviously too inefficient, it’s worth trying.  you can always change it later and, because it’s simple code, this shouldn’t be too hard.  One way to describe this is to paraphrase Albert Einstein:  Code should be as simple as possible, but no simpler.

Tidy up after yourself

code_cleanup.jpg Once you start to leave one or two things unfixed, it becomes much easier to leave “just one more”, and soon your code is a wreck.  There should not be a single “broken window” in the code you’re building (the phrase “broken window” comes from a study that showed that a major indicator of the state of a building was a single broken window; once one is broken, people care a lot less about maintaining the rest, it seems).  The book “The Pragmatic Programmer” has a nice description of this.

Learn new tools

If all you have is a hammer, then all your problems tend to look like nails.  The way to avoid this is to have more than one tool.  In general, you want to have a good, broad selection of tools with which to write your code.  A good way to acquire this is to try to learn the occasional new tool as you go along.  These can be useful pieces of software, new techniques or whatever; the important thing is that it gives you at least one more good option for writing your code.

Maintain your flow

Flow is a psychological state that you get into when you’re absorbed in your work (sportsmen call it being “in the zone”).  Have you ever gotten really into your work, so much so that suddenly an hour has passed without you noticing?  That’s flow!  In this state, you tend to be very productive and very focused on the task at hand.  Therefore, you want to try to stay in this state for as much of the time as possible.  It can take as much as 15 minutes to get into the flow, so it’s important to minimise things that will pull you out of the flow (once you’re out, that’s 15 minutes largely wasted).  That means try to avoid distractions, turn off the e-mail alert beep, listen to music to block out background noise, turn off your web browser.  Whatever it takes!

Make your code unsurprising

When someone glances at a chunk of code, they can often form a quick impression of what that chunk of code does.  It is convenient when this impression is accurate; it can be a real problem if the impression is misleading and they makes changes to the code before they realise.  The ‘principle of least surprise’ is that you should try to make your code’s actual functionality as close as possible to the typical quick impression.  Or, to put it another way, you should try to write your code so that it communicates its functionality accurately in a very short (pain-free) amount of time.  This means doing things like picking informative variable/function names, writing informative (and succinct) comments, and making the layout easy to read.

Don’t program by coincidence

‘Programming by coincidence’ is what happens when you “just get started coding” without thinking about what it is you actually want to achieve.  You write some code and it seems to work.  Great.  So you write some more. That also seems to works.  So you keep on doing this until one day you add some code and your software falls over.  And you have no idea why.  Think of this as the coding equivalent of a random walk; sure, you’re moving, but are you going to end up in the right place?  To avoid this, realise that a bit of planning and careful thought (including as the project progresses) is a very good thing.

Code entropy

Disordered code is bad, because it’s more likely to contain bugs.  Higher entropy is more disordered which is bad.  So you should try to keep the entropy of your code as low as possible.  This means taking care to keep things neat and tidy as you write the code.  It also means fixing bugs and refactoring messy bits of code.  One important aspect of code entropy is that any time you make a change to your code, the level of entropy will tend to increase (unless you’re very careful; fixing a bug, for example).  If you’re constantly re-writing your code, you’ll be introducing new bugs all the time and invalidating the testing you’ve done on that code.   So bear in mind that a bit of stability in your code is a good thing.

Summary

  • Let’s Re-Use our code as there is no point writing code when you can use some that’s already been written?  Reusing existing code can be a great way to save great big chunks of time.
  • Lets Rule Out any sort of dependencies or minimize it if not possible to rule out completely.
  • Test your code while you write to ensure bugs already fixed or appearing.
  • Use assertion for validation of data.
  • Keep error handling on top and don’t forget to throw exception until you are in staging environment. Of course you won’t show exceptions in production environment.
  • Keep the code simple so it is easier to construct and maintain.
  • Don’t leave anything broken and take initiative to fix yourself rather than wait for someone to figure the problem out for you.
  • Learn new tools and use then frequently. Tools can help you in various needs i.e. AJAX, Testing etc.
  • Maintain your flow in development.
  • Plan properly before you start coding, your goal should be very clear in your mind.
  • Make sure you are working for a stable code with very little bugs

All the above points don’t take much effort, once you get used to them, and the time (and headaches!) they can save you make it well worth the effort!

Please post your experiences with the above coding principles. If you like this post kindly subscribe to our RSS for free updates and articles delivered to you.


Oct 6, 2008 Author: Ashish | Filed under: Development Process, Programming

code_optimisation.jpgOptimization is the art of making your code run more quickly and/or using fewer of the available computing resources.  Sometimes this is desirable - completing an analysis in an hour rather than a week means you can get more done.  Sometimes it’s a necessity - your computer only has 500MB of RAM, so your software had better not need any more. Ever.  But sometimes it’s actually not important - if your software runs in a tenth of a millisecond, but need to wait for interactive user input, you’re already as quick as you need to be!  This is the key question you must ask yourself when thinking about optimisation:  Do I need this piece of code to go faster or use less memory? Post orginally taken from programming4scientists.com.

There are a number of different approaches that you can take to optimise your software.  Often it’s a blend of all of them that will give you the best results, but you’ll need to use your judgment in each case as good solutions will be code-, project- and deadline-specific, as well as relying on your skill as a developer.

Software optimization

This is what people normally mean by optimization – making changes to the code that improve the software’s performance in some way.  There are three important general types of software optimization that it’s useful to know about, algorithmic improvements, code improvements, and memory-versus-speed trade-offs.

An algorithmic improvement is when you change the algorithm that your code is using.  These are by far the most powerful code optimisations you can make, and can lead (sometimes) to orders of magnitude improvement in performance, if well thought out.  An algorithmic improvement is finding a fundamentally better way of doing something.  Such optimizations are always critically dependant on what exactly you’re doing, and often rely on deciding if what approximations you can make, given what your objectives are.

Code improvements are where you don’t change the underlying algorithm, but you do change it’s implementation in the code.  A defining characteristic of code optimization is that, for a given input, your software should produce the same output before and after the improvement.  It will just do so more quickly and/or using less memory.  The experience of many developers over many years suggests that you’re unlikely to get more than a factor of 2-10 improvement (at most) in the performance of your code using this kind of optimization.  This is very important to consider; if your code runs in a week, but you need it to run in three days, then  you might be okay with code optimization.  If you need it to run in a minute, you need to use a quicker algorithm in the first place.

Finally, memory-versus-speed trade-offs are a case that often occurs when you can change your code so that it’s faster, but uses more memory (or vice versa).  This is because of how computers handle data.  Any data to be used by a given piece of software must be read in to RAM from a hard drive, across a network or something like that.  This reading-in takes a bit of time.  To deal with a set of data, a process can either read them all in at once, or in chunks, operating on each chunk in turn.  Reading them all at once is faster, but requires enough RAM to hold all the data; reading in chunks only requires enough memory to hold a single chunk, but the periodic data-reading will slow the process down.

Bottlenecks and profiling

The key to any optimization is to know where the bottlenecks are in your code.  A code bottleneck is the part of the code that limits how quickly things can proceed. Our goal is to find these bottlenecks and then to fix them.  There’s no point of optimising sections of the code that aren’t bottlenecks – by definition, you won’t get much improvement in performance.  The key method in spotting bottlenecks is profiling.  This can be done using a profiler (a tool that tracks how much CPU time different parts of your code take), or sometimes even just be inserting print statements in your code (getting it to print to screen the time after every stage is a quick and easy way to do this).  Once you’ve used one or more of these to identify which parts of the code the computer spends most of its time on, you can go and have a look at that code and try to spot what it’s doing that’s taking so long.

Premature optimization

This is as bad as it sounds. optimization is fine-tuning of your code and as such is very specific to the exact nature of your code.  Imagine tweaking a car engine for optimum power output, but then stripping out the fuel injection system, adding a couple more cylinders and deciding to run it on liquid hydrogen – all your careful fine-tuning would become pointless.  So it is with computer code.  It’s also true that optimization will generally make your code less flexible and hence more effort to change.  This is a Bad Thing and should be avoided as much as possible.

Diminishing returns

You can’t keep optimizing forever (well, you can, but you shouldn’t).  There will come a point where you’ve made any big/easy gains in performance that are possible and you’ll increasingly be faced by potential improvements that are smaller and/or take longer to implement.  This is a law of diminishing returns.  This means you have to make a judgment as to when it is no longer worth continuing to optimize your code.  This will be a context-specific judgment, depending on the exact nature of the project you’re undertaking.  For example, if another week of coding can gain you a factor of two speed improvement that reduces run time from two months to one month, it might well be worth doing (provided you didn’t need that week for anything more important).  Conversely, if that week’s effort only gains you a 10% reduction in memory usage, but you’re already operating comfortably inside your machine’s RAM limit, don’t bother – you should spend that week on something more productive.

optimization can make your code run more quickly and/or using less memory.  If you need it to.  Be aware that there are a range of techniques that will allow you to invest some of your precious time in order to improve your code in this way.  Decide on whether this is necessary/desirable and, if it is, consider the types of optimization that might give you the performance boost you need.

Please post your experiences with code optimization. If you like this post kindly subscribe to our RSS for free updates and articles delivered to you.


Oct 3, 2008 Author: Ashish | Filed under: Programming

Advertisement

Adsense