What reasons could ease the choice between clear and concise artificial code example versus real-world working code which might be accompanied by all gory details for an author of programming book or a participant in online discussion?
views:
151answers:
4I suppose it depends on what the author is trying to explain.
If it is a basic concept, like inheritance, method overloading, etc, then a complex example, though accurate, could make the explanation harder.
If the author is trying to explain something like best practices for managing complexity in legacy code, you'd want a closer-to-reality example.
I think the criteria should be: the less code noise (code not directly related to the explanation) possible to convey the point.
You can indlue both. Look at the way that DO Factory show's design patterns. They give a code sample of what the structure of a pattern may look like and then they give what a real world example may look like.
If you are thinking about giving a very big example, then it should only be big to show how all of the parts fit together or how a larger solution should be crafted in a given framework or methedology.
What influences the decision is how many things you (or the author) want to consider at one time.
Real code considers many things. In educational contexts, it's usually helpful to consider only a few things at one time, and build up to be able to consider more and more of the things that go into real code. Examples should get progressively more realistic.
Pro of specially-crafted code: can be simpler and to the point, without fluff.
Con: too often, it looks artificial and doesn't really show the usefulness of what is used. Plus it might use bad practices ("I simplify for the demo. I would have used this (StringBuilder vs. +=, namespace, etc.) in real code, actually").
That's something that annoyed me in most regular expression tutorials I saw: you match c|d against aaaacaaaa, which is totally disconnected of real use cases.
In reaction, I wrote a regular expressions tutorial trying to use progressive (no forward references to not-seen yet features) yet realistic (I hope) examples.
Not obvious, perhaps not always possible, hence the simplifications.
I first learned Java with (French edition of) Java Head First, and beside the clarity of explanations (first OO concepts explanations I really understood!), I liked the concrete examples (building real programs) and while they simplify some stuff, they still explain the corner cases in a separate note instead of hiding them.