Question: Duplicating a variable to give it a better name

Question

Duplicating a variable to give it a better name

Answers 1
Added at 2016-12-08 02:12
Tags
Question

Something that has been on my mind for a while now and I can't seem to find what I am looking for online to answer my question because as you can probably guess from the title, I don't really know how to phrase what I am asking as a question but I'll try to explain.

I am currently working in Python for an assignment and we have to solve a word search puzzle. The last stage I am working on is drawing lines through the words that have been found. Say for example a word has been found going horizontally, the pixel coordinates I need are the x and y of the first letter of the word and the x and y of the last letter of the word BUT if a word has been found going horizontally for the last letter, only the x coordinate has been changed.

tldr;

Would it be better to code like this:

if found:
    last_x = x + ((len(word) - 1) * direction)
    last_y = y
    foundWords.append(get_new_found_word(x, y, last_x, last_y))  

or would it be better to code like this:

if found:
    last_x = x + ((len(word) - 1) * direction)
    foundWords.append(get_new_found_word(x, y, last_x, y)) 

For clarification, x and y in this method are for the rows and columns in the word search grid and not the pixels. The direction is either 1 or -1 (looking left or right from the start letter)

So what I am trying to ask is if it is better to create a variable last_y because it reads better and is easier to understand at a glance, or is it better to just use the y variable that is the same thing or does it not matter at all?

Many Thanks, James

Answers to

Duplicating a variable to give it a better name

nr: #1 dodano: 2016-12-08 12:12

First of all I would have suggested you to use more meaningful names for your x and y variables. For example, based on your comments, x could have been named word_pixel_x and the y could have been named word_pixel_y. However, the correct naming should be based on the rest of your code

Now for your question, my suggestion is to create two different get_new_found_word methods for your two different cases. A method for the case where your word found horizontally and another for the case where your word found diagonally. For the first case you will just pass three variables since the y and last_y will be the same.

eg.

get_new_found_word_horizontally(x, y, last_x)
get_new_found_word_diagonally(x, y, last_x, last_y)

Of course, the above are just suggestions from my own experience and based on the evidence your have provided.

Source Show
◀ Wstecz