Beautiful Code

Andy Oram, Greg Wilson

Mentioned 12

A group of computer programmers provide insights into software design and engineering.

More on Amazon.com

Mentioned in questions and answers.

If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?

I expect this list to be varied and to cover a wide range of things.

To search: Use the search box in the upper-right corner. To search the answers of the current question, use inquestion:this. For example:

inquestion:this "Code Complete"

Applying UML and Patterns by Craig Larman.

The title of the book is slightly misleading; it does deal with UML and patterns, but it covers so much more. The subtitle of the book tells you a bit more: An Introduction to Object-Oriented Analysis and Design and Iterative Development.

Masters of doom. As far as motivation and love for your profession go: it won't get any better than what's been described in this book, truthfully inspiring story!

Beginning C# 3.0: An Introduction to Object Oriented Programming

This is the book for those who want to understand the whys and hows of OOP using C# 3.0. You don't want to miss it.

alt text

Mastery: The Keys to Success and Long-Term Fulfillment, by George Leonard

It's about about what mindsets are required to reach mastery in any skill, and why. It's just awesome, and an easy read too.

Pro Spring is a superb introduction to the world of Inversion of Control and Dependency Injection. If you're not aware of these practices and their implications - the balance of topics and technical detail in Pro Spring is excellent. It builds a great case and consequent personal foundation.

Another book I'd suggest would be Robert Martin's Agile Software Development (ASD). Code smells, agile techniques, test driven dev, principles ... a well-written balance of many different programming facets.

More traditional classics would include the infamous GoF Design Patterns, Bertrand Meyer's Object Oriented Software Construction, Booch's Object Oriented Analysis and Design, Scott Meyer's "Effective C++'" series and a lesser known book I enjoyed by Gunderloy, Coder to Developer.

And while books are nice ... don't forget radio!

... let me add one more thing. If you haven't already discovered safari - take a look. It is more addictive than stack overflow :-) I've found that with my google type habits - I need the more expensive subscription so I can look at any book at any time - but I'd recommend the trial to anyone even remotely interested.

(ah yes, a little obj-C today, cocoa tomorrow, patterns? soa? what was that example in that cookbook? What did Steve say in the second edition? Should I buy this book? ... a subscription like this is great if you'd like some continuity and context to what you're googling ...)

Database System Concepts is one of the best books you can read on understanding good database design principles.

alt text

Algorithms in C++ was invaluable to me in learning Big O notation and the ins and outs of the various sort algorithms. This was published before Sedgewick decided he could make more money by dividing it into 5 different books.

C++ FAQs is an amazing book that really shows you what you should and shouldn't be doing in C++. The backward compatibility of C++ leaves a lot of landmines about and this book helps one carefully avoid them while at the same time being a good introduction into OO design and intent.

Here are two I haven't seen mentioned:
I wish I had read "Ruminations on C++" by Koenig and Moo much sooner. That was the book that made OO concepts really click for me.
And I recommend Michael Abrash's "Zen of Code Optimization" for anyone else planning on starting a programming career in the mid 90s.

Perfect Software: And Other Illusions about Testing

TITLE Cover

Perfect Software: And Other Illusions about Testing by Gerald M. Weinberg

ISBN-10: 0932633692

ISBN-13: 978-0932633699

Rapid Development by McConnell

The most influential programming book for me was Enough Rope to Shoot Yourself in the Foot by Allen Holub.

Cover of the book

O, well, how long ago it was.

I have a few good books that strongly influenced me that I've not seen on this list so far:

The Psychology of Everyday Things by Donald Norman. The general principles of design for other people. This may seem to be mostly good for UI but if you think about it, it has applications almost anywhere there is an interface that someone besides the original developer has to work with; e. g. an API and designing the interface in such a way that other developers form the correct mental model and get appropriate feedback from the API itself.

The Art of Software Testing by Glen Myers. A good, general introduction to testing software; good for programmers to read to help them think like a tester i. e. think of what may go wrong and prepare for it.

By the way, I realize the question was the "Single Most Influential Book" but the discussion seems to have changed to listing good books for developers to read so I hope I can be forgiven for listing two good books rather than just one.

