code_junkie

Best way to return status flag and message from a method in Java

Nov 12th, 2011
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. try {
  2. AuthenticateMethod();
  3. } catch (AuthenticateError ae) {
  4. // Display ae.getMessage() to user..
  5. System.out.println(ae.getMessage());
  6. //ae.printStackTrace();
  7. }
  8.  
  9. class Tuple<L, R> {
  10.  
  11. public final L left;
  12. public final R right;
  13.  
  14. public Tuple( L left, R right) {
  15. this.left = left;
  16. this.right = right;
  17. }
  18. }
  19.  
  20. public Option<String> authenticate(String arg) {
  21. if (success(arg))
  22. return Option.some("Just an example");
  23. else
  24. return Option.none();
  25. }
  26.  
  27.  
  28. ...
  29.  
  30.  
  31. for(String s : authenticate(secret)) {
  32. privilegedMethod();
  33. }
  34.  
  35. public Either<Fail, String> authenticate(String arg) {
  36. if (success(arg))
  37. return Either.right("Just an example");
  38. else
  39. return Either.left(Fail.authenticationFailure());
  40. }
  41.  
  42.  
  43. ...
  44.  
  45.  
  46. Either<Fail, String> auth = authenticate(secret);
  47. for(String s : auth.rightProjection()) {
  48. privilegedMethod();
  49. }
  50. for(Fail f : auth.leftProjection()) {
  51. System.out.println("FAIL");
  52. }
  53.  
  54. class SomeClass {
  55. public int authenticate (Client client) {
  56. //returns 0 if success otherwise one value per possible failure
  57. }
  58. public String getAuthenticationResultMessage (int authenticateResult) {}
  59. //returns message associated to authenticateResult
  60. }
  61.  
  62. if (authenticate()) {
  63. // normal behaviour...
  64. }
  65. else {
  66. // error case...
  67. }
  68.  
  69. authenticate();
  70. // normal behaviour...
  71.  
  72. if (isAuthenticated()) {
  73. //...
  74. }
  75.  
  76. public boolean authenticate(Client client, final StringBuilder sb) {
  77. if (sb == null)
  78. throw new IllegalArgumentException();
  79. if (isOK()) {
  80. sb.append("info message");
  81. return true;
  82. } else {
  83. sb.append("error message");
  84. return false;
  85. }
  86. }
  87.  
  88. public static void main(String[] args)
  89. {
  90. Object[] result = methodReturningStatus();
  91. if(!(Boolean)result[0])
  92. System.out.println("Method return: "+ result[1]);
  93. }
  94.  
  95. static Object[] methodReturningStatus()
  96. {
  97. Object[] result = new Object[2];
  98.  
  99. result[0] = false;
  100. result[1] = "Error happened";
  101.  
  102. return result;
  103. }
Add Comment
Please, Sign In to add comment