Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java 例外處理壞味道與重構技術

1,284 views

Published on

介紹常見的Java例外處理壞味道(bad smells)以及移除這些壞味道的重構(refactoring)方法

Published in: Design
  • Be the first to comment

Java 例外處理壞味道與重構技術

  1. 1. Teddy Chenteddy@teddysoft.twhttp://teddy-chen-tw.blogspot.twMar. 28 2013
  2. 2. Copyright@2013 Teddysoft
  3. 3. 3系統不穩定
  4. 4. 4
  5. 5. 5
  6. 6. 6
  7. 7. 7
  8. 8. 8Problem
  9. 9. 9Problem
  10. 10. Copyright@2013 Teddysoft
  11. 11. • Correctness– Contract Specification(超出範圍)• Robustness– Exception HandlingCopyright@2013 Teddysoft
  12. 12. Copyright@2013 Teddysoft
  13. 13. Copyright@2013 TeddysoftRuntimeExceptionThrowableException ErrorUncheckedExceptionCheckedException
  14. 14. Copyright@2013 Teddysofthandledeclare
  15. 15. Copyright@2013 Teddysoft
  16. 16. 16EH smell RefactoringIgnored checkedexceptionReplace Ignored Checked Exception withUnchecked ExceptionUnprotected mainprogramAvoid Unexpected Termination with BigOuter Try BlockDummy handler Replace Dummy Handler with RethrowNested try block Replace Nested Try Block with MethodIgnored checkedexception,Dummy handlerIntroduce Checkpoint ClassSpare handler Introduce Resourceful Try ClauseCopyright@2013 Teddysoft
  17. 17. public void writeFile(String fileName, String data) {Writer writer = null;try {writer = new FileWriter(fileName); /* may throw an IOException */writer.write(data); /* may throw an IOException */}catch (IOException e) {/* ignoring the exception */}}↓public void writeFile(String fileName, String data) {Writer writer = null;try {writer = new FileWriter(fileName); /* may throw an IOException */writer.write(data); /* may throw an IOException */}catch (IOException e) {throw new UnhandledException(e, “message”);}}17Copyright@2013 Teddysoft
  18. 18. 18static public void main(String[] args) {/* some code */}↓static public void main(String[] args) {try {/* some code */}catch (Throwable e) {/* displaying and/or logging the exception */}}Copyright@2013 Teddysoft
  19. 19. 19catch (AnException e) {e.printStackTrace();}↓catch (AnException e) {throw new UnhandledException(e, “message”);}Copyright@2013 Teddysoft
  20. 20. 20FileInputStream in = null;try {in = new FileInputStream(…);} finally {try { if (in != null) in.close (); }catch (IOException e) { /* log the exception */ }}↓FileInputStream in = null;try {in = new FileInputStream(…);} finally { closeIO (in); }private void closeIO (Closeable c) {try {if (c != null) c.close ();} catch (IOException e) { /* log the exception */ }}Copyright@2013 Teddysoft
  21. 21. 21public void foo () throws FailureException {try {/* code that may change the state of the object */}catch (AnException e) {throw new FailureException(e);} finally {/* code for cleanup */}}↓public void foo () throws FailureException {Checkpoint cp = new Checkpoint (/* parameters */);try {cp. establish (); /* establish a checkpoint *//* code that may change the state of the object */ }catch (AnException e) {cp.restore (); /* restore the checkpoint */throw new FailureException(e); }finally { cp.drop(); }} Copyright@2013 Teddysoft
  22. 22. 22try { /* primary */ }catch (SomeException e) {try {/* alternative */}catch(AnotherException e) {throw new FailureException(e);}}↓int attempt = 0; int maxAttempt = 2; boolean retry = false;do {try { retry = false;if (attempt == 0) { /* primary */ }else { /* alternative */ }} catch (SomeException e) {attempt++; retry = true;if (attempt > maxAttempt) throw new FailureException (e);}} while (attempt<= maxAttempt && retry)Copyright@2013 Teddysoft
  23. 23. Copyright@2013 Teddysoft
  24. 24. • CSS is a banking application for checkingcustomers’ credit history in processing theirloan applications24Credit ScoringSystem (CSS)Gateway(IBM MessageQueue)Joint CreditInformationCenter (JCIC)Authentication(DominoServer)OtherApplicationsCopyright@2013 Teddysoft
  25. 25. • The use of exceptions and return code weremixed in an arbitrary manner• Many checked exceptions were caught andignored• Unchecked exceptions were not caught whichlead to an unexpected termination of the JSPprogram• Failure atomicity of each component was notinvestigated25Copyright@2013 Teddysoft
  26. 26. • Bug fixing is a strong force drawing thedeveloper’s attention to deal withexceptions• Cost-effectiveness measurements can beprovided to convince the management tosupport the refactoring– Improving quality, saving maintenance cost, andincreasing customer satisfaction26Copyright@2013 Teddysoft
  27. 27. ReportedfailureFailing operation/ possiblereasonFailurecountCurrentrestorationactionsRestorationtime perfailureCannotmake aconnectionto DominoserverUser login/Connections of Domino InternetInter-ORB Protocol (DIIOP) wereexhausted. It was likely that DIIOPconnections were not correctlydisposed.1251. RebootingDominoserver2. RebootingCSSAbout 20minutesMQ serverconnectionis brokenSending request to JCJS/MQ connections were exhausted.Perhaps they were not properlyreleased.661. RebootingMQ Server2. RebootingCSSAbout 10minutesCannot sendmessages toMQ serverSending request to JCJS/There were two possible reasons:Message queue was full.Gateway was offline due tomaintenance or crash.101. RebootingMQ Server2. RebootingCSSAbout 10minutes 27
  28. 28. 28Credit ScoringSystem (CSS)Gateway(IBM MessageQueue)Joint CreditInformationCenter (JCIC)Authentication(DominoServer 1)OtherApplicationsAuthentication(DominoServer 2)XCopyright@2013 Teddysoft
  29. 29. 29ReportedfailureFailure count from Sep. 2005to Dec. 2005Failure count from Sep. 2006to Dec. 2006Sep. Oct. Nov. Dec. Sep. Oct. Nov. Dec.Cannot make aconnection toDomino server13 5 9 14 10 5 0 0MQ Serverconnectionbroken6 1 4 8 3/0 0 1/0 0Cannot sendmessages toMQ Server0 0 0 2 3/0 1/0 0 0Copyright@2013 Teddysoft
  30. 30. 30Code typeTotal vs.modified codeModificationpercentageNon-commentedline of code14150/371 2.63%Catch clauses 855/21 2.46%Copyright@2013 Teddysoft
  31. 31. 31Task Man-hours SumCollecting bugs reports in 2005 10 18 (43.9%)Refactoring cost (Code review) 7 (30.4%)Refactoring cost (Exception Handlinggoal analysis)4 (17.4%)Refactoring cost (Coding) 3 (13%)Refactoring cost (Testing) 9 (39.2%)Total man-hours in applyingrefactoring23 (56.1%)Total man-hours in improvingrobustness41 (100%)Copyright@2013 Teddysoft
  32. 32. 32Cost element Cost calculationMaintenance cost in 2005 201 (failure) * 2 (hours) * 100 (US$) =40,200 (US$)Refactoring cost 41 (man-hours) * 100 (US$) = 4,100 (US$)Maintenance cost saving inthe following year (money)40,200 (US$) – 4,100 (US$) = 36,100 (US$)Maintenance cost saving inthe following year(percentage)36,100 (US$) / 40,200 (US$) * 100 = 89.8%Copyright@2013 Teddysoft
  33. 33. 33Copyright@2013 TeddysoftEH smell RefactoringIgnored checkedexceptionReplace Ignored Checked Exception withUnchecked ExceptionUnprotected mainprogramAvoid Unexpected Termination with BigOuter Try BlockDummy handler Replace Dummy Handler with RethrowNested try block Replace Nested Try Block with MethodIgnored checkedexception,Dummy handlerIntroduce Checkpoint ClassSpare handler Introduce Resourceful Try Clause

×