Dylan Jackson
Dylan Jackson

Reputation: 811

Is it always best practice to declare a variable?

I'm new to C# and any form of programming, and I have a question that seems to divide those in the know in my university faculty. That question is simply: do I always have to declare a variable? As a basic example of what I'm talking about: If I have int pounds and int pence do I need to declare int money into which to put the answer or is it ok to just have:

textbox1.Text = (pounds + pence).ToString();

I know both work but i'm thinking in terms of best practice.

Thanks in advance.

Upvotes: 29

Views: 5504

Answers (10)

Tony Delroy
Tony Delroy

Reputation: 106076

Localisation and scope

For a programmer, knowledge of local variables - their content and scopes - is an essential part of the mental effort in comprehending and evolving the code. When you reduce the number of concurrent variables, you "free up" the programmer to consider other factors. Minimising scope is a part of this. Every little decision implies something about your program.

void f()
{
    int x = ...;  // "we need x (or side effect) in next scope AND
                  // thereafter..."

    {
         int n = ...;  // "n isn't needed at function scope..."
         ...
    } // can "pop" that n mentally...

    ...
}

The smallest scope is a literal or temporary result. If a value is only used once I prefer to use comments rather than a variable (they're not restricted to A-Za-z0-9_ either :-)):

x = employees.find("*",                       // name
                   retirement.qualify_at(),   // age
                   num_wives() + num_kids()); // # dependents

Concision

Keeping focused on what your program is achieving is important. If you have a lot of screen real-estate (i.e. lines of code) getting fields into variables, you've less code on screen that's actually responsible for getting algorithmic level stuff done, and hence it's less tangible to the programmer. That's another reason to keep the code concise, so:

     keep useful documentation targetted and concise

Upvotes: 2

Neowizard
Neowizard

Reputation: 3017

Variables come to serve the following two purposes above all else:

  1. Place holder for data (and information)
  2. Readability enhancer

of course more can be said about the job of a variable, but those other tasks are less important here, and are far less relevant.

The above two points have the same importance as far as I'm concerned.

If you think that declaring a variable will enhance readability, or if you think that the data stored in that variable will be needed many times (and in which case, storing it in a well name var will again increase readability), then by all means create a new variable.

The only time I strictly advice against creating more variables is when the clutter of too-many-variables impacts readability more then aids it, and this cannot be undone by method extraction.

Upvotes: 3

brandon
brandon

Reputation: 1230

There are two objectives in making this decision:

  • Readability - the code is readable and self-explanatory Code
  • Optimization - the code doesn't have any unnecessary calculation

If you look at this as an optimization problem it might seem less subjective

Most readable on a scale from 1 to 10 with 10 being the easiest. Using sensible variable names may give you a 2, showing the calculation in line may give you a 3 (since the user doesn't have to look up what "money" is, it's just there in that line of code). etc etc. This piece is subjective, you and the companies you work for define what is readable and you can build this cost model from that experience.

Most optimal execution is not subjective. If you write "pounds + pence" everywhere you want the money calculation to go, you are wasting processor time. Yes I know addition is a bad example, but it still holds true. Say minimum execution of a process is simplified to memory allocation of variables, assignments, and calculations. Maybe one or two of these additions in the code will be ok for readability, but at some point it becomes a complete waste on the processor. This is why variables exist, allocate some space to store the value, name it money so the user knows what it is, and reference that variable "money" everywhere it's needed.

This makes more sense as you look at loops. lets say you want to sum 1000 values in the following loop.

money = factor[1] + factor[2] + ... + factor[n]

You could do this everywhere you want to use the value money so that anyone that reads your code knows what money consists of, instead, just do it once and write in some comments when you first calculate money so any programmers can come back and reference that.

Long story short, if you only use money once and it's clear what the inline calculation means, then of course, don't make a variable. If you plan on using it throughout your code and it's meaning becomes remotely confusing, then declare a variable, save the processor and be done with it! Note: partially kidding about this approach, just thought it was funny to answer something like this in a cost model format :) still useful I'de say

Upvotes: 1

Lucero
Lucero

Reputation: 60190

In my opinion the answer is "no". You should, however, use variables in some cases:

  • Whenever a value is used multiple times
  • When a call to an expensive function is done, or one that has side-effects
  • When the expression needs to be made more self-explaining, variable (with meaningful names) do help

Basically, follow your common sense. The code should be self-explaining and clear, if introducing variables helps with that then use them.

Upvotes: 38

Steve Wellens
Steve Wellens

Reputation: 20620

Maintenance is king. It's the most expensive part of software development and anything you can do to make it easier is good.

Variables are good because when debugging, you can inspect the results of functions and calculations.

Upvotes: 15

Ivan Crojach Karačić
Ivan Crojach Karačić

Reputation: 1911

In my opinion if you do something like

int a = SomeFunc();
int b = SomeFunc2();
int c = a + b;
SomeFunc3(c);

it is better to just do

int a = SomeFunc();
int b = SomeFunc2();
SomeFunc3(a + b);

or even just

SomeFunc3(SomeFunc() + SomeFunc2());

If I am not manipulating with the variable after it's calculated then I think it's just better not to declare it because you just get more lines of code and way more room to make some mistake later on when your code gets bigger

Upvotes: 6

Mike M.
Mike M.

Reputation: 12511

I don't recall ever seeing anything like is, and I think it's more tied to different "styles" of programming. Some styles, such a Spartan programming actually attempts to declare as few as possible. If you aren't trying to follow a particular style, then it's best to go off of readability. In your example I wouldn't declare a special variable to hold it. It you were calculating taxes based off some percentage of the total of those, then I may- or at the very least I would comment what I was calculating.

Upvotes: 0

Tony Lukasavage
Tony Lukasavage

Reputation: 1937

Absolutely not. The only time I would create a variable for a single use like this is if it significantly increases the readability of my code.

Upvotes: 7

peacedog
peacedog

Reputation: 1415

I would suggest that logging frequently makes variable declaration worthwile, and when you need to know what something specific is and you need to track that specific value. And you are logging, aren't you? Logging is good. Logging is right. Logging is freedom and unicorns and happy things.

I don't always use a variable. As an example if have a method evaluating something and returning true/false, I typically am returning the expression. The results are logged elsewhere, and I have the inputs logged, so I always know what happened.

Upvotes: 2

Bala R
Bala R

Reputation: 108937

It depends on the situation. There is no one practice that would be best for all. For something this simple, you can skip creating a new variable but the best thing to do is step back and see how readable your expression is and see if introducing an intermediate variable will help the situation.

Upvotes: 1

Related Questions