Skip to content

Instantly share code, notes, and snippets.

@eirslett
Created March 24, 2013 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eirslett/5233325 to your computer and use it in GitHub Desktop.
Save eirslett/5233325 to your computer and use it in GitHub Desktop.
Examples for #THRIFT-1871
// === Scenario 1: Today's Thrift, no null-safety ===
// IDL file
User {
1: i32 id;
2: optional i32 born;
3: string name;
}
UserService {
User getUserById(1: i32 id);
}
// Generated java code (pseudo)
class User {
...
int getId() { ... }
int getBorn() { ... }
String getName() { ... }
}
class UserService {
User getUserById(int id) { ... }
}
// Code usage - will have runtime errors
User user = userService.getUser(123); // Assume that user #123 exists
System.out.println(2013 - user.getBorn()); // If user#123 has no birth date specified, this will output 2013
User user2 = userService.getUser(456); // Now, assume that user #456 doesn't exist
System.out.println(user2.getName()); // NullPointerException!
// === Scenario 2: How Scrooge (the alternative Thrift compiler) would compile the same IDL, and the resulting code ===
// IDL file
User {
1: i32 id;
2: optional i32 born;
3: string name;
}
UserService {
User getUserById(1: i32 id);
}
// Generated java code (pseudo)
class User {
...
int getId() { ... }
Option<Integer> getBorn() { ... }
String getName() { ... }
}
class UserService {
User getUserById(int id) { ... }
}
// Code usage - this error will be caught on compile-time
User user = userService.getUser(123); // Assume that user #123 exists
System.out.println(2013 - user.getBorn()); // We get a compile-time error here!
// This compiles, and works, no bugs:
if (user.getBorn().isDefined) {
System.out.println(2013 - user.getBorn());
} else {
System.out.println("Age unknown.");
}
// This error will still not be caught
User user2 = userService.getUser(456); // Now, assume that user #456 doesn't exist
System.out.println(user2.getName()); // NullPointerException!
// === Scenario 3: Like scenario 2, but now a function's return value is allowed to be optional ===
// IDL file
User {
1: i32 id;
2: optional i32 born;
3: string name;
}
UserService {
optional User getUserById(1: i32 id);
}
// Generated java code (pseudo)
class User {
...
int getId() { ... }
Option<Integer> getBorn() { ... }
String getName() { ... }
}
class UserService {
Option<User> getUserById(int id) { ... }
}
// This error will be caught on compile-time!
User user2 = userService.getUser(456);
System.out.println(user2.getName()); // Compile-time error: Option<User> has no method "getName"
// This compiles, and works, no bugs:
if (user2.isDefined) {
System.out.println(user2.getName());
} else {
System.out.println("User not found");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment