Возвращаясь к спору о примере использования паттерн-матчинга для поддержки обработки сообщений между актерами в Scala, начатому с
вот этого сообщенияАвтор: eao197
Дата: 03.05.07
.
В
Scala-программе есть фрагменты, аналогичные вот этому:
/**
* Send a message to a User (from the web, from IM, from SMS). The Actor
* will take care of persisting the information in the database.
*
* @param text - the text of the message
* @param src - the source of the message
*/
case class SendMessage(text: String, src: String) extends UserMsg
...
loop {
react {
// The user sends a message containing text and a source. This can
// be from the web, from IM, from SMS, etc.
case SendMessage(text, src) =>
// create a new Message object to be added to the user's local message and sent
// to followers
val msg = Message(text, System.currentTimeMillis, userName, src)
// add to our local messages (keeping only the maxMessages most recent messages)
latestMsgs = (msg :: latestMsgs).take(maxMessages)
// update all our followers (and ourselves) with the message
(this :: followers).foreach(_ ! msg)
// and put it in the database
MsgStore.create.message(text).source(src).who(userId).save
// if the message was autogenerated, then autogenerate another message in 5 or so minutes
if (src == "autogen") autoGen
Какой глубинный смысл в том, чтобы здесь раскрывать содержимое объекта типа SendMessage на локальные переменные text и src. Лучше ли это, например, вот такого непосредственного обращения с объектом SendMessage:
def onSendMessage( m: SendMessage ) {
val msg = Message(m.text, System.currentTimeMillis, userName, m.src)
// add to our local messages (keeping only the maxMessages most recent messages)
latestMsgs = (msg :: latestMsgs).take(maxMessages)
// update all our followers (and ourselves) with the message
(this :: followers).foreach(_ ! msg)
// and put it in the database
MsgStore.create.message(m.text).source(m.src).who(userId).save
// if the message was autogenerated, then autogenerate another message in 5 or so minutes
if (m.src == "autogen") autoGen
}
и если лучше, то чем?
Вопрос вызван вот чем: протоколы обмена сообщениями неизбежно эволюционируют. Это подразумевает не только изменение состава сообщений, но и изменения структуры отдельных сообщений. Самой простой модификацией при этом оказывается добавление новых полей в сообщение. Скажем, SendMessage может быть расширено полями priority и validity_period. Если прикладной код оформлен в виде методов onSendMessage, то подобные расширения протокола на нем не сказываются. В отличии от кода на основе pattern-matching-а (по моему субъективному мнению).
Интересны преимущества именно по отношению к гибридным языкам, вроде Scala, где есть "обычное" ООП (поскольку, если я правильно понимаю, в более фунциональных языках, вроде Erlang и Haskell, ситуация будет/может выглядеть иначе).