alt text

C++ How to Program It is good for beginner.This is excellent book that full complete with 1500 pages.

Effective C++ and More Effective C++ by Scott Myers.

Inside the C++ object model by Stanley Lippman

I bough this when I was a complete newbie and took me from only knowing that Java existed to a reliable team member in a short time

Not a programming book, but still a very important book every programmer should read:

Orbiting the Giant Hairball by Gordon MacKenzie

The Pragmatic programmer was pretty good. However one that really made an impact when I was starting out was :

Windows 95 System Programming Secrets"

I know - it sounds and looks a bit cheesy on the outside and has probably dated a bit - but this was an awesome explanation of the internals of Win95 based on the Authors (Matt Pietrek) investigations using his own own tools - the code for which came with the book. Bear in mind this was before the whole open source thing and Microsoft was still pretty cagey about releasing documentation of internals - let alone source. There was some quote in there like "If you are working through some problem and hit some sticking point then you need to stop and really look deeply into that piece and really understand how it works". I've found this to be pretty good advice - particularly these days when you often have the source for a library and can go take a look. Its also inspired me to enjoy diving into the internals of how systems work, something that has proven invaluable over the course of my career.

Oh and I'd also throw in effective .net - great internals explanation of .Net from Don Box.

I recently read Dreaming in Code and found it to be an interesting read. Perhaps more so since the day I started reading it Chandler 1.0 was released. Reading about the growing pains and mistakes of a project team of talented people trying to "change the world" gives you a lot to learn from. Also Scott brings up a lot of programmer lore and wisdom in between that's just an entertaining read.

Beautiful Code had one or two things that made me think differently, particularly the chapter on top down operator precedence.

K&R

@Juan: I know Juan, I know - but there are some things that can only be learned by actually getting down to the task at hand. Speaking in abstract ideals all day simply makes you into an academic. It's in the application of the abstract that we truly grok the reason for their existence. :P

@Keith: Great mention of "The Inmates are Running the Asylum" by Alan Cooper - an eye opener for certain, any developer that has worked with me since I read that book has heard me mention the ideas it espouses. +1

I found the The Algorithm Design Manual to be a very beneficial read. I also highly recommend Programming Pearls.

This one isnt really a book for the beginning programmer, but if you're looking for SOA design books, then SOA in Practice: The Art of Distributed System Design is for you.

For me it was Design Patterns Explained it provided an 'Oh that's how it works' moment for me in regards to design patterns and has been very useful when teaching design patterns to others.

Code Craft by Pete Goodliffe is a good read!

Code Craft

The first book that made a real impact on me was Mastering Turbo Assembler by Tom Swan.

Other books that have had an impact was Just For Fun by Linus Torvalds and David Diamond and of course The Pragmatic Programmer by Andrew Hunt and David Thomas.

In addition to other people's suggestions, I'd recommend either acquiring a copy of SICP, or reading it online. It's one of the few books that I've read that I feel greatly increased my skill in designing software, particularly in creating good abstraction layers.

A book that is not directly related to programming, but is also a good read for programmers (IMO) is Concrete Mathematics. Most, if not all of the topics in it are useful for programmers to know about, and it does a better job of explaining things than any other math book I've read to date.

For me "Memory as a programming concept in C and C++" really opened my eyes to how memory management really works. If you're a C or C++ developer I consider it a must read. You will defiantly learn something or remember things you might have forgotten along the way.

http://www.amazon.com/Memory-Programming-Concept-C/dp/0521520436

Agile Software Development with Scrum by Ken Schwaber and Mike Beedle.

I used this book as the starting point to understanding Agile development.

Systemantics: How Systems Work and Especially How They Fail. Get it used cheap. But you might not get the humor until you've worked on a few failed projects.

The beauty of the book is the copyright year.

Probably the most profound takeaway "law" presented in the book:

The Fundamental Failure-Mode Theorem (F.F.T.): Complex systems usually operate in failure mode.

The idea being that there are failing parts in any given piece of software that are masked by failures in other parts or by validations in other parts. See a real-world example at the Therac-25 radiation machine, whose software flaws were masked by hardware failsafes. When the hardware failsafes were removed, the software race condition that had gone undetected all those years resulted in the machine killing 3 people.

