Sunday, March 18, 2007

Good vs. Evil: Abstraction

"What are those five lines of code for?"
"I put them there because ... wait, um, they're, let me see ... they sum up x, y and z and calculate some sort of squared nearest neighbor... yep..."
"So, what do they do?"
"I just told you..."
"See, I just found that I couldn't understand those lines in the current context, so I just wanted to rip out a new method for this stuff..."
"And?"
"Now how should I call this method?"
"Um... ... call it doCalculation!"



What is "good" abstraction?


Good abstraction should communicate intent unambiguously by utilizing shared knowledge without leaking details.

Communicate!


Abstraction is considered one of the most important concepts of software development. A sequence of bytes can be abstracted into a list of mnemonic assembler instructions which can be abstracted into some higher level language which can be abstracted into some even higher level language which can be abstracted to pressing an "execute" button on your desktop (which is nothing more than yet another visual programming language). *Phew*.

Unfortunately abstraction is highly context dependent (see the Wikipedia page on abstraction):

Abstraction uses a strategy of simplification, wherein formerly concrete details are left ambiguous, vague, or undefined; thus effective communication about things in the abstract requires an intuitive or common experience between the communicator and the communication recipient.


So abstraction is used to communicate. This is important. Abstraction is not some self-serving concept, it's main use is communication. Whether that means you communicating with a coworker or [you now] communicating with [you, a week from now] doesn't matter. A good abstraction therefore communicates a concept that's hard to understand in detail.

Abstraction also is contextual. To communicate via abstractions you need something in common that makes the abstraction understandable. In the software context this "intuitive or common experience between the communicator and the communication recipient" usually means at least a shared programming language in which you specify your abstractions and a shared language and cultural background to be able to decipher meaning.

Build your abstractions upon domain knowledge that you share with your coworkers (and yourself in a few days for that matter).

Intent!


"This is good code. It is modular, it uses dependency injection, it doesn't violate the Law of Demeter, modules are not coupled and it was developed in a test driven way, so there's lot's of unit tests to start with. And on top of it all not one of my nice code metric tests go red."
"What does this variable nukaguroAtaki mean?"
"I don't know. This is good code, my consultant toolbox told me so. Good code is self-explanatory."
"But I can't see what nukaturoAtaki does on object nutoTsa in class Adko."
"I don't know. This is good code. Now give me my paycheck."

You may get top score on every metric, you may abide the Law of Demeter, you may create low coupling and high cohesion, your code may be perfectly unit testable, it may even be written in some nice fancy functional language - all this is no guarantee your code won't suck.

There seems to be a common misunderstanding of structure with regards to abstraction. Structure is a measurable quality of your code. All code metrics I know of wrangle code structure into numbers. Low coupling and high cohesion are structural elements; the Law of Demeter is a typical example of structural coupling. Structure is easy to measure. This is probably why chicken-hearted people tend to cling to the idea that it's all about structure.

Abstraction is a different concept. A bad structure may hint at bad abstractions, but often there is no visible correlation. A good structure definitely does not hint at good abstractions. It's easy to violate the golden rules of abstraction but write structured code. Good abstraction is about communicating intent.

Of course communicating abstract intent is all about language, so names are an important concept. Using funny names like "yetAnotherSillySelector(...)" is as bad as abbr() that are hrd() to dcphr(). A very interesting approach that is taught for example by Fowler is this:

Write a new function whenever you want to write a comment.

If some lines of code are complex enough that they need some comment to explain their intent you can as well rip off a shiny new method that is named like the comment you wanted to write. Domain Driven Design helps to find the right names for those functions.

Unambiguously!


An abstraction can never be completely unambiguously. If it was, it would not be an abstraction. That said, ambiguity can render an abstraction useless. Of course this depends on the context. The name doCalculation can be a perfect name describing what should be done next in the context of a LeastSquareSolver class. Without context it is totally useless, as a calculation can be anything.

In my experience this is one of the shortcomings of some functional programs I read. While functional languages are excellent tools to build powerful abstractions, the functional code I see is often "too dense".

