1

我需要一些关于为我的基于 Web 的业务层功能选择哪些签名的意见:

函数无效 CreateUser(公司用户公司,字符串名称...)

或者

函数 void CreateUser(int CompanyID, string name...)

如果这是基于窗口的,我会选择函数来获取对象而不是 int,因为既然公司已经加载到窗口窗体,为什么不直接使用它。另外,我认为业务层应该采用业务对象并且它的类型是安全的(防止意外传入 0 或 -1)。

但另一方面,如果这是一个基于 Web 的应用程序,则只有 id 会加载到客户端站点。所以加载公司对象有点多余,因为最终只会将公司ID保存在数据库中。

希望我的描述不会太混乱 =P 感谢您的阅读。

4

1 回答 1

0

我认为您回答了自己的问题,这取决于您使用的表示层。但是,当您想保持此业务层通用时,您将不得不使用 ID。

这是另一个想法。我个人喜欢将所有突变包装到类中,我称之为命令。例如,您可以有一个CreateUserCommand从基本命令继承的。这将允许您像这样使用它(我在这里假设 C#):

var command = new CreateUserCommand();

command.UserCompanyId = companyId;
command.UserName = name;

command.Execute();

将此逻辑包装在命令中是非常好的模式。它允许您将单个用例放在单个命令中。尤其是当命令中的逻辑量增加时,您会喜欢这种模式,但我发现它对 CRUD 操作也非常有效。

此模式还允许您在基类中抽象事务模型。基类可以包装调用以在数据库事务中执行。这是一个简单的实现:

public abstract class CommandBase
{
    public void Execute()
    {
        this.Validate();

        using (var conn = ContextFactory.CreateConnection())
        {
            conn.Open();
            using (var transaction = conn.BeginTransaction())
            {
                using (var db = ContextFactory.CreateContext(conn))
                {
                    this.ExecuteInternal(db);

                    db.SubmitChanges();
                }

                transaction.Commit();
            }
        }
    }

    protected virtual void Validate() { }

    protected abstract void ExecuteInternal(YourDataContext context);
}

这就是它的CreateUserCommand样子:

public class CreateUserCommand : CommandBase
{
    public int UserCompanyId { get; set; }
    public string UserName { get; set; }

    protected override void ExecuteInternal(YourDataContext context)
    {
       this.InsertNewUserInDatabase(context);
       this.ReportCreationOfNewUser();
    }

    protected override void Validate()
    {
        if (this.UserCompanyId <= 0) 
            throw new InvalidOperationException("Invalid CompanyId");
        if (string.IsNullOrEmpty(this.UserName))
            throw new InvalidOperationException("Invalid UserName");
    }

    private void InsertNewUserInDatabase(YourDataContext context)
    {
       db.Users.InsertOnSubmit(new User()
       {
          Name = this.UserName,
          CompanyId = this.CompanyId
       });
    }

    private void ReportCreationOfNewUser()
    {
        var message = new MailMessage();
        message.To = Configuration.AdministratorMailAddress;
        message.Body = "User " + this.Name + " was created.";

        new SmtpClient().Send(message);
    }
}

我希望这有帮助。

于 2010-09-24T10:50:16.793 回答