It seems most people have already touched on the some very good books. One which really helped me out was Effective C#: 50 Ways to Improve your C#. I'd be remiss if I didn't mention The Tao of Pooh. Philosophy books can be good for the soul, and the code.

Discrete Mathematics For Computer Scientists

Discrete Mathematics For Computer Scientists by J.K. Truss.

While this doesn't teach you programming, it teaches you fundamental mathematics that every programmer should know. You may remember this stuff from university, but really, doing predicate logic will improve you programming skills, you need to learn Set Theory if you want to program using collections.

There really is a lot of interesting information in here that can get you thinking about problems in different ways. It's handy to have, just to pick up once in a while to learn something new.

I saw a review of Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools on a blog talking also about XI-Factory, I read it and I must say this book is a must read. Altough not specifically targetted to programmers, it explains very clearly what is happening in the programming world right now with Model-Driven Architecture and so on..

Solid Code Optimizing the Software Development Life Cycle

Although the book is only 300 pages and favors Microsoft technologies it still offers some good language agnostic tidbits.

Managing Gigabytes is an instant classic for thinking about the heavy lifting of information.

My vote is "How to Think Like a Computer Scientist: Learning With Python" It's available both as a book and as a free e-book.

It really helped me to understand the basics of not just Python but programming in general. Although it uses Python to demonstrate concepts, they apply to most, if not all, programming languages. Also: IT'S FREE!

Object-Oriented Programming in Turbo C++. Not super popular, but it was the one that got me started, and was the first book that really helped me grok what an object was. Read this one waaaay back in high school. It sort of brings a tear to my eye...

My high school math teacher lent me a copy of Are Your Lights Figure Problem that I have re-read many times. It has been invaluable, as a developer, and in life generally.

I'm reading now Agile Software Development, Principles, Patterns and Practices. For those interested in XP and Object-Oriented Design, this is a classic reading.

alt text

Kernighan & Plauger's Elements of Programming Style. It illustrates the difference between gimmicky-clever and elegant-clever.

to get advanced in prolog i like these two books:

The Art of Prolog

The Craft of Prolog

really opens the mind for logic programming and recursion schemes.

Here's an excellent book that is not as widely applauded, but is full of deep insight: Agile Software Development: The Cooperative Game, by Alistair Cockburn.

What's so special about it? Well, clearly everyone has heard the term "Agile", and it seems most are believers these days. Whether you believe or not, though, there are some deep principles behind why the Agile movement exists. This book uncovers and articulates these principles in a precise, scientific way. Some of the principles are (btw, these are my words, not Alistair's):

  1. The hardest thing about team software development is getting everyone's brains to have the same understanding. We are building huge, elaborate, complex systems which are invisible in the tangible world. The better you are at getting more peoples' brains to share deeper understanding, the more effective your team will be at software development. This is the underlying reason that pair programming makes sense. Most people dismiss it (and I did too initially), but with this principle in mind I highly recommend that you give it another shot. You wind up with TWO people who deeply understand the subsystem you just built ... there aren't many other ways to get such a deep information transfer so quickly. It is like a Vulcan mind meld.
  2. You don't always need words to communicate deep understanding quickly. And a corollary: too many words, and you exceed the listener/reader's capacity, meaning the understanding transfer you're attempting does not happen. Consider that children learn how to speak language by being "immersed" and "absorbing". Not just language either ... he gives the example of some kids playing with trains on the floor. Along comes another kid who has never even SEEN a train before ... but by watching the other kids, he picks up the gist of the game and plays right along. This happens all the time between humans. This along with the corollary about too many words helps you see how misguided it was in the old "waterfall" days to try to write 700 page detailed requirements specifications.

There is so much more in there too. I'll shut up now, but I HIGHLY recommend this book!

alt text

The Back of the Napkin, by Dan Roam.

The Back of the Napkin

A great book about visual thinking techniques. There is also an expanded edition now. I can't speak to that version, as I do not own it; yet.

Agile Software Development by Alistair Cockburn

