<p>I really enjoyed <a href="http://www.codinghorror.com/blog/archives/001148.html" rel="noreferrer">Jeff's post</a> on <a href="http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan_programming" rel="noreferrer">Spartan Programming</a>. I agree that code like that is a joy to read. Unfortunately, I'm not so sure it would necessarily be a joy to work with.</p>

<p>For years I have read about and adhered to the "one-expression-per-line" practice. I have fought the good fight and held my ground when many programming books countered this advice with example code like:</p>

<pre><code>while (bytes = read(...))
{
   ...
}

while (GetMessage(...))
{
   ...
}
</code></pre>

<p>Recently, I've advocated one expression per line for more practical reasons - debugging and production support. Getting a log file from production that claims a NullPointer exception at "line 65" which reads:</p>

<pre><code>ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());
</code></pre>

<p>is frustrating and entirely avoidable. Short of grabbing an expert with the code that can choose the "most likely" object that was null ... this is a real practical pain.</p>

<p>One expression per line also helps out quite a bit while stepping through code. I practice this with the assumption that most modern compilers can optimize away all the superfluous temp objects I've just created ...</p>

<p>I try to be neat - but cluttering my code with explicit objects sure feels laborious at times. It does not generally make the code easier to browse - but it really has come in handy when tracing things down in production or stepping through my or someone else's code.</p>

<p>What style do <em>you</em> advocate and can you rationalize it in a practical sense?</p>

