Misunderstanding the Law of Demeter

深入解析《The Law of Demeter》原则,通过实例对比属性委托与行为委托的区别,阐述其对面向对象设计的影响与价值。探讨如何通过行为委托改善代码质量和可维护性。

http://www.dan-manges.com/blog/37

 

The Law of Demeter is not easy to understand when reading it for the first time. Quoting the definition from Wikipedia:

More formally, the Law of Demeter for
functions requires that a method M of
an object O may only invoke the methods
of the following kinds of objects:

   1. O itself
   2. M's parameters
   3. any objects created/instantiated within M
   4. O's direct component objects

In particular, an object should avoid invoking
methods of a member object returned by another method.


The Wikipedia article summarizes it as "Only talk to your immediate friends." Developers seems to recognize violations by looking for more than one "dot", such as:

foo.bar.baz


Here, "foo" is talking to "baz" through "bar". The solution (in Ruby) is to use Forwardable and set up a delegation. Here is an example:

class Foo
  extend Forwardable
  def_delegator :bar, :baz

  def bar
    # an associated object
    # could be a belongs_to in Rails
  end
end


With this delegation in place, we can reduce the two "dots" into one by doing: foo.baz. Forwardable and def_delegator take care of going from "foo" through "bar" to "baz." While this may seem to solve our problem, the solution has a significant misconception.

Delegation is an effective technique to avoid Law of Demeter violations, but only for behavior, not for attributes.

To explain, I need a better example than foo/bar/baz. One of the classic examples I have seen to explain this is a Paper Boy, a Customer, and a Wallet. A paper boy needs to collect money from his customers. A customer stores his/her money in a wallet. Here is how this might be modeled violating the Law of Demeter:

class Wallet
  attr_accessor :cash
end
class Customer
  has_one :wallet
end
class Paperboy
  def collect_money(customer, due_amount)
    if customer.wallet.cash < due_ammount
      raise InsufficientFundsError
    else
      customer.wallet.cash -= due_amount
      @collected_amount += due_amount
    end
  end
end


Hopefully apparent from this example is that a paperboy should not be taking cash out of a customer's wallet. This is a clear Law of Demeter violation. Going back to the simple way to recognize this mistake, we can see two dots in "customer.wallet.cash". Here is how this might change with attribute delegation.

class Wallet
  attr_accessor :cash
end
class Customer
  has_one :wallet

  # attribute delegation
  def cash
    @wallet.cash
  end
end

class Paperboy
  def collect_money(customer, due_amount)
    if customer.cash < due_ammount
      raise InsufficientFundsError
    else
      customer.cash -= due_amount
      @collected_amount += due_amount
    end
  end
end


This example is only slightly different. A customer now has cash, which simply delegates to cash in the wallet. Now in the Paperboy collect_money method, we don't have two dots, we just have one in "customer.cash". Has this delegation solved our problem? Not at all. If we look at the behavior, a paperboy is still reaching directly into a customer's wallet to get cash out. That's not good. However, if instead of delegating attributes, we delegate behavior, we will end up with a much better OO design.

class Wallet
  attr_accessor :cash
  def withdraw(amount)
     raise InsufficientFundsError if amount > cash
     cash -= amount
     amount
  end
end
class Customer
  has_one :wallet
  # behavior delegation
  def pay(amount)
    @wallet.withdraw(amount)
  end
end
class Paperboy
  def collect_money(customer, due_amount)
    @collected_amount += customer.pay(due_amount)
  end
end


Again, the change is simple, but our OO-ness and class responsibilities are much better. Notice the way delegation is done now. The pay method on customer simply delegates to the withdraw method on the wallet. Even with the argument on the pay method, this could also be implemented by using Forwardable.

Is the Customer#pay method, with doing nothing but a simple delegation, valuable? Yes. We want our paper boy to know as little as possible about the customer. It's okay for the paper boy to know the customer has a method available to pay him. The paper boy knowing the customer has a wallet (and even further, that the wallet has cash), is not okay. This is what the Law of Demeter is about.

Thinking again about attribute/getter/setter delegation, it gives classes too much knowledge about other classes. This includes classes that are far away from each other in the domain model. Going back to the first example, we don't want a paper boy to know a customer has a wallet. Onto the second example, we really don't want a customer to know a wallet has cash if we don't need to. The behavior delegation is a much better way to solve this problem.

