Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Programming Language Paradigms

Stefan Kanev
November 03, 2012

Programming Language Paradigms

Stefan Kanev

November 03, 2012
Tweet

More Decks by Stefan Kanev

Other Decks in Programming

Transcript

  1. void transfer(Account fromAcc, Account toAcc, int amount, User user, Logger

    logger) throws Exception { Transaction = new Transaction(); try { transaction.begin(); logger.info("Transferring money..."); if (!checkUserPermission(user)) { logger.info("User has no permission."); throw new UnauthorizedUserException(); } if (fromAcc.getBalance() < amount) { logger.info("Insufficient funds, sorry."); throw new InsufficientFundsException(); } fromAcc.withdraw(amount); toAcc.deposit(amount); transaction.commit(); logger.info("Successful transaction."); } catch(Exception e) { transaction.rollback(); throw e; } }
  2. void transfer(Account fromAcc, Account toAcc, int amount) throws Exception {

    if (fromAcc.getBalance() < amount) { logger.info("Insufficient funds, sorry."); throw new InsufficientFundsException(); } fromAcc.withdraw(amount); toAcc.deposit(amount); }
  3. @transactions @logging @authenticate def transfer(sender, receiver, amount): if sender.balance() <

    amount: raise "Insufficient funds" sender.withdraw(amount) receiver.deposit(amount) Подобно, но не AOP
  4. Алан Кей твърди, че обмяната на съобщения между обектите е

    по- важна от самите обекти. http://lists.squeakfoundation.org/pipermail/squeak-dev/1998-October/017019.html
  5. Добрия обектно-ориентиран дизайн има много на брой, малки на размер,

    прости класове. Същината му е в комуникацията между тях.
  6. public static float area(Circle circle) { return PI * circle.radius

    * circle.radius; } Лош обектно-ориентиран код
  7. class Circle { public float area() { return PI *

    radius * radius; } } Добър обектно-ориентиран код
  8. Клас Child може да наследява клас Parent, само ако на

    всички места, на които програмата приема Parent може да подадем Child. class Child extends Parent
  9. emails = [] for user in users if user.active? emails

    << user.email end end notify(emails)
  10. Често когато покажа това на някого, той ще каже, че

    първия вариант е по-ясен. Но за мен втория вариант е по-ясен. Защо?
  11. В момента за мен map и filter са по- четими.

    Първия път като ги видях не бе така.
  12. class Circle def initialize(center, radius) @center, @radius = center, radius

    end def area Math::PI * @radius * @radius end end class Square def initialize(top_left, side) @top_left, @side = top_left, side end def area @side * @side end end ООП
  13. ФП Circle = Struct.new(:center, :radius) Square = Struct.new(:top_left, :side) module

    Geometry extend self def area(shape) case shape when Circle then Math::PI * shape.radius * shape.radius when Square then shape.side * shape.side end end end
  14. class Circle def initialize(center, radius) ... def area ... def

    circumference 2 * Math::PI * @radius end end class Square def initialize(top_left, side) ... def area ... def circumference 4 * @side end end Операция в ООП ☢
  15. module Geometry def area(shape) case shape when Circle then Math::PI

    * shape.radius * shape.radius when Square then shape.side * shape.side end end def circumference(shape) case shape when Circle then 2 * Math::PI * shape.radius when Square then 4 * shape.side end end end Операция във ФП ✔
  16. class Rectangle def initialize(top_left, width, height) @top_left, @width, @height =

    top_left, width, height end def area @width * @height def circumference 2 * @width + 2 * @height end end Тип в ООП ✔
  17. module Geometry def area(shape) case shape when Circle then Math::PI

    * shape.radius * shape.radius when Square then shape.side * shape.side when Rectangle then shape.width * shape.height end end def circumference(shape) case shape when Circle then 2 * Math::PI * shape.radius when Square then 4 * shape.side when Rectangle then 2 * shape.width + 2 * shape.height end end end Тип във ФП ☢
  18. Рамките могат да бъдат и нож с две остриета. Какво

    става ако пишем на Java и ни трябва често да добавяме нови операции?
  19. emails = [] for user in users if user.active? emails

    << user.email end end notify(emails)
  20. 1. The Brit lives in a red house. 2. The

    Swede keeps dogs as pets. 3. The Dane drinks tea. 4. The green house is next to, and on the left of the white house. 5. The owner of the green house drinks coffee. 6. The person who smokes Pall Mall rears birds. 7. The owner of the yellow house smokes Dunhill. 8. The man living in the centre house drinks milk. 9. The Norwegian lives in the first house. 10. The man who smokes Blends lives next to the one who keeps cats. 11. The man who keeps horses lives next to the man who smokes Dunhill. 12. The man who smokes Blue Master drinks beer. 13. The German smokes Prince. 14. The Norwegian lives next to the blue house. 15. The man who smokes Blends has a neighbor who drinks water. Who has the fish? Einstein’s Riddle
  21. solution(People) :- People = [_, _, _, _, _], same(brit,

    red, People), same(swede, dogs, People), same(dane, tea, People), left_of(green, white, People), same(green, coffee, People), same(birds, pall_mall, People), same(yellow, dunhill, People), center_house(milk, People), first_house(norwegian, People), neighbors(blends, cats, People), neighbors(horses, dunhill, People), same(beer, blue_master, People), same(german, prince, People), neighbors(norwegian, blue, People), neighbors(blends, water, People), maplist(person, People), flatten(People, Items), is_set(Items).
  22. has(Thing, Person) :- nationality(Thing), Person = [Thing, _, _, _,

    _]. has(Thing, Person) :- color(Thing), Person = [_, Thing, _, _, _]. has(Thing, Person) :- pet(Thing), Person = [_, _, Thing, _, _]. has(Thing, Person) :- beverage(Thing), Person = [_, _, _, Thing, _]. has(Thing, Person) :- cigars(Thing), Person = [_, _, _, _, Thing]. same(A, B, People) :- has(A, Person), has(B, Person), member(Person, People). first_house(A, People) :- has(A, Person), People = [Person, _, _, _, _]. center_house(A, People) :- has(A, Person), People = [_, _, Person, _, _]. left_of(A, B, People) :- has(A, PersonA), has(B, PersonB), nextto(PersonA, PersonB, People). neighbors(A, B, People) :- left_of(A, B, People); left_of(B, A, People).
  23. ?-

  24. class Comment < ActiveRecord::Base validates_presence_of :body belongs_to :user belongs_to :revision

    attr_protected :user_id, :solution_id delegate :solution, to: :revision delegate :task, :task_name, to: :solution def editable_by?(user) self.user == user or user.try(:admin?) end def user_name user.name end end
  25. DSL

  26. Scenario: Purchasing goods with coupons Given a product "MacBook Air"

    that costs 2000$ And a discount coupon "CUCUMBER" for 10% When I add "MacBook Air" to my bag And I apply the coupon "CUCUMBER" Then I should have to pay 1800$ Cucumber
  27. Езика ни дава рамки, които структурират програмата ни. Това я

    прави по-разбираема за всички останали.