[{'answer_id': 51112, 'author': 'jjnguy', 'author_id': 2598, 'author_profile': 'https://Stackoverflow.com/users/2598', 'pm_score': 2, 'selected': False, 'text': '<p>One expression per line.</p>\n\n<p>There is no reason to obfuscate your code.  The extra time you take typing the few extra terms, you save in debug time.</p>\n'}, {'answer_id': 51147, 'author': 'pkaeding', 'author_id': 4257, 'author_profile': 'https://Stackoverflow.com/users/4257', 'pm_score': 3, 'selected': False, 'text': "<p>I think the ideal solution is to find a balance between the extremes.  There is no way to write a rule that will fit in all situations; it comes with experience.  Declaring each intermediate variable on its own line will make reading the code more difficult, which will also contribute to the difficulty in maintenance.  By the same token, debugging is much more difficult if you inline the intermediate values.</p>\n\n<p>The 'sweet spot' is somewhere in the middle.</p>\n"}, {'answer_id': 51152, 'author': 'amrox', 'author_id': 4468, 'author_profile': 'https://Stackoverflow.com/users/4468', 'pm_score': 2, 'selected': False, 'text': '<p>I tend to err on the side of readability, not necessarily debuggability.  The examples you gave should definitely be avoided, but I feel that judicious use of multiple expressions  can make the code more concise and comprehensible.</p>\n'}, {'answer_id': 51166, 'author': 'Dan Blair', 'author_id': 1327, 'author_profile': 'https://Stackoverflow.com/users/1327', 'pm_score': 4, 'selected': True, 'text': "<p>In <strong>The Pragmatic Programmer</strong> Hunt and Thomas talk about a study they term the Law of Demeter and it focuses on the coupling of functions to modules other than there own.  By allowing a function to never reach a 3rd level in it's coupling you significantly reduce the number of errors and increase the maintainability of the code. </p>\n\n<p>So:</p>\n\n<blockquote>\n  <p>ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());</p>\n</blockquote>\n\n<p>Is close to a felony because we are 4 objects down the rat hole.  That means to change something in one of those objects I have to know that you called this whole stack right here in this very method.  What a pain.</p>\n\n<p>Better:</p>\n\n<blockquote>\n  <p>Account.getUser();</p>\n</blockquote>\n\n<p>Note this runs counter to the expressive forms of programming that are now really popular with mocking software.  The trade off there is that you have a tightly coupled interface anyway, and the expressive syntax just makes it easier to use.</p>\n"}, {'answer_id': 51182, 'author': 'Michael Haren', 'author_id': 29, 'author_profile': 'https://Stackoverflow.com/users/29', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m usually in the "shorter is better" camp. Your example is good:</p>\n\n<pre><code>ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());\n</code></pre>\n\n<p>I would cringe if I saw that over four lines instead of one--I don\'t think it\'d make it easier to read or understand. The way you presented it here, it\'s clear that you\'re digging for a single object. This isn\'t better:</p>\n\n<pre><code>obja State = session.getState();\nobjb Account = State.getAccount();\nobjc AccountNumber = Account.getAccountNumber();\nObjectA a = getTheUser(AccountNumber);\n</code></pre>\n\n<p>This is a compromise:</p>\n\n<pre><code>objb Account = session.getState().getAccount();\nObjectA a = getTheUser(Account.getAccountNumber());\n</code></pre>\n\n<p>but I still prefer the single line expression. Here\'s an anecdotal reason: it\'s difficult for me to reread and error-check the 4-liner right now for dumb typos; the single line doesn\'t have this problem because there are simply fewer characters.</p>\n'}, {'answer_id': 51484, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 0, 'selected': False, 'text': '<p>Maintainability, and with it, readability, is king.  Luckily, shorter very often means more readable.</p>\n\n<p>Here are a few tips I enjoy using to slice and dice code:</p>\n\n<ul>\n<li><strong>Variable names</strong>: how would you describe this variable to someone else on your team?  You would <em>not</em> say "the numberOfLinesSoFar integer".  You would say "numLines" or something similar - comprehensible and short.  Don\'t pretend like the maintainer doesn\'t know the code at all, but make sure you yourself could figure out what the variable is, even if you forgot your own act of writing it.  Yes, this is kind of obvious, but it\'s worth more effort than I see many coders put into it, so I list it first.</li>\n<li><strong>Control flow</strong>: Avoid lots of closing clauses at once (a series of }\'s in C++).  Usually when you see this, there\'s a way to avoid it.  A common case is something like</li>\n</ul>\n\n<p>:</p>\n\n<pre><code>if (things_are_ok) {\n  // Do a lot of stuff.\n  return true;\n} else {\n  ExpressDismay(error_str);\n  return false;\n}\n</code></pre>\n\n<p>can be replaced by</p>\n\n<pre><code>if (!things_are_ok) return ExpressDismay(error_str);\n// Do a lot of stuff.\nreturn true;\n</code></pre>\n\n<p>if we can get ExpressDismay (or a wrapper thereof) to return false.</p>\n\n<p>Another case is:</p>\n\n<ul>\n<li><strong>Loop iterations</strong>: the more standard, the better.  For shorter loops, it\'s good to use one-character iterators when the variable is never used except as an index into a single object.</li>\n</ul>\n\n<p>The particular case I would argue here is against the "right" way to use an STL container:</p>\n\n<pre><code>for (vector&lt;string&gt;::iterator a_str = my_vec.begin(); a_str != my_vec.end(); ++a_str)\n</code></pre>\n\n<p>is a lot wordier, and requires overloaded pointer operators *a_str or a_str->size() in the loop.  For containers that have fast random access, the following is a lot easier to read:</p>\n\n<pre><code>for (int i = 0; i &lt; my_vec.size(); ++i)\n</code></pre>\n\n<p>with references to my_vec[i] in the loop body, which won\'t confuse anyone.</p>\n\n<p>Finally, I often see coders take pride in their line number counts.  But it\'s not the line numbers that count!  I\'m not sure of the best way to implement this, but if you have any influence over your coding culture, I\'d try to shift the reward toward those with compact classes :)</p>\n'}, {'answer_id': 51533, 'author': 'epatel', 'author_id': 842, 'author_profile': 'https://Stackoverflow.com/users/842', 'pm_score': 0, 'selected': False, 'text': '<p>Good explanation. I think this is version of the general <a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm" rel="nofollow noreferrer">Divide and Conquer</a> mentality.</p>\n'}, {'answer_id': 4297073, 'author': 'Zecc', 'author_id': 400127, 'author_profile': 'https://Stackoverflow.com/users/400127', 'pm_score': 2, 'selected': False, 'text': '<pre><code>ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());\n</code></pre>\n\n<p>This is a bad example, probably because you just wrote something from the top of your head.\nYou are assigning, to variable named <code>a</code> of type <code>ObjectA</code>, the return value of a function named <code>getTheUser</code>.<br>\nSo let\'s assume you wrote this instead:</p>\n\n<pre><code>User u = getTheUser(session.getState().getAccount().getAccountNumber());\n</code></pre>\n\n<p>I would break this expression like so:</p>\n\n<pre><code>Account acc = session.getState().getAccount();\nUser user = getTheUser( acc.getAccountNumber() );\n</code></pre>\n\n<p>My reasoning is: how would I think about what I am doing with this code?<br>\nI would probably think: "first I need to get the account from the session and then I get the user using that account\'s number".</p>\n\n<p>The code should read the way you think. Variables should refer to the main entities involved; not so much to their properties (so I wouldn\'t store the account number in a variable).</p>\n\n<p>A second factor to have in mind is: will I ever need to refer to this entity again in this context?<br>\nIf, say, I\'m pulling more stuff out of the session state, I would introduce <code>SessionState state = session.getState()</code>.</p>\n\n<p>This all seems obvious, but I\'m afraid I have some difficulty putting in words why it makes sense, not being a native English speaker and all.</p>\n'}]
['https://Stackoverflow.com/questions/51108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4910/']