Do users ever touch your code? If you're not doing solely back-end work, I recommend About Face: The Essentials of User Interface Design — now in its third edition (linked). I used to think my users were stupid because they didn't "get" my interfaces. I was, of course, wrong. About Face turned me around.

"Writing Solid Code: Microsoft's Techniques for Developing Bug-Free C Programs (Microsoft Programming Series)" by Steve MacGuire.

Interesting what a large proportion the books mentioned here are C/C++ books.

While not strictly a software development book, I would highly recommend that Don't Make me Think! be considered in this list.

As so many people have listed Head First Design Patterns, which I agree is a very good book, I would like to see if so many people aware of a title called Design Patterns Explained: A New Perspective on Object-Oriented Design.

This title deals with design patterns excellently. The first half of the book is very accessible and the remaining chapters require only a firm grasp of the content already covered The reason I feel the second half of the book is less accessible is that it covers patterns that I, as a young developer admittedly lacking in experience, have not used much.

This title also introduces the concept behind design patterns, covering Christopher Alexander's initial work in architecture to the GoF first implementing documenting patterns in SmallTalk.

I think that anyone who enjoyed Head First Design Patterns but still finds the GoF very dry, should look into Design Patterns Explained as a much more readable (although not quite as comprehensive) alternative.

Even though i've never programmed a game this book helped me understand a lot of things in a fun way.

How influential a book is often depends on the reader and where they were in their career when they read the book. I have to give a shout-out to Head First Design Patterns. Great book and the very creative way it's written should be used as an example for other tech book writers. I.e. it's written in order to facilitate learning and internalizing the concepts.

Head First Design Patterns

97 Things Every Programmer Should Know

alt text

This book pools together the collective experiences of some of the world's best programmers. It is a must read.

Extreme Programming Explained: Embrace Change by Kent Beck. While I don't advocate a hardcore XP-or-the-highway take on software development, I wish I had been introduced to the principles in this book much earlier in my career. Unit testing, refactoring, simplicity, continuous integration, cost/time/quality/scope - these changed the way I looked at development. Before Agile, it was all about the debugger and fear of change requests. After Agile, those demons did not loom as large.

One of my personal favorites is Hacker's Delight, because it was as much fun to read as it was educational.

I hope the second edition will be released soon!

You.Next(): Move Your Software Development Career to the Leadership Track ~ Michael C. Finley (Author), Honza Fedák (Author) link text

I've been arounda while, so most books that I have found influential don't necessarily apply today. I do believe it is universally important to understand the platform that you are developing for (both hardware and OS). I also think it's important to learn from other peoples mistakes. So two books I would recommend are:

Computing Calamities and In Search of Stupidity: Over Twenty Years of High Tech Marketing Disasters

Working Effectively with Legacy Code is a really amazing book that goes into great detail about how to properly unit test your code and what the true benefit of it is. It really opened my eyes.

What are real-world problems where a recursive approach is the natural solution besides depth-first search (DFS)?

