Debugging old code in dynamically typed languages like Python, Ruby, JavaScript, etc. is often a struggle. For example, below Ruby function extracts only the key:val pairs from the result (hash) if a key is present in filters (array).
def filter(result, filters)
end
At glance there is no way of telling the data types for result and filters. Also we don't know if the result hash is using symbols or strings keys. We also don't know the data type expected by the filters elements.
My question is, how can I improve my code readability and what is the general best practice? Two things that come to mind are:
Comments - I generally avoid too many comments and would prefer making the code more descriptive. Also adding comments for each variables defined inside the function may populate the code with too many comments.
# result: hash | filters: array (strings) def filter(result, filters) endVariable Naming - Adding the data type in variable name. I'm not sure if this is good practice. e.g.
def filter(result_hash, filters_array) end
EDIT: I thought there was a standard but, I learned that this is an opinion-based question. It was good to learn about the different options available!
Both of your methods are suboptimal, although the first one is more maintainable and more readable.
The variable names are too generic.
Variable names encode the data type, which is usually (a) not needed in practice, (b) not very readable, and (c) can change with time, requiring a variable names change.
I recommend a naming convention that is more specific and does not depend on the type of the variable. Use plurals for arrays/lists, singular for scalars, and also singular for hashes/dictionaries. For example: