Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable to use tricks to save programmer when putting data in your code?

Example: It's really annoying to type a list of strings in python:

["January", "February", "March", "April", ...]

I often do something like this to save me having to type quotation marks all over the place:

"January February March April May June July August ...".split()

Those took the same amount of time, and I got 2x the # of months typed in. Another example:

[('a', '9'), ('4', '3'), ('z', 'x')...]

instead of:

map(tuple, "a9 43 zx".split())

which took much less time.

like image 452
Claudiu Avatar asked Jul 13 '09 23:07

Claudiu


4 Answers

Code is usually read many times, and it is written only once.
Saving writing time at the expense of readability is not usually a good choice, unless you are doing some throw-away code.

The second version is less explicit, and you need some time to understand what the code is doing. And we are simply talking about variable instantiation, not about algorithms!

like image 137
rob Avatar answered Oct 29 '22 02:10

rob


A good text editor can make these things a non-issue. For example, I can type the following line in my code:

print `"January February March April May June July August September October November December".split()`

And then using the key sequence V:!python<ENTER> I can run the line through the python interpreter, and the output is the following:

['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

I'm using Vim for my example, but I'm sure this is just as easy with Emacs, TextMate, etc.

like image 38
too much php Avatar answered Oct 29 '22 00:10

too much php


In a reasonably smart editor you could:

  1. Select the lines of interest,
  2. insert the replacement (<space> by "<space>" for the 1st ex.),
  3. check selected lines checkbox,
  4. click replace all,
  5. bam.. your done.

Readable and easy to type... respect the power of the editor!

like image 44
NomeN Avatar answered Oct 29 '22 02:10

NomeN


In general, I think this is a bad idea. The first example isn't SO bad (it's sort of a substitute for python's lack of qw), but the second is much more difficult to understand. In particular, I think this sort of thing is very unpythonic, and certainly not appropriate when writing Python code, at any rate. Code readability is much more important than saving a little time writing the code. If you really have THAT much data to hardcode, write a script to generate it for you.

like image 45
Nick Lewis Avatar answered Oct 29 '22 00:10

Nick Lewis