(I don't consider Tower of Hanoi, Fibonacci number, or factorial real-world problems. They are a bit contrived in my mind.)

The best example I know is quicksort, it is a lot simpler with recursion. Take a look at:

shop.oreilly.com/product/9780596510046.do

www.amazon.com/Beautiful-Code-Leading-Programmers-Practice/dp/0596510047

(Click on the first subtitle under the chapter 3: "The most beautiful code I ever wrote").

I'm interested in building a regex engine, as a side-project, just for learning purposes.

I know the theory behind evaluation of regular expressions, and have a sufficient understanding of finite state machines etc.

What I'm interested in is how a regex engine is implemented in software. So I was wondering if there was any sort of tutorial or online resource that explains the implementation of a regex engine, translation from the regex to a FSM and so on. I don't want any sites that just explains the theory behind it.

Thanks.

In first chapter of Beautiful Code (Amazon, online draft) Brian Kernighan talks about Rob Pike's elegant, very small regex matcher. It's really simple, but Kernighan gives seven exercises to extend it, which might be a good intro for you.

This is related to a chapter from beautiful code. And in that chapter I read about the nested ifs.

The author was talking about deeply nested ifs as orginator of bugs and less readable. And he was talking about replacing nested ifs with case statements and decision tables.

Can anybody illustrate how to remove nested ifs with case (select case) and decision tables ?

Well, not directly an answer to your question since you specifically ask about switch/case statements, but here is a similar question.

Invert “if” statement to reduce nesting

This talks about replacing nested if's with guard-statements, that return early, instead of progressively checking more and more things before settling on a return value.

For decision tables, please see my answer to this question, or better still read chapter 18 in Code Complete 2.

I am build a very large dictionary and I am performing many checks to see if a key is in the structure and then adding if it unique or incrementing a counter if it is identical.

Python uses a hash data structure to store dictionaries (not to be confused with a cryptographic hash function). Lookups are O(1), but if the hash table is full the it has to be rehashed which is very expensive.

My Question is, would I be better off using a AVL Binary Search Tree or is a hash table good enough?

Python dictionaries are highly optimized. Python makes various special-case optimizations that the Python developers cater for in the CPython dictionary implementation.

  1. In CPython, all PyDictObject's are optimized for dictionaries containing only string keys.
  2. Python's dictionary makes an effort to never be more than 2/3rds full.

The book "Beautiful Code" discusses this all.

The eighteenth chapter is Python's Dictionary Implementation: Being All Things to All People by Adrew Kuchling

It is much better to use it than try to achieve the hand crafted custom implementation which will have to replicate all these optimizations to be any where near the main CPython implementation of dictionary look ups.

What are some of the open source projects out there that you would hold up as shining examples of projects that correctly and effectively use enterprise sofware patterns and best practices such as Inversion of Control, Model-View-Controller, Unit Testing, etc.?

For purposes of this question the project should:

  1. Include source code that illustrates the pattern in use, and
  2. Be doing something important and useful, i.e. not using the pattern frivolously just because it is flavor of the week. Hence the words, "Correctly and Effectively" in the question

It should be software that you could show to the people who work for you and enthusiastically be able to say, "I want you to do it the way these guys did it."

You can try this book - Beautiful Code

The author has collected some experience-sharing articles of open source projects. e.g. Python's Dictionary Implementation, Subversion's Delta Editor, etc.

Apologies if this question is too open-ended for the site, but it just seemed the best place to ask it.

I am a self-taught programmer with little maths in his educational background and who has, through the course of a ten-year career moved slowly from front-end web scripting and web development to middle and data-tier software engineering. As a result there are areas of my knowledge and experience that are somewhat lacking.

After a recent review with my manager, it was indicated to me that overcoming these gaps was all that was standing between me and a promotion to a senior engineer role. However in order to get that, I was going to have to find for myself a structured approach to learning and demonstrate that I'd taken on board what I needed to know.

Personally I'd identify my areas of weakness as follows. Be aware that the problem in a lot of cases is not that I don't understand, technically, how these things work but that I don't see where it is or is not appropriate to apply them. For example I know what an Interface is and, technically, what it does, but I have a hard time differentiating when it's appropriate to use an Interface over, say, a group of related OO classes which inherit from a base class. So it's kind of more ignorance of good software design than it is technical ignorance - I do have trouble appreciating, digesting and working on things like loosely coupled systems.

  • Interfaces
  • Delegates
  • Design Patterns
  • Network architecture & protocols

Also I've never done some of the low-level stuff like compilers and suchlike. I wonder sometimes if it'd make a big difference to my ability to write code which is not only effective but well optimised if I had a better knowledge of this sort of material.

Sometimes the worry that I can't identify weaknesses in my skill set because I don't know how to ask the right questions knaws away at me. So, in the hope that I've framed the question properly, I'd like your suggestions on:

  • From the sound of what I'm currently lacking are there any other topics I should think about looking at?
  • Where are some good resources for learning this material?
  • Are there any structured, self-taught courses I can work through that are relevant? I don't, sadly, have time to take a formal qualification.

Cheers, Matt

I was a self taught coder not so long ago so I can relate to your position. Since then I've shipped 10 Millions LOC applications, so I had to develop discernment. 3 things helps me to get software engineering : books, code and people.

First of all, good engineering is about beauty, the beauty of an elegant design, of an efficient mecanism. You need to develop that sense for beauty and to do that you need to see it and discuss it.

Books like SICP, Refactoring, Head First Design Patterns and Beautiful Code are all about beautiful/better code. Most of the time they are not about a language per se (or about exotic languages). Code complete is also interesting but somehow more low level.

Online reading of code is also a good way to educate your taste. I have no example in mind but this is a common question, you should easily find some ideas. Also, building an ambitious application (a game, 3d modeler, web server, database) is a good practive : you're likely to redo it 2 or 3 times to have a better architecture.

People is also very important. If you find a/a few passionate software architect(s) to discuss with, you will be able to confront your view on what is beauty. I am still digesting some discussion I had with my manager a few years ago.

This "enlighment" is an ongoing process, so don't get discouraged and just move forward. One day, you'll see ugly code with an obvious alternative implementation, one you could discuss and compare objectively as better than the original.

I like reading open-source code to see how particular problems have been solved, or simply to study how to create nice and clean code.

I was wondering if there actually was any good book out there that goes through excerpts of different (preferably in Java) open-source projects to show how patterns have been used and implemented, some nifty tricks, etc.?

Update: I took design patterns as an example, but it’s not really what I am after. I read a lot of open-source code, and I often find interesting ways of doing things which I didn’t think of before – my question is whether there is a book that shows some “cool” open-source code, a bit like how Clean Code uses FitNesse code to illustrate refactoring and other points.

Well, you can read just book about open source project, and authors can show what and how. E.g. I read Pro Spring 2.5 and there is even chapter called "Spring Patterns" with explanation of why and how they call files, directories, design patterns they use and invite you to use etc. Probably take a look at the books about open source projects you investigate.

UPDATE (just that paragraph insert to extend answer:) : as I told previously, you can look through the books about open source projects and find there information how this project is developed, architectural issues etc. Once I looked for real good example of "Open/Closed Principle" using, theory is nice but I would not say that it is so clear how to use it. The only book which helped me was Expert Spring MVC and Web Flow (I already pointed you to google books with that chapter I read). I didn't read the whole book, but I am sure it contains a lot of such things (what and how was used to make Spring done). From book Clean Code: A Handbook of Agile Software Craftsmanship I remember that there is a chapter, when they take a code from one open source project and make it better (unfortunately open source does not mean that it is good enough); that book also contain reference to how some other projects where written (e.g. jUnit). I don't know any book, which is completely dedicated to any project, there are just books where is "theory", and books about project which can have some explanation of what is inside. I would recommend books from APress (Pro and Expert series, afaik "beginning" books does not contain such explanation), and Packt Publishing - their main topic is open source.

UPDATE 2 (just can't stop :) Just remembered new series of books from OReilly "Beautiful ...." - I never read it, but I looked through. It actually consists of different stories behind development, real stories from life. I see there is also Beautiful Code: Leading Programmers Explain How They Think - I should contain what you need. Other "beautiful" books can be worth of your time too.

About patterns in general there are a lot of good books, and it depends on what exactly are you looking for. E.g. Head First Design Patterns is quite good to explain common patterns in fun way. If you need more, you can take a look at Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions to see how different applications, systems etc. can be integrated (and how open source projects do it too). Etc. Just specify what patterns or tricks do you want to read about, community will make its suggestion ;)

Some web links out of my bookmarks:

  1. Anti Patterns Catalog - know what you are not going to do!
  2. Design Patterns and Martin Fowler's Catalog - that's shortly about what is good to use and know about
  3. SOA patterns - community site for SOA patterns (integration etc.)

And few more books to take a look at:

  1. Head First Object-Oriented Analysis and Design
  2. Agile Software Development, Principles, Patterns, and Practices
  3. Code Complete - this book is just a bible of how to write code...

people, who develop open source definitely know what are those books about ;)

