程式碼的重構(Refactor-Extract)
阿新 • • 發佈:2018-12-17
1、vs中的程式碼重構快捷方式:Refactor-Extract;
選中兩個需要重構的部分完整程式碼,右擊,選中Refactoe-Extract-Extract Method;
該選中的程式碼會自動形成一個Execute()方法,自己修改方法名就OK啦。
2、下面說一下我的具體程式碼修改:這個是兩個方法中執行了相同的INSERT語句,所以將它整合成一個方法;這樣後續有修改或者改動時,會方便很多,也便於程式碼閱讀。
1 //APP端(插入T_UserBookingTraining) 2 public int SubscribeIntentionMajor(int courseId, intshareUserId, string name, string phoneNum, string intentionMajor) 3 { 4 var type = 1; 5 string tidSql = @" 6 IF EXISTS( 7 SELECT tcl.TrainingInstitutionId 8 FROM dbo.T_Course tc 9 LEFT JOIN dbo.T_Class tcl ON tc.ClassId = tcl.Id 10 WHERE tc.Id = @cid)11 SELECT tcl.TrainingInstitutionId 12 FROM dbo.T_Course tc 13 LEFT JOIN dbo.T_Class tcl ON tc.ClassId = tcl.Id 14 WHERE tc.Id = @cid 15 ELSE 16 SELECT 0"; 17 var tid = DbTopOnline.ExecuteScalar<int>(tidSql, new { cid = courseId }); 18 19 returnInsertUserBookingTraining(shareUserId, name, phoneNum, intentionMajor, tid, type); 20 }
1 //官網端(插入T_UserBookingTraining) 2 public int SubscribeIntentionMajorFromWebSite(string phoneNum, int tid) 3 { 4 var shareUserId = 0; 5 var name = phoneNum; 6 var intentionMajor = "來自官網的意向"; 7 var type = 2;
8 return InsertUserBookingTraining(shareUserId, name, phoneNum, intentionMajor, tid, type); 9 }
1 //重構出來的程式碼(主要執行INSERT操作) 2 private int InsertUserBookingTraining(int shareUserId, string name, string phoneNum, string intentionMajor, int tid, int type) 3 { 4 string userIdSql = @" 5 SELECT 6 tu.Id 7 FROM 8 dbo.T_User tu 9 WHERE 10 tu.TrainingInstitutionId = @tid 11 AND Name = 'admin' 12 AND IsDel=0 13 AND IsUsed=1"; 14 var userId = DbTopManager.ExecuteScalar<int>(userIdSql, new { tid }); 15 16 string sql = @"; 17 IF EXISTS(SELECT * FROM T_UserBookingTraining WHERE Phone = @phoneNum AND TrainingInstitutionId = @tid ) --判斷手機號 18 BEGIN 19 UPDATE dbo.T_UserBookingTraining 20 SET Intention = @intentionMajor, UserName = @name 21 WHERE Phone = @phoneNum 22 END 23 ELSE 24 BEGIN 25 INSERT INTO dbo.T_UserBookingTraining 26 ( TrainingInstitutionId , 27 TemplatId , 28 SceneId , 29 Type , 30 UserId , 31 ShareUserId , 32 Phone , 33 UserName , 34 Intention , 35 ProgressStatus , 36 IsDel , 37 IsUsed , 38 CreateTime 39 ) 40 VALUES ( @tid, -- TrainingInstitutionId - int 41 0 , -- TemplatId - int 42 0 , -- SceneId - int 43 @type , -- Type - tinyint 44 @userId , -- UserId - int 45 @uid, -- ShareUserId - int 46 @phoneNum, -- Phone - nchar(11) 47 @name, -- UserName - nvarchar(20) 48 @intentionMajor, -- Intention - nvarchar(60) 49 0 , -- ProgressStatus - tinyint 50 0 , -- IsDel - bit 51 1 , -- IsUsed - bit 52 GETDATE() -- CreateTime - datetime 53 ) 54 END"; 55 return DbTopOnline.Execute(sql, new 56 { 57 userId, 58 uid = shareUserId, 59 name, 60 phoneNum, 61 intentionMajor, 62 tid, 63 type 64 }); 65 }