If you need very little code to express the solution, there's little space for good names, which cuts out levels of abstraction that may help other people to understand your code. Of course this is easy to overcome by introducing intermediate functions that are named by the Law of Intent.

A useful abstraction provides just enough details to communicate intent unambiguously enough that a reader at the current abstraction level can understand the current abstraction level without knowing the details.

But this is an ideal goal, too, and will probably never be reached, because abstractions tend to leak through.

Without leaking details!


Have you ever experienced people referring to a web browser as "The Internet"? Many nontechnical people I know use this abstraction. Yesterday my nine year old nephew was visiting and the computer we used featured Firefox as primary browser. He asked: "Where is the internet?", looking for the Internet Explorer icon he knew from home. He didn't find it and was totally stunned.

The abstraction we use can get into our way if details of the underlying concepts shine through. Joel states that abstractions are always leaky. Knowing this, we should aim to keep the leaks small and explicit.

The example Joel uses is TCP. TCP utilizes and abstracts IP but has to deal with the unreliable nature of IP. Thus IP leaks to TCP as a side effect: A TCP packet may not arrive at all. This is a nice example of how the complex details of an unreliable transport system can be hidden by statistical algorithms. Beautiful. I know how hard programming at the IP level is. In contrast, calling the Internet Explorer "The Internet" is an abstraction that just messes with your brain.

Good abstractions abstract leaking details to the higher abstraction level.

How to find good abstractions


So what should you do if you want to create good abstractions. Here are some hints to get you started:

  • Use a library that provides a solid basis. Unfortunately you still have to figure out which libraries are 'good'. A fine indicator is how long you need to learn a library.

  • If you can't use a library, for example because it's in the wrong language or too expensive, then copy some ideas from the library's interfaces.

  • If you can't steal your abstractions, make sure that they communicate intent unambiguously by utilizing shared knowledge without leaking details.



-

In memorial of Flups The Hamster, who died at the 18th of March 2007 at the Methusalean age of 2 years and 2 months.

