C#を使用して単一責任原則を実装する方法は?
クラスには、変更する理由が1つだけあるはずです。
定義 −この文脈では、責任は変更する理由の1つと見なされます。
この原則は、クラスを変更する理由が2つある場合、機能を2つのクラスに分割する必要があることを示しています。各クラスは1つの責任のみを処理し、将来1つの変更を行う必要がある場合は、それを処理するクラスで変更します。より多くの責任を持つクラスに変更を加える必要がある場合、その変更は、クラスの他の責任に関連する他の機能に影響を与える可能性があります。
例
単一責任原則の前のコード
using System;
using System.Net.Mail;
namespace SolidPrinciples.Single.Responsibility.Principle.Before {
class Program{
public static void SendInvite(string email,string firstName,string lastname){
if(String.IsNullOrWhiteSpace(firstName)|| String.IsNullOrWhiteSpace(lastname)){
throw new Exception("Name is not valid");
}
if (!email.Contains("@") || !email.Contains(".")){
throw new Exception("Email is not Valid!");
}
SmtpClient client = new SmtpClient();
client.Send(new MailMessage("Test@gmail.com", email) { Subject="Please Join the Party!"})
}
}
} 単一責任原則後のコード
using System;
using System.Net.Mail;
namespace SolidPrinciples.Single.Responsibility.Principle.After{
internal class Program{
public static void SendInvite(string email, string firstName, string lastname){
UserNameService.Validate(firstName, lastname);
EmailService.validate(email);
SmtpClient client = new SmtpClient();
client.Send(new MailMessage("Test@gmail.com", email) { Subject = "Please Join the Party!" });
}
}
public static class UserNameService{
public static void Validate(string firstname, string lastName){
if (string.IsNullOrWhiteSpace(firstname) || string.IsNullOrWhiteSpace(lastName)){
throw new Exception("Name is not valid");
}
}
}
public static class EmailService{
public static void validate(string email){
if (!email.Contains("@") || !email.Contains(".")){
throw new Exception("Email is not Valid!");
}
}
}
} -
Python 3で辞書を使用して文字列をフォーマットするにはどうすればよいですか?
辞書を使用して文字列を補間できます。これらには、%と変換文字の間の括弧内にキーを指定する必要がある構文があります。たとえば、フロートがキー「cost」に格納されていて、それを「$ xxxx.xx」としてフォーマットする場合は、表示する場所に「$%(cost).2f」を配置します。 。 辞書で文字列フォーマットを使用して文字列を補間し、数値をフォーマットする例を次に示します。 >>>print('%(language)s has %(number)03d quote types.' % {'language': "Python&quo
-
Pythonを使用して文字列をJSONに変換する方法は?
json.loads()を使用してJSON文字列を辞書に変換します。このメソッドは、有効なjson文字列を受け入れ、すべての要素にアクセスできる辞書を返します。たとえば、 >>> import json >>> s = '{"success": "true", "status": 200, "message": "Hello"}' >>> d = json.loads(s) >>> print d["