返回的作品,更优雅的方式第一种方法? [英] Returning the first method that works, more elegant way?

查看:135
本文介绍了返回的作品,更优雅的方式第一种方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我发现自己编写这调用其他方法相继方法以及基于哪种方法首先返回一个适当的值一定的价值。我一直在做的是一个方法设定值,然后检查值,如果它不是那么好我检查下一个。下面是最近的一个例子:

Recently I've found myself writing methods which call other methods in succession and setting some value based on whichever method returns an appropriate value first. What I've been doing is setting the value with one method, then checking the value and if it's not good then I check the next one. Here's a recent example:

private void InitContent()
{
    if (!String.IsNullOrEmpty(Request.QueryString["id"]))
    {
        Content = GetContent(Convert.ToInt64(Request.QueryString["id"]));
        ContentMode = ContentFrom.Query;
    }

    if (Content == null && DefaultId != null)
    {
        Content = GetContent(DefaultId);
        ContentMode = ContentFrom.Default;
    }

    if (Content == null) ContentMode = ContentFrom.None;
}

下面的的getContent 方法应该返回如果 ID 不是在数据库中。这是一个简短的例子,但你可以想像,如果有更多的选择,这可能让笨重。有没有更好的方式来做到这一点?

Here the GetContent method should be returning null if the id isn't in the database. This is a short example, but you can imagine how this might get clunky if there were more options. Is there a better way to do this?

推荐答案

我建议你尝试一些工厂设计模式的这种情况。你可以抽象的内容创建由注册不同的创造者的过程。此外,你可以在每个创作者为自己的逻辑添加偏好。此外,我建议你封装相关的内容,就像其他的帖子ContentDefinition类中的所有数据。

I suggest you try some kind of Factory design pattern for this case. You can abstract the content create procedure by register different creators. Moreover, you can add preference on each creator for your own logic. Besides, I suggest you encapsulate all data related to Content just like "ContentDefinition" class from other's post.

在一般情况下,你需要知道,总有一个权衡灵活性和效率之间。有时你的第一个解决方案是不够好:)

In general, you need to know that there is always a trade off between flexibility and efficiency. Sometime your first solution is good enough:)

这篇关于返回的作品,更优雅的方式第一种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