Hope that helps

UPDATE (25-05-2011) Just found one book, which I definitely going to buy, and I think it perfectly fits your question:

The Architecture of Open Source Applications
enter image description here

Architects look at thousands of buildings during their training, and study critiques of those buildings written by masters. In contrast, most software developers only ever get to know a handful of large programs well — usually programs they wrote themselves — and never study the great programs of history. As a result, they repeat one another’s mistakes rather than building on one another’s successes. This book’s goal is to change that. In it, the authors of twenty-five open source applications explain how their software is structured, and why. What are each program's major components? How do they interact? And what did their builders learn during their development? In answering these questions, the contributors to this book provide unique insights into how they think. Electronic versions of The Architecture of Open Source Applications for e-readers will be available for download soon.

I am looking for examples of reasonably short, but reasonably complicated segments of code (objects, functions, classes, a particular set of variable names, etc) that strike that perfect zen like balance of self documentation and implementation elegance.

It could either be something you are really proud of or something that you came across and experienced an "Aha!" moment of enlightenment.

Some potential criteria (not all need to be met in a single example):

  • Sparse and Focused
  • Self evident. Perhaps so clearly written that even a non programmer could understand what you are trying to do, even if they don't understand the syntax or implementation details.
  • Manifestly Useful (has multiple use cases, e.g. a sorting algorithm, handy recursive method, etc.)
  • Clever
  • Enlightening
  • Production quality and functional (e.g. not pseudo code)

