Given some (relatively) complicated line of code, I would often be inclined to split it onto multiple lines to make its function/purpose clear to others.
However, if it is quite clear from context what a line does, would you still do the same thing merely to make clearer how it does it? Or would you take the attitude that future developers probably don't know/care how it works, only that it works?
For some context, the particular line that's prompted this question is Python code that takes a string like "1.title" and uses it to modify self.data[1].title
:
#IRL, these 2 values are already set somehow
id = "1.title"
val = "foo"
setattr(self.data[int(id[:id.index(".")])], id[id.index(".")+1:], val)
That last line is not the nicest thing in the world to read, so I was thinking of splitting it into:
index = int(id[:id.index(".")])
attrib = id[id.index(".")+1:]
setattr(self.data[index], attrib, val)
If you wanted to go crazy, you could even do dotLocation = id.index(".")
first, and use that in the setting of index
and attrib
.
This is probably a bit clearer to someone else reading it for the first time, but I prefer it nice and concise on one line, and it's highly unlikely that anyone is going to need to modify this one-line utility function. Is there really much point to splitting it up like that?
(Note: I'm fully aware that this is not exactly life-or-death stuff. I'm not going to lose any sleep over it, I'm just wondering what others would do in this kind of situation.)
(Last thing: someone might want to add better tags to this, it's my first Programmers question :) )