//修改前namespace CleanCSharp.Errors.Dirty { public class SomeClass { public int DoSomeProcess(int? id) { if (id == null) { return -1; // null id } string data = LoadData(); if (string.IsNullOrWhiteSpace(data)) { return -2; // data is corrupt } ProcessData(data); return 0; // no error, all good } private string LoadData() { return "some data"; } private void ProcessData(string data) { // do something } } }
修改前,调用 namespace CleanCSharp.Errors.Dirty { public class ConsumerOfSomeClass { public void Consume() { var sc = new SomeClass(); const int idToProcess = 42; int returnCode = sc.DoSomeProcess(idToProcess); switch (returnCode) { case -1: // null id // do something break; case -2: // corrupt data // do something break; case 0: // no error Save(idToProcess); break; } } private void Save(int id) { // save } } }
//修改后 using System; using System.IO; namespace CleanCSharp.Errors.Clean { public class SomeClass { public void DoSomeProcess(int? id) { if (id == null) { throw new ArgumentNullException("id"); } string data = LoadData(); ProcessData(data); } private string LoadData() { var demoData = ""; if (string.IsNullOrWhiteSpace(demoData)) { throw new InvalidDataException( "The data stream contains no data."); } return demoData; } private void ProcessData(string data) { // do something } } }
//修改后 using System; using System.Diagnostics; using System.IO; namespace CleanCSharp.Errors.Clean { public class ConsumerOfSomeClass { public void Consume() { var sc = new SomeClass(); const int idToProcess = 42; try { sc.DoSomeProcess(idToProcess); } catch (ArgumentNullException ex) { // null id // do something such as logging // if cannot respond to this // exception propagate up the // call stack throw; // Notice the throw is not: throw ex; } catch (InvalidDataException ex) { // bad data // do something throw; } catch (Exception ex) { // any other exceptions that may occur // do something throw; } Save(idToProcess); } private void Save(int id) { // save } } }
时间: 2024-10-18 01:10:00