I am looking for an example snippet followed by a brief commentary of what makes the code special. Of course the best examples will require minimal additional commentary because they are well documented.

Note to moderators: I am new to stackoverflow, so if this question is somehow not appropriate or must be closed, can you provide an explanation of where it runs afoul of stackoverflow's norms? I am not intending to waste people's time.

The goal of this question it to learn good commenting practices through examples provided and rated by the community.

I recommend you read Beautiful Code. It's a great example of what you're after.

alt text

I want to write regular expression library in C/C++. What is the good starting point , any books or articles.

I know there are may libraries are available , but I want to write my own version.

[Edit 16-Jan-2015] I recently encountered this beautiful book Beautiful Code. I recommend you go through Chapter 1, "A Regular Expression Matcher" by Brian Kernighan.

You can read the classic paper by Ken Thompson, "Regular expression search algorithm" ... http://portal.acm.org/citation.cfm?doid=363347.363387 ... this paper should give you a good understanding on how regular expressions are matched using finite automata.

This is another page giving some detailed information by Russ Cox ... http://swtch.com/~rsc/regexp/

Hope these help you get started.

Does Oracle have built-in string character class constants (digits, letters, alphanum, upper, lower, etc)?

My actual goal is to efficiently return only the digits [0-9] from an existing string.

Unfortunately, we still use Oracle 9, so regular expressions are not an option here.

Examples The field should contain zero to three letters, 3 or 4 digits, then zero to two letters. I want to extract the digits.

String    --> Result
ABC1234YY --> 1234
D456YD    --> 456
455PN     --> 455

If you are able to use PL/SQL here, another approach is write your own regular expression matcher function. One starting point is Rob Pike's elegant, very tiny regular expression matcher in Chapter 1 of Beautiful Code. One of the exercises for the reader is to add character classes. (You'd first need to translate his 30 lines of C code into PL/SQL.)

I'm trying to learn how to make my application has the same "face" in all files, the same pattern, but I do not know if this is the right thing to do.

I want know if the more correct in software development, is to limit the application to only one type of pattern.

For example, that's how my application looks like (just a piece)

Api.js:

'use strict'
var Server = require('./server');
var Api = {
 init: function() {
   Server.init('start');
 }
};

Server.js:

'use strict'
var Server = {
 init: function(command) {
  this.command = command;

  if (command === 'start') {
    this.start();
  }
 }
};

I'm using the "initializer object pattern" in all my application. So i'm avoiding decorator pattern, facade, everything.

Should i avoid or i can use more than one? If the right answer is use several, depending on the needs, i have other question. This doesn't make the maintenance more difficult? Is not make the code like a spaghetti?

Thanks.


Update.

I'm going to try explain again, this time with a bounty.

i already try to ask but seems that no one really can give me a concise answer.

I would like to know what are the secrets from making a good app, a good web app, talking about code appearance. I want know if I should maintain the same standard code throughout my hole application, if this is GOOD, or really doesn't matter.

