初识DSL,Domain Specific Language

DSL(Domain Specific Language) -- 领域特定语言

什么是DSL

全世界喝咖啡的人,都知道

Venti half-caf, non-fat, no foam, no whip latte,

就好像喝奶茶的人会很老到地说

加奶,少糖,多冰,同样的道理

DSL就是用最简洁、方便的语言使得代码更漂亮、清楚。

维基百科的定义

"A programming language or specification language dedicated to a particular problem domain, a particular problem representation technique, and/or a particular solution technique."

一个简单的例子

不好的DSL:

c = ChessGame.new
p = Piece.new("white_pawn_1")
c.positions["white_pawn_1"] = "a3"
c.update_positions!

漂亮的DSL

ChessGame.new do |move|
  move.black_pawn(forward)
  move.white_pawn(forward)
  #…
  move.white_queen(pwn_king)
end
一个更加漂亮的例子(Machinist

Machinist使你脱离YAML fixtures,从而可以这样使用(called with people(:caligula)):

Caligula:
   Id: 8
   Name: caligula
   Birthday: 3-16-0037
   Likes: fire

to:

Person.blueprint do 
  name {Sham.name}
  birthday {Sham.date}
  likes {Sham.likes}
End

And then calling it with
Person.make(:name => ‘caligula, :likes => ‘fire’).

参考资料: