LBYL vs EAFP in Java?
Personally, and I think this is backed up by convention, EAFP is never a good way to go.
You can look at it as an equivalent to the following:
if (o != null)
o.doSomething();
else
// handle
as opposed to:
try {
o.doSomething()
}
catch (NullPointerException npe) {
// handle
}
Moreover, consider the following:
if (a != null)
if (b != null)
if (c != null)
a.getB().getC().doSomething();
else
// handle c null
else
// handle b null
else
// handle a null
This may look a lot less elegant (and yes this is a crude example - bear with me), but it gives you much greater granularity in handling the error, as opposed to wrapping it all in a try-catch to get that NullPointerException
, and then try to figure out where and why you got it.
The way I see it EAFP should never be used, except for rare situations. Also, since you raised the issue: yes, the try-catch block does incur some overhead even if the exception is not thrown.
Is Javascript LBYL or EAFP?
The top answer to this reddit post sums up my opinion on this pretty well, but I'll give my 2 bits.
Definitely Look Before You Leap.
Consider this code.
const thing = {};
try {
thing.forestryServices.apply();
}
catch (e) {
console.log(e);
}
thing.forestryServices = {
apply: "surprise goombas"
}
try {
thing.forestryServices.apply();
}
catch (e) {
console.log(e);
}
The error returned in both cases is an object of type Error. Trying to recover from those errors would be significantly more difficult than doing the required checks ahead of time to make sure your object is valid for what you're trying to do to it.
EAFP. Ask for forgiveness not permission in Java
You can avoid the overhead of throwing an exception by checking the size of the array:
if(rowIndex < array2D.length)
{
if(columnIndex < array2D[rowIndex].length)
{
// you are safe here
}
}
Concurrency implications of EAFP/LBYL
Your thoughts are correct. Some additional points:
If the attribute exists most of the time, try:except: might be much faster than
the LBYL idiom.
If you don't like the try: except: syntax, you can also write:
item = getattr(foo, 'bar', None)
if item is None:
....
else:
....
Choosing between if() and try-catch
Interestingly enough, your question depends on the programming language you are talking about.
In languages such as C, Java, C++, C# ... people prefer the "LBYL" (Look Before You Leap) pattern; whereas languages such as python heavily emphasize "EAFP" (it's Easier to Ask for Forgiveness than Permission).
Meaning: in python, you are using try/catch a lot (even the "counting for loop" is implemented as try/catch); whereas in C#, Java, C++ you would prefer doing if/else instead.
And these conventions are really important to follow - most Cx-language programmers simply assume that you don't use try/catch to model control flow. In other words: you should follow that paradigm that the majority of other developers in that language would be using.
what is the elegant way to check if a nested list has and has NOT a value at a specific index?
Python's much loved EAFP approach with exception handling would be my way of doing it.
try:
print(ar[i][j]) # i -> row index, j -> col index
except IndexError:
print('Error!')
Another way, also known as the LYBL approach, would be using if
checks:
if i < len(ar) and j < len(ar[i]):
print(ar[i][j])
And here's the "one liner" version (that kills readability, but you seem to want):
print(ar[i][j] if i < len(ar) and j < len(ar[i]) else "Error")
- What is the EAFP principle in Python?
- LBYL vs EAFP in Java? (the same concept applies to almost any language.)
Related Topics
Recyclerview Scrolled Up/Down Listener
Fragment Add or Replace Not Working
Nullpointerexception on Button.Findviewbyid()
Rotate Marker and Move Animation on Map Like Uber Android
Onintercepttouchevent Only Gets Action_Down
Center Message in Android Dialog Box
Listview Selection Remains Persistent After Exiting Choice Mode
How to Use Tablayout with Viewpager2 in Android
App Crashing When Trying to Use Recyclerview on Android 5.0
Android Studio - Failed to Complete Gradle Execution - Error in Opening Zip File
How to Detect a Click in an Ontouch Listener
Convert a String to a Byte Array and Then Back to the Original String
Why Can't I Use Resources.Getsystem() Without a Runtime Error
Double Tap: Zoom on Android Mapview
How to Convert Camelcase into Human-Readable Names in Java
Hibernate: Automatically Creating/Updating the Db Tables Based on Entity Classes
How to Use Mockito with Junit5
Java.Net.Unknownhostexception: Invalid Hostname for Server: Local