Because I'm not confident this example is perfectly clear (after all, why wouldn't a customer know he has cash, why should that be hidden (read: encapsulated) in the wallet?), here is another example, and what I think has caused some overuse of attribute delegations:

An Order belongs_to a Customer. Let's say we're developing a Rails view to display order information, and this should include details on the customer. We might write the view like this:

<%= @order.customer.name %>


Two dots! Demeter violation? No. If you thought it was, you might have a delegation in your model, something like:

class Order
  extend Forwardable
  def_delegator :customer, :name, :customer_name
end


Our view now becomes:

<%= @order.customer_name %>


We've traded a dot for an underscore. And thinking about this further, why should an order have a customer_name? We're working with objects, an order should have a customer who has a name. Adding these attribute delegations also decreases maintainability.

The crux of this is that webpage views aren't domain objects and can't adhere to the Law of Demeter. Clearly from the examples of behavior delegation the Law of Demeter leads to cleaner code. However, when rendering a view, it's natural and expected that the view needs to branch out into the domain model. Also, anytime something in a view dictates code in models, take caution. Models should define business logic and be able to stand alone from views. If this "train-wreck" method calling in your views is bothersome, there is a better solution that I will blog about later.

Focus on delegating behavior more than attributes. This ties well into the "Tell, don't ask." principle. With the paper boy example, our code is much better when a customer tells his/her wallet to withdraw an amount, rather than asking the wallet for how much cash it has and then doing the logic in the customer model.

内容概要:本文围绕“考虑隐私保护的分布式联邦学习电力负荷预测研究”展开,提出了一种融合联邦学习框架与隐私保护机制的电力负荷预测方法,旨在解决传统集中式数据处理中潜在的用户隐私泄露问题。通过构建分布式模型训练体系,各参与方在本地完成模型训练,仅向中心服务器上传模型参数或梯度信息,实现“数据不动模型动”的协同建模模式,确保数据“可用不可见”。研究采用Python语言实现了完整的联邦学习流程,涵盖客户端本地训练、全局模型聚合、隐私保护策略(如差分隐私或同态加密)集成、通信机制设计及预测性能评估等核心模块,显著提升了电力负荷预测在隐私安全与模型精度之间的平衡能力。; 适合人群:具备Python编程基础和机器学习基础知识,从事电力系统、智能电网、能源大数据分析、数据隐私保护等相关领域研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①应用于居民或工业级电力负荷预测任务,在保障用户用电数据隐私的前提下实现高精度预测;②为构建符合数据合规要求的智慧能源管理系统提供技术支撑;③推动联邦学习在能源互联网、跨企业数据协作等场景中的落地应用,促进多方协同建模与数据价值释放。; 阅读建议:建议读者结合文中提供的Python代码进行实践操作,重点关注联邦学习的通信轮次设置、本地训练迭代策略、模型聚合算法设计以及隐私噪声添加机制的实现细节,并可根据实际需求替换底层预测模型(如LSTM、XGBoost、Transformer等)以进一步优化预测性能。
内容概要:本文介绍了一种基于噪声抑制半监督学习的锂离子电池SOH(State of Health,健康状态)估计方法的Python代码实现,旨在通过结合半监督学习框架与噪声抑制技术,提升电池健康状态预测的准确性与鲁棒性。该方法充分利用少量有标签样本和大量无标签数据进行模型训练,有效缓解了实际应用中电池老化数据标注成本高、获取困难的问题。文中详细阐述了模型的整体架构设计、关键特征提取策略、噪声处理机制以及半监督学习中的损失函数构建,并提供了完整的可复现代码,便于研究人员理解和二次开发。; 适合人群:具备一定机器学习理论基础和Python编程能力,从事电池管理系统(BMS)、新能源汽车、储能系统等领域的科研人员或工程师,尤其适用于关注电池寿命预测、状态估计及数据驱动建模的研究生与青年学者。; 使用场景及目标:①实现锂离子电池健康状态的高精度估计,服务于电池管理系统的优化与安全预警;②为工业场景下标注数据稀缺的退化建模问题提供一种高效的半监督解决方案;③推动复杂噪声环境下电池性能退化预测的研究进展,增强模型在真实工况中的泛化能力和稳定性; 阅读建议:建议读者结合所提供的Python代码逐模块深入学习,重点理解数据预处理流程、噪声抑制模块的设计原理以及半监督损失函数的实现细节,同时可在不同公开电池数据集上进行迁移实验与对比分析,以全面掌握该方法的有效性与适用边界。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值