Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a proper way to do function/method calls in programming

Tags:

coding-style

So, I was coding and I essentially got this line of code

return parseInt(trim(elem.value.substring(1, elem.value.length)))

And I was thinking, is this proper or would a professor/employer slam me for allowing such a line of code.

I feel like, while nice a tidy, this is difficult to understand what the crap I was doing at first glance. This one isn't so bad b/c most of the calls are common enough (making sure it's an int, trimming the string so conversion works and removing unnecessary information from the beginning of the string)

But, is this ok? Or should I break it down and comment each line so it's easier to understand for future programmers? Like...

var returnInt;
returnInt = elem.value.substring(1, elem.value.length); //remove $ symbol
returnInt = trim(returnInt); //trim whitespace
returnInt = parseInt(returnInt); //convert to int
return returnInt;

I wasn't sure how to search for this so I apologize if there's something on this.

like image 759
Chauncey Philpot Avatar asked Feb 17 '26 10:02

Chauncey Philpot


2 Answers

The first format is fine, except that it can make runtime exceptions like NullPointerExceptions difficult to debug (because the stack trace returns a line number and there are multiple things it could be on one line). So if NPEs can occur, write it out in multiple lines.

And it's not necessary to end-of-line comment every line. It's pretty obvious what trim and parseToInt do to anyone but the most novice programmer, and a simple Google search would turn that up anyways.

like image 132
smcg Avatar answered Feb 19 '26 21:02

smcg


It's okay as long as you format your code nicely. e.g. your line may look like:

return parseInt(
         trim(
           elem.value.substring(1, elem.value.length)))

quote:

Or should I break it down and comment each line so it's easier to understand for future programmers? Like...

var returnInt;
returnInt = elem.value.substring(1, elem.value.length); //remove $ symbol
returnInt = trim(returnInt); //trim whitespace
returnInt = parseInt(returnInt); //convert to int
return returnInt;

It's not easier. Excessive mutability is evil; and this won't work if your values have different type. (Oops, you are probably using dynamic-typed language, but then the name of var returnInt will be misleading, because at some program states is is indeed not an Int). Please, don't write code like this.

like image 37
Display Name Avatar answered Feb 19 '26 20:02

Display Name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!