简体   繁体   中英

Variable shorthands

Not really related to programming in general.

I don't know if this is a struggle for anybody, and there's probably an easy solution to this problem, but I couldn't find any elegant solutions.

Everyone knows that if you're a programmer, you should write readable code to save time and help yourself in the future, like giving variables better names instead of s or n .

For Example:

public void doSomething(Function<> functionToDo, int numberOfTimes)

instead of:

public void doIt(Function<> f, int n)

But sometimes, if I have a long variable name and I have to type it in an equation that makes me have to scroll right to see the whole thing, that can get frustrating.

So, my question is: Is there any way I can define a shortcut variable that doesn't affect runtime or memory?

like c++'s pre-proccesor statement #define: #define n numberOfTimes

Or, if there isn't solution to this at all, should I keep long variable names for the readability, or keep things short instead?

Any ideas are appreciated.

It's all about the context where an identifier is declared. For instance, if your function doIt was named doNTimes it would be perfectly fine to name the parameters f and n . Also, they are local to the function so you don't need to search for their documentation (which should be just before or after the function header). As you mention, in choosing a name there is also a tradeoff between identifier comprehensibility and expression comprehensibility; whereas a more descriptive name increases the former and decreases the latter the opposite holds true for a short name.

If you know that your identifier is going to be used in complex expressions it's a good idea to use a shorter name. A function call with side-effects on the other hand will (should) only be a single statement so then the name can be longer.

To summarize, I would say that it's a good idea to keep formal parameters and local variables short as that make expressions easy to comprehend; the documentation is right there in the function anyway, eg

public void doNTimes(Function<> f, int n); /** apply f n times */

Note: In a real scenario you would also need to provide the actual parameters of f .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM