DEV Community

Discussion on: Let's Clean Up: Ugly Try-Catches!

Collapse
 
andrewharpin profile image
Andrew Harpin

Good code should read like a document, really good code can be understood by a non coder.

There are sometimes benefits from abstracting complex functionality, but it is a balance of readability, functionality and performance.

Code is first and foremost a document describing the behaviour of your action.

Looking at it from a different perspective, if a Dev was to come along and they had never seen this code or your no-try mechanism.

They have to read your code, then they have to go and learn your no-try and maybe they'll understand it, maybe they won't.

However there is a high probability they've seen a try-catch, so they don't need to learn this functionality and so immediately understand what you are trying to achieve!

This is an over abstraction which makes you feel better as a particular function has been reduced, but as a piece of code actually over complicates the readability of the code as it deviates from normal coding practice.

Try catch is easily explained to a non-coder, your function less so, especially as the name doesn't reflect the functionality of it's operation.

This is why function naming is critical in abstraction.

Collapse
 
coly010 profile image
Colum Ferry

I understand what you're saying, and it makes sense. There's a cost to learning what the method does, but the same can be said for any dependency you add to your codebase.

Take for example someone adding lodash, are using both _.clone and _.cloneDeep but someone else comes along to read it. If they don't know about lodash, or the difference between those functions, they will have to go and look them up to.

Perhaps simply calling the function tryCatch might have explained more what the function is doing, BUT, for any dev that wants it to be called this, then they can alias the import.

import { noTry as tryCatch } from 'no-try';

Or

const tryCatch = require('no-try').noTry;