惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
D
Docker
云风的 BLOG
云风的 BLOG
F
Fortinet All Blogs
F
Full Disclosure
H
Hackread – Cybersecurity News, Data Breaches, AI and More
P
Proofpoint News Feed
Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
L
LangChain Blog
H
Help Net Security
B
Blog
T
Tailwind CSS Blog
V
V2EX
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
Recent Announcements
Recent Announcements
aimingoo的专栏
aimingoo的专栏
美团技术团队
A
About on SuperTechFans
C
Cybersecurity and Infrastructure Security Agency CISA
K
Kaspersky official blog
I
InfoQ
Project Zero
Project Zero
I
Intezer
Google DeepMind News
Google DeepMind News
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Threat Research - Cisco Blogs
Last Week in AI
Last Week in AI
C
Cyber Attacks, Cyber Crime and Cyber Security
G
GRAHAM CLULEY
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
AWS News Blog
AWS News Blog
Spread Privacy
Spread Privacy
S
Securelist
Recorded Future
Recorded Future
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 叶小钗
S
Security Affairs
Blog — PlanetScale
Blog — PlanetScale
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
罗磊的独立博客
The Hacker News
The Hacker News

博客园 - idior

每日代码 - 7/1 减小方法参数的依赖 每日代码 - 6/29 读写分离 每日代码 - 6/28 代码逻辑分组 每日代码 - 6/26 lambda表达式 Resume Covariance and Contravariance How does ElementName Binding work? Weird behavior of DataContext Inheritance How does ElementName Binding work – Part 3 InheritanceContext How does ElementName Binding work – Part 2 BindingExpression Logical Tree & Visual Tree Memory leak caused by EventHandle - weak event Resources on Debugging/Tracing WPF How does ElementName Binding work? - Part 1 Logical Tree & NameScope Inside WCF Runtime 有谁准备参加10月份的MVP聚会? MVP聚会 Practical .NET2 and C#2 翻译样章 Be evil or not?
每日代码 - 6/27 避免创建非法对象
idior · 2013-06-27 · via 博客园 - idior
 
public class BuyerHelper
{
    private static final UserRepository userRepository;

    public static void createAndCheckBuyer(Cart cart)
    {
        int userId = cart.getUserId();
        User user = userRepository.getUserById(userId);

        Buyer buyer = BuyFactory.createFrom(user);
        BaseCheckResult checkResult = BuyerChecker.checkBuyerPermission(buyer);
        
        if (checkResult.isSuccess())
            cart.setBuyer(buyer);
        else
            throw new InvaildBuyerException();        
    }
}

很简单的一段代码,存在以下问题:

1. 责任不清晰。

该方法既包含了验证用户是否是一个合法买家的功能,又实现了根据用户创建买家的功能,并且还隐藏了一个很危险的功能,它还负责将这个创建好的买家设置到cart的属性。而cart是一个外来参数,这意味着后续的代码中很有可能会依赖这个被附加到cart上的buyer属性上,而这一点其实是比较隐晦的。

2. 创建非法对象。

本方法实现的功能应该是判断一个用户是否是一个有效的买家,理论上来说如果一个用户不是有效买家的话,就不应该出现一个买家对象。但是,在这段代码中,确实先不管三七二十一先把Buyer对象创建出来,然后再对它进行验证。我们应该尽力避免创建非法对象。