The paradigm separates the domain model (data) from use cases (context) and roles that objects play (interaction). DCI is complementary to model–view–controller (MVC). MVC as a pattern language is still used to separate the data and its processing from presentation.
Last active
December 10, 2015 12:38
-
-
Save dsci/4435360 to your computer and use it in GitHub Desktop.
A Ruby example implementation of DCI (Data Context Interaction). To play around.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Account | |
def initialize | |
@balance = 500 | |
end | |
def decrease_balance(amount) | |
@balance = balance - amount | |
end | |
def increase_balance(amount) | |
@balance = balance + amount | |
end | |
def balance | |
@balance | |
end | |
def update_log(message, amount) | |
p "#{message}: #{amount} Euro. New balance is #{balance}" | |
end | |
def self.find(id) | |
return self.new | |
end | |
end | |
module ContextAccessor | |
def context | |
Thread.current[:context] | |
end | |
end | |
module Context | |
include ContextAccessor | |
def context=(ctx) | |
Thread.current[:context] = ctx | |
end | |
def context | |
Thread.current[:context] | |
end | |
def in_context | |
old_context = self.context | |
self.context = self | |
res = yield | |
self.context = old_context | |
return res | |
end | |
end | |
module SourceAccount | |
include ContextAccessor | |
def transfer_out(amount) | |
raise "Insufficient funds" if balance < amount | |
decrease_balance(amount) | |
context.destination_account.transfer_in(amount) | |
update_log("Transfered out", amount) | |
end | |
end | |
module DestinaAccount | |
include ContextAccessor | |
def transfer_in(amount) | |
increase_balance(amount) | |
update_log("Transfered in", amount) | |
end | |
end | |
class TransferringMoney | |
include Context | |
attr_reader :source_account, :destination_account | |
def self.transfer(source_account_id, destination_account_id,amount) | |
source = Account.find(source_account_id) | |
destination = Account.find(destination_account_id) | |
TransferringMoney.new(source,destination).transfer(amount) | |
end | |
def initialize(source_account, destination_account) | |
@source_account = source_account.extend(SourceAccount) | |
@destination_account = destination_account.extend(DestinaAccount) | |
end | |
def transfer(amount) | |
in_context do | |
source_account.transfer_out(amount) | |
end | |
end | |
end | |
amount_to_transfer = 200 | |
TransferringMoney.transfer(12,32,amount_to_transfer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment