Learn a new language – not everything needs a hammer

Want to learn a new language?

So you’ve been doing your research and have decided that you’d like a new tool in the ol toolbox, rather than using [insert language here] as your hammer of choice.

Congratulations it happens to all of us at some point or another.

We all get to that point where we decide “There must be a better way”

To share, I’d been attempting to carry out some fairly heavy data comparison through just PHP – using it as a proverbial club a while back. Quickly it occurred to me that, although good for certain things, the performance just wasn’t there as the numbers increased and increased and increased.

We all get to that point where we decide “There must be a better way” – scratching our beards (both men and women) starring wistfully out of the window.

So how to best approach this? You know a handful of languages, and you, let’s be honest don’t need to look too deep in to for loops, variables, conditional operators and the like – it’s all been said before? So what do you do?

Dr Syntax

First thing I like to do is look at syntax, what are the specific syntax rules for that language – the grammar as it were. So for instance in PHP we might do:

<?php 
    $x = 9;
    if ( ($x % 3) === 0 ) 
    {
        $y = true; 
    } 
    else 
    { 
        $y= false; 
    } // or 
    $x = 9; 
    $y = ( ($x % 3) === 0 ) ? true : false 
?>

Whereas in Python we’d do…

x = 9
if x%3 is False: 
    y = true
else:
    y = false
# or
x = 9
y = true if x%3 is False else False

Syntax is obviously vital between languages – even if the principal constructs are in essence the same – the syntax is vital just simply to get the code running – however you shouldn’t have to dwell to long here to get the fundamentals. Which leads us nicely on to….

Additional advice : Check to see if the language treats functions as “first class citizens”

Best Practices (and what makes the language tick)

Just because you can write a C style for loop in pretty much every high level language out there – really doesn’t mean you should.

Why I hear you cry?

Would you use a TV from the 1970s? I think not.

Languages move forward in leaps and bounds and gone in a lot of languages is the simple for(start, condition, incrementer). There are for loops for arrays, there are comprehensions that allow you to roll these into a single statement, there are For Eachs, For ins.

However don’t blindly just use a feature because you can, it doesn’t mean you are improving your performance, and you might be affecting readability.

Firstly google the best practices – whether this is PHPs PSR standards, or Pythons PEP8 / PEP257, best practices will guide you in making your code readable and either a collaborator or the future you will be forever grateful (from the spaces to use for indents, to the naming conventions on variables).

Secondly search for “X the right way” where X is the name of the language. Read the blogs. Look on GitHub. Get a flavour of why developers choose certain ways and what the general consensus on the best solution for a given language is. Something that might be ideal in JS might not be the Pythonic way.

Debugging (under the bed and deep in the shed)

Before I start writing code, I always anticipate it won’t run first time, that’s a given. If you click compile, build or run and the code “Just works” – be suspicious. Be VERY suspicious. Given my acceptance of this I like to know I can easily debug a project, and easily determine what variables reference at any given time.

So for instance say I have…..

	Hashtable response = MyAwesomeAPIObj.getUpdate(parameters)
	/// returns under 'id' key the value 'id : 1000' or  'Error : 013'
	Integer updateId = (Integer)response['id'].split(':').pop()
	
	/// I could try to parse this response
	if ( id &gt; 200 ) 
	{
		Console.writeLine('%s updates reached!', id);
	}

This won’t throw an error, even though there is a problem. I’m reading the results and think “Woah, hangon – summit’s up!”. Without prior knowledge of the debug process I’d now be having to either print a tonne of stuff to the standard output or frantically researching debugging principles. Which wastes a tonne of time – and distracts me from figuring out what the real problem is.

Debugging is ultimately a way of, essentially, white box testing the code – which should offer indications of what the state of any given variable is at any given time. An essential tool in even the mightiest coders tool belt.

Unit Testing

One of the key paradigms of modern programming is the application of TDD (test driven development) – the idea that you create tests for the different potential outcomes of a piece of code before you create the code – therefore creating the test suite as you go. The beauty being that you create a test suite as well as regression test your code as you go – and if you get round to re-factoring the tests are there.  Boo yah.


import unittest

import MyMod

class TestMyModule(unittest.TestCase):

    def test_mymods_cool_method(self):

        res = MyMod.cool_method()

        expected_res = {'id': 2002}

        self.assertDictEqual(res, expected_res)

        self.assertEqual(True, True)

Therefore after getting my head around the best practices the next thing I like to do is to figure out the best practices for unit tests. Some languages like python have unit tests as part of their standard library, whereas JavaScript requires third party libraries like Chai and Mocha.

My best advice.

Read blogs, look at stack overflow and quora and look at what people are using and what is still in active development.

Refactor

Once I have all these pieces, I like to look at an inefficient use of a previous language I have used to solve a problem and explore that with the new chosen weapon in my toolbox. Refactoring old code or rehashing an old principal is great for both exploring the potential of a language and allowing you to perform a side by side comparison between the two languages.

Now go forth and write code.

Tips

  1. Currently using PHP? Check out C#
  2. Looking to create an API? Check out Python and Flask
  3. Using Node? Try out GO
  4. Been toying with Java? Check out Scala

Some General Language Agnostic Tips

  1. Comment and document – not overly but to give an overview
  2. Avoid obvious comments – don’t comment if statements, PLEASE DON’T
  3. Group your code into sets of discernible pieces – feel free to comment
  4. Use consistent indentation across the board (4 spaces is great – and python will agree)
  5. Use a consistent naming schema, whether this is camel case or underscores
  6. DON’T REPEAT YOURSELF
  7. Avoid deep nesting of if statements where possible.
  8. Limit your line length to, let’s say, less than 100 characters
  9. Optimise your project structure – don’t dump everything in a single folder
  10. Consistent temporary names – using a C style loop use ‘i’ as your look iterator
  11. Using SQL in your code? PLEASE capitalize the keywords
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s