最近我参加了一次工作面试,面试官给了我一段代码来解决它违反 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());
}
}
}
}
}
最佳答案
(我假设你熟记这些原则,所以我不会解释它们的含义)
单一职责:因为 Controller 负责从数据库中检索数据(通常通过存储库或服务-存储库组合完成)以及电子邮件发送,这应该在服务中使用 Controller 。
开闭原则:email sender class和controller在同一个地方实现,显然不对扩展开放,对修改关闭
接口(interface)隔离:根本不用
依赖倒置:根本没有使用,例如存储库类和电子邮件发送服务应隐藏在接口(interface)(即 IEmailSender、IMyDataRepository)后面,并且 Controller 应使用那些不知道/不关心确切实现的接口(interface)。如果与依赖注入(inject)结合使用会更好 -> Controller 将通过使用 Unity、SimpleInjector 等获得在构造函数中实现这些接口(interface)的类的实例。
Liskov:没有使用类层次结构和接口(interface)等。
如果我必须实现这样的东西:
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
}
}
这个例子并不完美,但你可以理解它的要点:)
关于c# - 违反了哪些 SOLID 原则? (我应该怎么做才能解决这个 Controller 问题?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54550903/