Friday, March 23, 2007

Declarative vs. Imperative

Recently i was talking to Michael Silver about declarative vs. imperative programming; he found an article on the topic saying that declarative programming is overrated and that "languages like Ruby" allow writing imperative code that "looks" and "feels" declarative. The article didn't give any examples, but Michael sent me an example using ActiveRecord to define a database schema.

   1: ActiveRecord::Schema.define(:version => 2) do
   2:  
   3:   create_table "comments", :force => true do |t|
   4:     t.column "body", :text
   5:     t.column "post_id", :integer
   6:   end
   7:  
   8:   create_table "posts", :force => true do |t|
   9:     t.column "title", :string
  10:     t.column "body", :text
  11:     t.column "created_at", :datetime
  12:     t.column "author_name", :string
  13:     t.column "comments_count", :integer, :default => 0
  14:   end
  15:  
  16: end

After a while of figuring out the semantics of the Ruby syntax, i realized that it isn't even a *language* feature that the article was touting - it's simply a "fluent API" which is apparently fairly common in Ruby libraries.



So I thought I would try to create a library in .Net that would "feel" very similar to the Ruby style.



So, here's the same code in VB.Net...




   1: With ActiveRecord.DefineSchema().AsVersion(2)
   2:  
   3:     With .WithTable("comments").UseForce()
   4:         .WithColumn("body").AsType(Of String)()
   5:         .WithColumn("post_id").AsType(Of Integer)()
   6:     End With
   7:  
   8:     With .WithTable("posts").UseForce()
   9:         .WithColumn("title").AsType(Of String)()
  10:         .WithColumn("body").AsType(Of String)()
  11:         .WithColumn("Created_at").AsType(Of Date)()
  12:         .WithColumn("author_name").AsType(Of String)()
  13:         .WithColumn("comments_count").AsType(Of Integer).UseDefault(0)
  14:     End With
  15:  
  16: End With


...and here's the same code in C#...




   1: ActiveRecord.DefineSchema(delegate(ARSchema s)
   2: {
   3:  
   4:     s.WithTable("comments", delegate(ARTable t)
   5:     {
   6:         t.WithColumn("body").AsType<string>();
   7:         t.WithColumn("post_id").AsType<int>();
   8:     }).UseForce();
   9:  
  10:     s.WithTable("posts").UseForce(delegate(ARTable t) 
  11:     {
  12:         t.WithColumn("title").AsType<string>();
  13:         t.WithColumn("body").AsType<string>();
  14:         t.WithColumn("Created_at").AsType<DateTime>();
  15:         t.WithColumn("author_name").AsType<string>();
  16:         t.WithColumn("comments_count").AsType<int>().UseDefault(0);
  17:     });
  18:  
  19: }).AsVersion(2);

The VB and the C# versions both take advantage of the language features.  VB supports the With statement, while C# supports anonymous delegates.  Both of these scenarios were enabled with overloaded methods within the same library.

76 comments:

dasmb said...

The benefits of declarative programming have little if anything to do with syntax. Their value stems from the fact that they separate the process of stating a problem form the process of solving it.

This essentially takes design by contract to the next level. Producers of the declarative input describe what they need, and how they need it, allowing producers of the declarative program to determine the best way to get it.

Approximating this in an imperative language is obviously possible -- at heart, everything's imperative -- but the crux of the issues is that an imperative program operating on declarative input must be prepared to check pre and post conditions and have a plan to deal with every eventuality. There is no assuming that DoStep1 is called before DoStep2, which is called before DoStep3. If you expose such operations, you must deal with all possible input violations at each step.

Declarative languages assist programmers in managing these conditions, or disallowing users to get into them.

Anonymous said...

Hi There I'd love to thank you for such a great made site!
I was sure this is a perfect way to make my first post!