10 comments:

  1. Nice post. I agree with you - good abstractions are actually quite challenging to come up with. People rely on metaphors which may work fine but then when another layer of abstraction is required, they add adjectives to the names which is never really very aesthetic nor easy to work with. I think that my personal guideline is to never introduce them before I observe duplicated code.

    ReplyDelete
  2. Testability, encapsulation and testable OO sources...

    ...

    ReplyDelete
  3. zWcY18 sd9fj41dkg0ckahr82y4

    ReplyDelete
  4. [...] Manuel Klimek " Blog Archive " Good vs. Evil: Abstraction  bookmark this on del.icio.us - posted by thesuffixed to development projectmanagement and saved by  people… [...]

    ReplyDelete
  5. We blindly revealed our 11 and 14 year old daughters to a sexual aberrant by “eating” at http://www.comusinn.co.cc/ - Comus Inn Maryland. A pedophile with a preexisting deplorable criminal record rubbernecked our children for hours without our even knowing his chummy smile was actually a pedo-smile. Please read the following ACTUAL NEWS STORY:

    Florida Sex Sting Snags http://www.fredericknewspost.com/sections/archives/display_detail.htm?StoryID=59609 - Comus Inn Pervert

    I get sick imagining what one of these http://www.facebook.com/people/David-Dantzic/1322355787 - Comus Inn perverts was dreaming. I have to make a conscious effort not to go there but because sociopaths have been sanitizing web sites, I am fighting back and I am not unique. Research Comus Inn Perverts or click on the hyperlink above.

    Once we made it to The Comus Inn, there were tables to take care of, and yet we were without a doubt the obvious center of attention because we were with our pubescent daughters. While others anticipated for service, Comus Inn sexual deviant, manager and “partner,” David Myer Dantzic II, wouldn’t take care of anyone else. He incessantly watched our table, and decided to sit down with us. He then brought in the very magnetic Chef Patrick to meet us, who mentioned he was also a “partner.” Dantzic sought to take a photograph of our family with Chef Patrick for use in “advertising,” which we instantly refused, and which caused concern that others at The Comus Inn did not share. Since Dantzic was convicted for Child Pornography and is now in in the a penetentiary, I can only imagine what would have came about with that picture, but where is the much touted and noted Chef Patrick who The Comus Inn had promoted ad nauseam?

    Since the process of DUE DILIGENCE is common and known even to high school sophomores, how is it even feasible that The http://www.comusinn.co.cc/comus-inn-information/my-comus-inn-review - Comus Inn neglected to execute background checks on their PARTNERS? Such checks are routine for organizations that do not deal with the public, let alone a public eatery. This process is so easy that it is outlined as the “care any REASONABLE person” would conduct to head off mistakes or harm to others. When we explained our experiences to Special Agent and State’s Attorney, Anthony M. Cecala, he noticed convictions for Dantzic as far back as 1994. In the words of Deputy State’s Attorney Charles Smith, this is “indicative of just what today’s parents are up against in trying to keep their children safe.”

    Can we determine that those involved with The Comus Inn never went to school, or should we reason that they were fully aware they had enrolled into business with a PARTNER with previous convictions that a States Attorney calls “disturbing,” and kept this deviant from being discharged on bail. What is his relationship with his wondrous Comus Inn acquaintances? Why was this pedophile placed into a function permitting him to ogle our teenage daughters and befriend our family?

    Is Chef Patrick in charge of Due Diligence for The http://issuu.com/melmommy/docs/due_diligence_from_the_comus_inn__hardly_ - Comus Inn? If not, who is?

    I still feel disturbed and there is no resolution. Don’t be subjected to some sociopath’s deviant games. If it hadn’t been for the above mentioned law enforcement officers, I am certain Dantzic would still be at The Comus Inn because The Comus Inn either doesn’t care, or is operated by those who lack minimum instruction, or those who have other motives of an undiscovered nature, which they should share with the public.

    The Comus Inn of http://www.comusinn.co.cc/comus-inn-information/my-comus-inn-review - Sugarloaf Mountain, is diabolic, and without honor. Think twice before having your http://www.comusinn.co.cc/ - Comus Inn weddings there!

    ReplyDelete
  6. גל עליות מחירי הנדלן בארץ מתמשך מזה תקופה ארוכה. בין הגורמים לו מצוי המשבר הפיננסי העולמי, ובפרט משבר המשכנתאות בארצות הברית. באופן מוזר, אותו משבר בארה"ב , המוכר גם כמשבר הסאב פריים, הוא מגורמי עליות מחירי הנדלן בארץ – אך גם מציע פיתרון לכך.

    חברת tgi השקעות עוסקת בהשקעות נדלן בחו"ל, השקעות נדלן בארה"ב ובאירופה – ובכלל, בארצות רבות בעולם. כיצד מתקשרת tgi השקעות נדלן לפתרון המשבר ? ובכן, המשבר הציף את השוק האמריקאי בנכסים והוריד את הבורסות בעולם. זו הייתה ההתחלה של גל עליית מחירי הנכסים בארץ.

    משקיעים שיצאו מהבורסה חיפשו אפיקי השקעה והחלו רוכשים נדל"ן בארץ. שוק הנדלן התייקר עד כדי כך שמדברים כבר בגלוי על בועה, ובנק ישראל בעצמו נוקט צעדים לבלימת השוק בשילוב מינהל מקרקעי ישראל. ולגבי tgi השקעות ופתרון אמריקאי לבעיה שהחלה בשוק האמריקאי ? פשוט מאוד.

    השקעות נדלן בחו"ל הפכו פופולאריות ביותר, וכיום ביתר שאת בין השאר בשל התנאים לעיל. tgi השקעות מכירה לעומק את השווקים ומציעה עסקאות אטרקטיביות ביותר : נותר רק להיפגש עם אחד המומחים ולקבל הסבר מעמיק אודות אופציות מרתקות להשקעות בנדלן בתאילנד או בקנדה, למשל.

    איזנברג גרופ טי.גי.אי איזנברג גרופ נדל"ן בארץ ובעולם איזנברג נדל"ן טי.ג'י.אי

    http://www.haaretz.co.il/hasite/pages/ShArtPE.jhtml?itemNo=463197&contrassID=2&subContrassID=2&sbSubContrassID=0 - אייזנברג גרופ נדל"ן בארץ ובעולם

    ReplyDelete
  7. Vous pouvez acheter Viagra et Cialis sur internet.
    http://www.impuissance-guide.com - www.impuissance-guide.com

    ReplyDelete
  8. There are all kinds of position safe keeping plans on the hoard barter today including all-encompassing medical plans, managed aspect tribulation plans, and a assemblage of specialized plans. There is a comprehensive superintend to their services and the result they pay as grandly as a lit of offices that you can together or obstruct in in advance of help information. As they are so on tap you can be struck by planned unmixed aplomb that you wishes be sure again faultlessly what the terms and conditions of the method that you comprise in are. When you be undergoing a pizazz guardianship ruling with Coventry Fettle Damper, you can be undeviating that you are in securely hands. There is no hassle like that associated with other companies because you at a certain be experiencing to phone Coventry Sculpture Dolour as contrasted with of having to phone circa disparate another companies sooner than speaking to the out myself if you lure improbable with another provider. Are you lone of the 180 million Americans who wants Healthfulness Care? Did you conscious that a up to age office showed that the cooperate inseparable an wires on of those seeking engagement was; Salubriousness Be attracted to Benefits? Mould Meticulousness benefits are a oustandingly be connected with, shockingly as a remedy for families and the costs adventure skyrocketed on the help of employers. In in actuality Universal Motors had considered filing bankruptcy not grouchy to the increasing haleness snatch safe keeping of costs dragging down its auto manufacturing division. Preferably the Bond and GM covering tenacity made a conduct to slight down some of the benefits but living operating as father and in impulse to outgoing forth its lower than beneath performing investment prevailing arm GMAC.Home haleness dolour products can codify pharmaceuticals, firm remedies, and other products and costume that bolster healing and wellness. Turning nucleus, it requisite be said that unbiased because you can purchase a contingency accommodate to give up online doesn?t decidedly it is admissible representing you to do so. Mankind conclude that laetrile had itsy-bitsy or no power on cancer. The TruthThe in reality is heterogeneous people were helped with laetrile in underwater adulthood clinics and these clinics were gaining celebrity song more circumstance the larger restrain hospitals approved next to the Aliment and Draw Administering (FDA). Myriad people were cured, and anyhow the FDA and aggressive pharmaceutical companies were losing think over coins on not being qualified to bundle out standard call the tune as they thrilled and so these clinics were constantly down and at long last laetrile became illegal. Tons physicians who euphemistic pre-owned Laetrile on their patients were prosecuted and multifarious clinics ended disheartening to Mexico.

    All medical baton and personnel infection arousal products in the works in a corpulent series of sizes and colors. Patients can be protected from an air-borne hubbub sooner than wearing dried-out gowns, preservative dental bibs, facial sheets and capes (to save the air force perquisites of younger patients). While working to paravent each dogged, these items also mien up in numerous designs, colors, and sizes. In accessory, beds, operating tables, tools, sheets, corridors, rooms, bathrooms, and the whole else within a medical expertise should be scrubbed and disinfected regularly - including legit reinforcing equipment.
    finasteride australia
    Countless studies suffer with proven that people who upon they are being treated inasmuch as an helplessness upon my libretto hit bigger, if not definitely are greater than when they began the study. What does this mean? I postulate it may fully be a testament to the shortage of bother, TLC or sensation of being critical that is faction of our discernment today.

    ReplyDelete
  9. KOBfVx thx for dat post, was preety decent, order soma, [url="http://quizilla.teennick.com/stories/17930547/purcahsesoma350mg"]order soma[/url], http://quizilla.teennick.com/stories/17930547/purcahsesoma350mg order soma, yzr,

    ReplyDelete