Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBrendan Moran
14,052 PointsWhat is the better coding principle: as many variables as possible, or the fewest lines possible?
What is the better principle? Or is there no better principle, and it is just a case of "it depends"?
If it just depends, then can you give me an example of where/why "fewest lines possible is best" and where/why "most variables" would be best? Or will I just learn this with experience?
I can see why having more variables for more flexibility could be important in longer or more complex programs.
2 Answers
Steven Parker
231,269 PointsThe best practice is to use the right number of variables, not "as many variables as possible". Enough to get the job done, and with sufficient flexibility to fit the predictable future needs of the program.
As for lines of code, the objective should not be how many, but whether the code does the job needed, and is efficient and maintainable. Code that is too short can be difficult for maintainers to understand. It can also be inefficient - sometimes adding a few lines (such as tests to eliminate unneeded steps from loops) can make a program actually run faster.
There is a "sweet spot" for both of these concepts that will be based on the particular requirements in each situation, and will be acquired with experience.
David Czerepak
11,865 PointsSteven is right. However whenever you can reiterate something based on the requirements in each situation, like Steve mentioned above, you should. So if you have to do the same thing over and over, it should be one section of code being passed that same job, but maybe with different inputs.
The above link is a great book.
The below link is a shorter read.
http://programmers.stackexchange.com/questions/103233/why-is-dry-important
Brendan Moran
14,052 PointsThanks for the resources! I will check those out.
Brendan Moran
14,052 PointsBrendan Moran
14,052 PointsOk, thanks! Makes sense.