Sincerely,
Edwyn Sammy
if you're ever bored check out my site!
[url=http://www.partyopedia.com/articles/finding-nemo-party-supplies.html]finding nemo Party Supplies[/url].

Anonymous said...

Genial brief and this post helped me alot in my college assignement. Gratefulness you for your information.

Anonymous said...

You have to express more your opinion to attract more readers, because just a video or plain text without any personal approach is not that valuable. But it is just form my point of view

Anonymous said...

I am reading this article second time today, you have to be more careful with content leakers. If I will fount it again I will send you a link

Anonymous said...

hi there everyone. I'm actually into shoes and I have been searching for that singular make. The prices seeking the velcros were about 200 bucks on every site. But definitively I found this site selling them for the benefit of half price. I exceptionally want these [url=http://www.shoesempire.com]prada sneakers[/url]. I will definetly buy those. what do you think?

Anonymous said...

Bonjour I'd like to thank you for such a great made forum!
I was sure this is a nice way to introduce myself!
We believe the only way accumulate assets it is usually a sensible scheme to begin a savings or investing strategy as soon in life as achievable. But don't despair if you have not thought of saving your capital until later on in life. With the help of hard work, that is investigating the best investment vehicles for your capital you can slowly but surely increase your wealth so that it extends to a big sum by the period you wish to retire. Inspect all of the available asset classes from stocks to real estate as investments for your money. A smartly diversified portfolio of investments in different asset classes will make your money age throughout the years.

-Chandra Clavette
[url=http://urwealthy.com]currency conversion [/url]

Anonymous said...

Hello. My wife and I bought our house about 6 months ago. It was a foreclosure and we were able to get a great deal on it. We also took advantage of the 8K tax credit so that definitely helped. We did an extensive remodeling job and now I want to refinance to cut the term to a 20 or 15 year loan. Does anyone know any good sites for mortgage information? Thanks!

Mike

Anonymous said...

hi everyone. I'm actually into shoes and I was digging as far as something that exact make. The prices seeking the sneakers are about 300 bucks on every site. But completely I bring about this locate selling them someone is concerned half price. I absolutely like these [url=http://www.shoesempire.com]gucci sneakers[/url]. I will probably order them. what can you tell me about these?

Anonymous said...

good day bros. I'm honestly into shoes and I had been searching for the sake of that exact make. The prices as regards the sneakers were all over 340 dollars everwhere. But completely I base this site selling them someone is concerned half price. I exceptionally like those [url=http://www.shoesempire.com]gucci sneakers[/url]. I will absolutely buy them. what do you think?

Anonymous said...

Do You interesting of [b]Female use of Viagra[/b]? You can find below...
[size=10]>>>[url=http://listita.info/go.php?sid=1][b]Female use of Viagra[/b][/url]<<<[/size]

[URL=http://imgwebsearch.com/30269/link/viagra%2C%20tramadol%2C%20zithromax%2C%20carisoprodol%2C%20buy%20cialis/1_valentine3.html][IMG]http://imgwebsearch.com/30269/img0/viagra%2C%20tramadol%2C%20zithromax%2C%20carisoprodol%2C%20buy%20cialis/1_valentine3.png[/IMG][/URL]
[URL=http://imgwebsearch.com/30269/link/buy%20viagra/3_headsex1.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/3_headsex1.png[/IMG][/URL]
[b]Bonus Policy[/b]
Order 3 or more products and get free Regular Airmail shipping!
Free Regular Airmail shipping for orders starting with $200.00!

Free insurance (guaranteed reshipment if delivery failed) for orders starting with $300.00!
[b]Description[/b]

Generic Viagra (sildenafil citrate; brand names include: Aphrodil / Edegra / Erasmo / Penegra / Revatio / Supra / Zwagra) is an effective treatment for erectile dysfunction regardless of the cause or duration of the problem or the age of the patient.
Sildenafil Citrate is the active ingredient used to treat erectile dysfunction (impotence) in men. It can help men who have erectile dysfunction get and sustain an erection when they are sexually excited.
Generic Viagra is manufactured in accordance with World Health Organization standards and guidelines (WHO-GMP). Also you can find on our sites.
Generic [url=http://viagra.wilantion.ru]Viagra 100mg pills[/url] is made with thorough reverse engineering for the sildenafil citrate molecule - a totally different process of making sildenafil and its reaction. That is why it takes effect in 15 minutes compared to other drugs which take 30-40 minutes to take effect.
[b]generic generic viagra tadalafil
Cheap Viagra 25mg
viagra reports
buy viagra without prescription
Viagra Common Side Effects
Viagra Online Usa
liquid viagra alcohol shot
[/b]
Even in the most sexually liberated and self-satisfied of nations, many people still yearn to burn more, to feel ready for bedding no matter what the clock says and to desire their partner of 23 years as much as they did when their love was brand new.
The market is saturated with books on how to revive a flagging libido or spice up monotonous sex, and sex therapists say “lack of desire” is one of the most common complaints they hear from patients, particularly women.

Anonymous said...

maybe you have a shoe fetish because you're not taking the viagra

viagra online said...

hello friend thanks for sharing this useful and interesting information about Declarative vs. Imperative thanks!!

Jim said...

Ugghh SPAAAAM. You might want to activate some sort of validation before letting people post anymore.

Anonymous said...

best registry cleaner , A software application system that tests the Pc registry and appears for obsolete and sick entries.
Apps often produce Registry entries for temporary data and pointers to other files, but never erase them. In addition, http://www.registry1000.com/2010/05/09/best-registry-cleaner/ , [url=best registry cleaner]http://www.registry1000.com/2010/05/09/best-registry-cleaner/[/url] if files are by hand deleted by the user.
Registry entries may point to files that do not exist. A Registry cleaner freeware can ahtvniwxnjnjnjnnjaw participate a package of method programs or a stand-alone, best registry cleaner application

eco vacation costa rica said...

Hello congratulations you did an excellent work with this blog about Declarative vs. Imperative I would like to know more about this topic and please when you have any update contac me please to read it. thanks for sharing!!

Anonymous said...

Buy Neopoints to archive your highest target on Neopets.
Neopets is a very complicated game to earn Neopoints yourself in, it may experience months of hardwork honourable to institute 1,000,000 Neopoints!
[url=http://buyneopoints.org]Buy Neopoints[/url] and get the elemental Neopets cheats!

Neopets has tons of games you can caper, and when you buy neopoints, it resolution net your exposure much bettert!
Inspect us out today and you won't repent it, Neopoints packages start from well-grounded $2.25!
Buy Neopoints

Anonymous said...

Thank you, that was extremely valuable and interesting...I will be back again to read more on this topic.

Anonymous said...

Our ensemble creates a matter card on the underpinning of unique and pretty projects.
These projects are carried revealed near the cards the best team of explicit artists and designers in
the shop who are experts in every gist of the word. They are also extraordinarily lithe, so you can
achieve jolly fascinating dealing press card designs, depending on the individual needs of each client.
We do not own a whiz printing machines undertake the highest quality of each own card.
Extensive selection of dossier allows you to meet the expectations of parallel with the most tough customers
from every conceivable industry. We guarantee the language and amenities of large quantities of business
cards in the shortest conceivable time. In our case, the highest quality is the satisfaction of the proposed
penalty and honest accommodation from people receiving and carrying revealed an pecking order notwithstanding task cards.
With access to the services offered through our website, you can shortly and without undue
formalities mission an sect for goods, judgement the project and approved it and ordered some task
cards. Settle upon our theatre troupe as a sympathetic subject postcard is oft a oath after success.
Greet
Merio [url=http://www.kalendarze.dogory.pl]Kalendarze[/url]

Anonymous said...

Hi there,

I have a message for the webmaster/admin here at develocity.blogspot.com.

May I use some of the information from your post above if I provide a backlink back to your website?

Thanks,
Harry

Anonymous said...

Hi,

Thanks for sharing the link - but unfortunately it seems to be not working? Does anybody here at develocity.blogspot.com have a mirror or another source?


Thanks,
Thomas

Anonymous said...

Great post! I want to see a follow up to this topic :D

Jarred

Anonymous said...

Il semble que vous soyez un expert dans ce domaine, vos remarques sont tres interessantes, merci.

- Daniel

hardcore bdsm video said...

I appreciate this post.

Anonymous said...

There is a great application Digeus Registry Cleaner I recommend to use this software when there are problems with windows. I also use Windows Tune Up Suite form Windsty. It restores system to a healthy state.

No Deposit Bonus said...

I really enjoy to be here. Your have great insight about
"Declarative vs. Imperative" of your post. Your Develocity blog is really excellent.
--------------------------
My website: Play Poker Tours Bonus deals and Instant bonus for Poker.

Poker said...

I appear forward to coming back to read your "Declarative vs. Imperative" post also.
--------------------------
Visit my web: Poker 50 gratuit & Poker Bonus Deposito & Poker Online Kostenlos & Bonus senza deposito

Online Poker said...

Great job with "Declarative vs. Imperative" article! Love your writing style on Develocity! Funny, but serious and to the point, at the same time! Nice job dear admin.
--------------------------
My site: Play Poker Without Risk 100% free poker !

price per head service said...

I am thoroughly convinced in this said post. I am currently searching for ways in which I could enhance my knowledge in this said topic you have posted here

call center voip solutions said...

Thank you, I have recently been searching for information about this topic for ages and yours is the best I have discovered so far.

pay per head said...

Thanks for the list, just submitted to them. Keep up the good work.

Anonymous said...

dittoTweet spanmetadata display: block;width: 100%;clear: both;margin-top: 8px;padding-top: 12px;height: 65px; p It's a place rich in historyEducation As the youngest child he can be educated by his older siblings We did not screen out any sectors
retweet > span background-position: -80px 3px; pR1 percent of their regular season gamesThe first thing you should do with your child is select a song that suits them Our expert's team has designed and prepared the training kit for IBM certificationA professional employer organization can certainly be a boon to many companies[url=http://www.andrewluckjerseys.net]Andrew Luck Womens Jersey[/url]
but only if yours really needs the services offered[url=http://www.robertgriffiniiijersey.net]Robert Griffin III Jersey[/url]
and you have thoroughly checked the contract "Okay let’s go

Anonymous said...

[URL=http://pharmacypills.atspace.co.uk/buy-amitriptyline-canada/Sydney-order-endep-75-mg.html]Sydney order endep 75 mg[/URL]

Anonymous said...

Poifiefurry PoifiefurryJB
J.J. Watt Jersey for sale
Authentic Vernon Davis Jersey
Black Patrick Willis Jersey

Anonymous said...

nFzs michael kors
xYjx lisseur ghd pas cher
rVae north face store
4nSif ugg boots sale
6pMep michael kors handbags

Anonymous said...

sKnu coach outlet online
iXgi ugg boots uk
oFao michael kors bags
7mVaq ugg sale
4tTqt chi flat iron
2iWgr michael kors purses
2bUxj nfl jerseys
3aAjl coach outlet
9gBwo north face jackets
4dMsh ugg australia
5gVyq ghd purple
4vRgb michael kors bags
4rAkd nike nfl jerseys
3wGbq planchas ghd
8hNbr ugg sale

Anonymous said...

zRmq coach factory
hLhb ugg boots sale uk
dSsw michael kors bags
0mYvx ugg uk
6kYpw chi hair products
5cGdp michael kors handbags
2rDyq nfl football jerseys
6bTfe coach outlet online
5pSxk north face sale
5eUab botas ugg baratas
7aEua ghd hair straighteners
7cLcr michael kors purse
0qMve nike nfl jerseys
0rKxo plancha ghd
7rVjp discount ugg boots

Anonymous said...

buy viagra canada purchase viagra placebo - can you buy generic viagra

Anonymous said...

[url=http://onlinecasinose25.com ]internet casino [/url]difference. He would have telephoned just the same and trusted to http://casinoonlinebonussverige.com online casino kerching online casino A streamlet that to in rear of him is sitting,

Anonymous said...

GlfRjw http://sinsakuchanel.com/ EdqJmw [url=http://sinsakuchanel.com/]シャネル バッグ トート[/url] NudQxn http://ninnkicoach.com/ BcvRrz [url=http://ninnkicoach.com/]コーチ公式ファクトリー[/url] YtsPjh http://diorautoretto.com/ LuiAia [url=http://diorautoretto.com/]ディオール 財布 エナメル[/url] HucKeb http://nihongucci.com/ NyoAws [url=http://nihongucci.com/]グッチ裕三[/url] DluVuf http://longchampnihon.com/ PpqYyl [url=http://longchampnihon.com/]ロンシャン プリアージュ サイズ[/url] DmtPcz http://sinsakuvuitton.com/ UudMsi [url=http://sinsakuvuitton.com/]ルイヴィトン コピー ベルト[/url] PgzAdx http://gekiyasuprada.com/ ZxpSas [url=http://gekiyasuprada.com/]プラダ 店舗[/url] TusRrc http://uggsinsaku.com/ EjkZrh [url=http://uggsinsaku.com/]UGG 手袋[/url]

Anonymous said...

viagra online without prescription viagra online quality - buy viagra or cialis online

Anonymous said...

top [url=http://www.001casino.com/]casino online[/url] brake the latest [url=http://www.realcazinoz.com/]free casino[/url] free no consign reward at the chief [url=http://www.baywatchcasino.com/]casino compensation
[/url].

Anonymous said...

Great blοg here! Alѕо your websitе loads uρ fаst!
Whаt web host are yοu using? Cаn I get
your affіlіate lіnk to your hοѕt?
I wish my wеbsite lοaded uр
as quickly as yours lоl
My site - loans for bad credit

Anonymous said...

Нave you eνer thought аbout aԁding a little bit mοre than ϳust your агtіcleѕ?
I mеаn, what yοu sаy is fundаmental and evеrything.
Neverthеless think about if you addеԁ somе grеat photos or
videos to giνе youг pοsts mоre,
"pop"! Yоur сοntent is еxсellent but ωіth ρiсs аnԁ ѵіdеos, thiѕ website could undеniably be onе of the
beѕt in its nichе. Goоd blog!
My page ... loans for bad credit

Anonymous said...

buy soma soma san diego ca - buy somatropin in usa

Anonymous said...

buy soma online order soma to arizona - buy soma online with no prescription

Anonymous said...

buy soma online order soma online overnight - soma drug fiction

Anonymous said...

buy soma online generic soma names - soma drug user reviews

Anonymous said...

buy tramadol addiction to tramadol - tramadol veterinary dose

Anonymous said...

buy tramadol online tramadol generic for ultram - tramadol 50 mg price

Anonymous said...

tramadol 50mg cheap tramadol cod - tramadol 325 dosage

Anonymous said...

order tramadol online cod tramadol hcl usa - order tramadol free shipping

Anonymous said...

generic xanax xanax for anxiety dosage - alprazolam 0.5 mg tablet myl

Anonymous said...

buy tramadol tramadol 50mg dosage humans - tramadol 50 mg compared to percocet

Anonymous said...

generic xanax xanax online from india - xanax side effects gynecomastia

Anonymous said...

All of the win for all to see greater than payday advance services we reviewed are suited, law-abiding institutions that provide a substantiate service to those who ask for a not many strikingly dollars to misappropriate to one's heels it be means of a severe patch. In this position, you'll awaken articles with payday loans word and capital tips, as fount as sweeping reviews and a side during side affiliation to plagiarize you prime mover an educated decision on which reinforcement is repair toward your short-term prepay needs. We launch that the most talented options allowing for on the subject of payday loans online.

Fit those that requisite difficulty cash between paydays, intuition the differences in payday advance lenders can fix on how comfortably and at you fare the boodle you need. It used to be that you had to be cast to a physical fingers on and discontinuation fitting for an affirmation on your payday allowance, after submitting copies of surcease stubs and bank statements. Nowadays, there is a difference in payday advance lenders because there are some that proffer express and within easy reach online options. When you away benefit of online options, it is doable to support trice approvals and should prefer to the shekels you constraint in a topic of a scattering hours, or less.


Best Online Payday Loans and Cash Advance:
pay day loan
[url=http://paydayloanmoneyfast.com/loan/payday-loans-south-africa-6e]Payday loans south africa[/url]
http://paydayloanmoneyfast.com/loan/instant-payday-loans-no-credit-check-e3 - Instant payday loans no credit check

Anonymous said...

buy cialis online usa cialis price euro - cialis 2.5 online

Anonymous said...

cheap cialis online cialis from usa online pharmacy - cialis online in usa

Anonymous said...

buy cialis online order cialis with prescription - cialis online free trial

Anonymous said...

xanax online xanax side effects forum - xanax 1mg green

Anonymous said...

buy cialis online cialis 2.5 mg price - generic cialis at cvs

Anonymous said...

buy tramadol usa tramadol for dogs dosage usa - buy tramadol in usa

Anonymous said...

buy tramadol tramadol online shipped to florida - tramadol for dogs human use

Anonymous said...

bookmarked!!, ӏ like your websіtе!


My websіte payday loans

Anonymous said...

buy klonopin online how to get klonopin out of your system fast - klonopin withdrawal weight gain

Anonymous said...

07 buy generic prednisone - cheap prednisone http://www.prednisoneonlinerx.net/index.html, [url=http://www.prednisoneonlinerx.net/index.html]cheap prednisone online [/url]

Anonymous said...

buy tramadol online tramadol hcl acetaminophen 650 - buy tramadol online forum

Anonymous said...

Hi therе every one, hеre еveгy perѕοn іs sharing such know-hοw, thus it's good to read this weblog, and I used to visit this weblog everyday.

Here is my website same day loans

Anonymous said...

Hi there to eѵery bοdу, іt's my first visit of this webpage; this website includes awesome and in fact excellent stuff for visitors.

Also visit my webpage :: payday loans uk
Also see my webpage > payday loans uk

Anonymous said...

http://southcarolinaaccidentattorney.com/#90864 carisoprodol side effects constipation - do drug tests test carisoprodol

Anonymous said...

Nice pοst. I wаѕ сheckіng constantlу
this blog and I'm impressed! Very helpful information specifically the last part :) I care for such information much. I was seeking this particular information for a long time. Thank you and best of luck.

Take a look at my web page payday loans

Anonymous said...

I have rеаd ѕοmе just right stuff hеre.
Ceгtainly vаlue bookmarking fог rеvisitіng.
I surpгise how a lot еffοrt уou placе to create
this κind of excellent informative web ѕite.


my ωеb sіtе - New Bingo Sites

Anonymous said...

In the world today, there are just small amount companies that having
said that atelier dyson machines, pair of analysts by European: Bodum as well
as , Cona. For your option is perpetual, concentrate on first
consider preferably this particular coffee brewer nor
espresso maker to try. It may be an easy Southeast satellite dish yet in fact flavorsome what you know already that it
is fantastic kitchen expertise.

my website: Coffeemakersnow.Com

Anonymous said...

Nearly all dieters should not to become for being a significant issue, except to enjoy people cheerful, a new Executive as
well as , Elegant designs have a real drip-proof spout.
If you are hoping to put incredibly affordable juice extractor which is usually easy
then you should keep an eye on at your Hamilton Water television commercial lemon or lime juicer.
Any machine between the many assets the idea lovers enjoy.
People young and old building place are really extremely smartly-designed and simply know just what they need
as it pertains to cooking food and consequently kitchen's items.

Feel free to surf to my web-site - power juicer deluxe vs power juicer pro

Anonymous said...

The most popular is 2 segments, your rubber-ish (Take part in at any time really it could be manufactured with on the other hand looks like pliable plastic)
stopper having clinic evident top whom unscrews should you add in a specific
thing to collaboration among. You could view throughout the globe and see it difficult to state some thing awful for this exceptional kitchen appliance.

Will not lose your finances although creating these kinds choice just as it is more likely to help you most
effectively pick and choose quite a few massive plethora supported.
Some grip are required to be fitted stringently towards
the framework of the actual printer. Desire would love to fix other vegetables typical and extremely tasking in your, give particular veges inside
your plenty.

Also visit my web site :: Best blender reviews

Anonymous said...

For particular this is choose generally be spared getting all those fruits and veggies
cut to make products and solutions before making juice.
For people who can't spend the time, to go with nevertheless another toy. Merely because they will add a good wrong flavor, in certain cases mass fast beverage growers purification the site of one's cider,
so limonoids can be found automobile investigation
which offers substantiation oftentimes alternative melanoma mixed martial artists while pesticides.
Oster far too gives take great pride in for any other products, each of our Oster 18
Time Food processor consisting of Food Processor.


Feel free to surf to my web site; ninja blender recipes