For example, i have two EXAMPLES files

app.js:

var server = require('./server');

var app = {
 init: function() {
   server.init('DEVELOPMENT');
 }
};

module.exports = app;

server.js:

var server = {
 init: function(env) {
  if (env === 'DEVELOPMENT') {
    // CODE
  } else {
    // CODE
  }
 }
}

module.exports = server;

In this case, i'm using one object with method init, which is the pattern that i'm using in my hole app..

Or it doesn't matter, i should write anything:

first object:

var server = require('./server');

var app = {
 init: function() {
   server('DEVELOPMENT');
 }
};

module.exports = app;

than server as a function:

var server =function(env) {
  if (env === 'DEVELOPMENT') {
    // CODE
  } else {
    // CODE
  }
}

module.exports = server;

I can give 100 of my points. it's incredible how i can't find a good answer for this particular issue.

Thanks.

Should I using other patterns?

No, you should not insist on a single pattern.

No design pattern books will ever advise you to use a single pattern. Just like you cannot chop all ingredients in one single way (are you going to dice the spaghetti?), you cannot organise all logic in one single pattern.

Sure, you can make all your Objects use the initialiser pattern, and don't use constructors at all. This is ok. Been there, done that. I like it.

But these objects can be used with Builder or Abstract Factory (if it make things simpler). As long as the builders/factories themselves have initialiser, and that they properly initialise the created objects, then your use of the initialiser pattern will be consistent. Outside of creational patterns, it is usually good to organise objects with structural and behavioural patterns. They do not conflict with initialiser at all.

For example, look at DOM. All nodes are created by the Document object - elements, text nodes, comments, even events. This is the Factory pattern.

Yet the Document object is also a Facade! From it you access the whole system's status, objects, data, you can even write to it! Every DOM operation starts from the Document, it is the Facade of the DOM system.

DOM nodes also implements multiple patterns. They are organised in Composite, let you listen to events with Observer and Command, and handle events in a Chain of Responsibility. They are certainly parsed by an Interpreter, DocumentFragment is a Proxy, svg elements are implemented as Decorators, and createNodeIterator obviously gives you an Iterator.

The point is, good object-oriented design will yield multiple design patterns as a result, intentional or not.


What are the secrets for good code appearance

I think the best looking code is the one that is easiest to understand to you, and the way you read code changes as you gain more experience.

For example my style is too condensed for most programmers, but to me it strikes a good balance. So do develop your own style - you are not me, and you are not yesterday's you either.

Remember this as we go through the styles.

At the lowest level we have coding style - most importantly indent and bracket.

This one is simple, pick the one you like and stick with it. There are language specific styles, and they are often good starting points. Configure your IDE's formatter so that you can format all your code with hotkey.

Above the code syntax we have comment style and naming convention.

Setting rules on comment is fine, sometimes it is necessary for documenting tools. Avoid too much comment in practice. You may also want to decide your namespace and your stand on naming function expressions.

Above these structures, we have logic conventions.

The same code logic can often be done in many ways, some more 'beautiful' than the others in your eyes. Look at this example.

I picked the second style on first sight: no duplicate, logic is sectioned cleanly, format is not my style but reasonable. But many programmers would prefer the first style: logic is plain as day, a few duplications is worth it. While abstract, this level is quite deep - present your logic the wrong way actually increase the chance an experienced programmer read it wrong.

Finally, we arrives at the level of design pattern, about as far as code beauty goes.

The key to keep your code structure beautiful, is using the right patterns at right level to consistently accomplish loose coupling and code reuse, while avoiding pitfalls and over-design.

There are quite some books about beautiful code, and then there are even more books about designing and implementing beautiful software. (Decide for yourself which are beyond your level.) Knowledge is as important as experience, and you can gain them only by spending your time to study, to write, and to revise/refactor your apps.

Feel free to change your mind as you explore and experiment with your code. Changing your mind is a good sign of learning.

But first, familiarise yourself with design patterns. Just don't forget, they are the generic result of applying object-oriented principals to common tasks. It is still up to you to do the design.

Design Patterns Are Not Silver Bullets.