违反了哪些SOLID原则? (我应该怎么做才能解决此Controller问题?)

时间:2019-02-06 10:04:04

标签: c# asp.net model-view-controller

最近我进行了一次求职面试,面试官给了我一段代码来解决它违反SOLID原则的问题,但是我不是专家程序员,并且由于缺乏知识无法找到任何问题,现在我正在要求您帮助我

这段代码有什么问题?

using System.Data.SqlClient;
using System.Linq;
using System.Web.Mvc;
using System.IO;
namespace InterviewTest.Controllers
{
    public class EMailController : Controller
    {
        const string logFile = "log.txt";

        // this is a method which takes an id or a username after searching in 
       //database this method sends an email to the searched id or username 
       //then this operation Is stored in a log file...

        public ActionResult Index()
        {
            string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password = myPassword;";

            SqlConnection con = new SqlConnection(connectionString);

            con.Open();

            SqlCommand cmd = new SqlCommand("select * from tblUsers where id = " + int.Parse(Request.QueryString["id"]) + " or username = '" + Request.QueryString["username"] + "'" , con);
            SqlDataReader reader = cmd.ExecuteReader();

            reader.Read();

            string email = reader.GetString(2);

            emailer.Instance.send(email);

            FileStream fs = System.IO.File.OpenWrite("c:\\myapp\\" + logFile);
            StreamWriter sw = new StreamWriter(fs);

            sw.Write(DateTime.Now.ToString() + " sent email to " + email);

            fs.Close();

            return View();
        }

        // This is a class Which is responsible for sending email
        public class emailer
        {
            private static emailer instance = null;

            public static emailer Instance
            {
                get {
                    if (instance == null)
                    {
                        instance = new emailer();
                    }
                    return instance;
                }
            }

            internal void send(string email) {
                try {
                    // Suppose this piece of code has been implemented
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

(我假设您内心了解这些原理,所以我不会解释它们的含义)

单一责任:因为控制器负责从数据库中检索数据(通常是通过存储库或服务存储库组合来完成)以及电子邮件发送,因此应该在服务中使用控制器。

打开-关闭原则:电子邮件发件人类与控制器在同一位置实现,因此显然不能打开以进行扩展和关闭以进行修改

接口隔离:完全没有使用

依赖倒置:完全不使用,例如存储库类和电子邮件发送服务应隐藏在接口(即IEmailSender,IMyDataRepository)后面,并且控制器应使用不了解/关心确切实现的接口。如果与依赖注入一起使用,甚至更好->控制器将通过使用Unity,SimpleInjector等获得构造函数中实现这些接口的类的实例。

Liskov:没有使用类层次结构和接口等。

如果我必须实现这样的东西:

public class EmailController : Controller
{
  // Interface segregation applied
  private IEmailSendingService emailService;
  private IUserService userService;
  private ILoggingService loggingService

  // Dependency inversion principle / Dependency injection applied
  public EmailController(IEmailService mailSrvc, IUserservice usrSvc, ILoggingService log)
  {
      this.emailService = mailSrvc;
      this.userService = usrSvc;
      this.loggingService = log;
  }

  public ActionResult SendEmail()
  {
    try
    {
      var emailAddress = this.userService.GetEmail(...);
      // validate email address, maybe through another service
      if(Validator.ValidateEmail())
      {
          // Single responsibility applied
          this.emailService.SendEmail(emailAddress);
      }          
    }
    catch(MailNotFoundException ex)
    {
      this.loggingService.LogError("Email address not found for xy user");
      return NotFound();
    }
    catch(EmailSendingFailedException ex)
    {
      this.loggingService.LogError("Could not send email because xyz");
      // return internalservererror etc.
    }
    catch(Exception ex)
    {
      this.loggingService.LogError("...");
    }          

      // return whats needed
  }
}

该示例并非完美无缺,但您可以充分理解它的要点:)