Should code in examples be copy-paste-able (as a working program)?
Yes
- Reader can just copy-paste a working solution and try it out for themselves
- Saves the read headaches if his program doesn't work, because he implemented the solution wrongly (forgot to
#include
,import
, ...)
No
- Examples are way to long if they should work out-of-the-box
- Distracts from main objective (Showing how a specific problem should be solved)
- 90% of people are only interested in a solution, not a working program (they would probably only copy-paste the 3 line solution, instead of the working program)
- Unnecessary - Everyone should know how to write a working program (if not, they shouldn't start sorting arrays)
Some arguments only apply to some languages (like C++, Java) and not to others (Python, ...)
I vote for No. I think it is unnecessary to write a full program.
Actual code from an actual examples in an actual topic in an actual tag :)
[...]
#include <iostream>
#include <utility>
#include <map>
int main()
{
std::multimap<int, std::string, std::greater<int>> sorted_map;
// Sort the names of animals in descending order of the number of legs
sorted_map.insert(std::make_pair(6, "bug"));
sorted_map.insert(std::make_pair(4, "cat"));
sorted_map.insert(std::make_pair(100, "centipede"));
sorted_map.insert(std::make_pair(2, "chicken"));
sorted_map.insert(std::make_pair(0, "fish"));
sorted_map.insert(std::make_pair(4, "horse"));
sorted_map.insert(std::make_pair(8, "spider"));
for (auto const& entry: sorted_map)
{
std::cout << entry.second << " (has " << entry.first << " legs)" << '\n';
}
}
[...]
The only difference between sorting in descending order (above) rather than ascending is just one argument: std::greater<int>
.
Also, the example above also doesn't compile, it misses #include <functional>
.
I would definitely rewrite to something like:
[...]
//'sorted_map' sorts its keys in descending order
std::multimap<int, std::string, std::greater<>> sorted_map;
sorted_map.emplace(1, "bar");
sorted_map.emplace(5, "foo");
std::string value = sorted_map.begin()->second;
//'value' is "foo", because keys are sorted in descending order, and so 5 comes before 1
[...]
In my opinion, the second code-snippet is much better, for the reasons stated above. This might not be a problem for small code-snippets, but when you start having multiple #include
s (and other stuff) the program gets longer and longer (as this one).
What should we encourage?