Best name for array indexed by id with boolean value - naming-conventions

I get obsessed with the best names for arrays and variables that I use, I'll look up words in the thesaurus, dictionary, etc..
So I'm trying to name this array / structure:
$nameMe = array(
'392' => TRUE,
'234' => TRUE,
'754' => TRUE,
'464' => TRUE,
);
and it's used to check if that id has a certain property, like so
if(isset($name[$id])) {
doSomething();
}
Problem being I'm getting really long variable names like
$propertyNameArrayIdIndexed
Any ideas for how I can better name this particular function of array? or better names in general

$hasProperty[$id]
or
$isSomething[$id]
What is the property exactly?
$isOdd[$id]
$isWriteable[$id]
$hasAssociatedFile[$id]

Nothing wrong with long variable names, as long as they describe what the variable is doing, rather than how it's declared or defined.

I would drop "Array" from variable names.
A function that used the array may be named something like:
IsPropertyAvailable?($id)
or just
IsAvailable?($id)
when properly encapsulated.
So the associated data structure for querying could be named
$availableIds

Name variables by their "role" (in the UML sense) not their type. So, the proper name for the variable should depend very much on where and how its used. Simply knowing the type of data structure is not enough to give it an apt name. So, say that you have an enumeration of properties, each of which might be renderable as an icon. I'd leave out any indication of type, and declare it something like Set<Property> displayableIcons.
Even if you are using Hungarian notation, the actual type shouldn't be part of the name, but some type-qualifier or indication of an informal sub-type would be alright, like String b64JpgMugshot.

You want your code to read as much like plain English as possible. In plain English you'd end up with something like;
If the car is red
Do the red car stuff
So my recommendation is to avoid introducing unnecessary computerese ('array', 'property', 'index' etc.) into the naming of the variable. Your programming language is imposing "isset" on you. That's fine, that makes it clear that you have an array of booleans and means you can simply say;
if( isset(red[car_idx]) )
dosomething();
Summary: I think the array should be named simply as the property you are trying to test for. If the name of the property is a nice English language adjective that either applies to a noun or not, the boolean nature of the array is apparent even without isset(). So simply;
Red[], Oblong[], Large[]
Not IsRed[], IsOblong[], IsLarge[] because the extra "Is" in addition to the one in isset() is redundant.

propertyNameable, IspropertyNameable.

is your array only going to contain true? If so, I'd say change your data structure to something like this:
$availableIds = array(392, 234, 754, 464);
and then your if statements are much more meaningful:
if (in_array($myId, $availableIds)) { ... }

I just use dah[].

I would agree with other commenters that the question seems to lack proper context for proper concise naming, but something generic like able['foo'], enabled['bar'] or ready['ack'] may work.

Related

Should I give up grammatical correctness when naming my functions to offer regularity?

I implement several global functions in our library that look something like this:
void init_time();
void init_random();
void init_shapes();
I would like to add functions to provide a check whether those have been called:
bool is_time_initialized();
bool is_random_initialized();
bool are_shapes_initialized();
However, as you can see are_shapes_initialized falls out of the row due to the fact that shapes is plural and therefore the function name must start with are and not is. This could be a problem, as the library is rather large and not having a uniform way to group similiar functions under the same naming convention might be confusing / upsetting.
E.g. a user using IntelliSense quickly looking up function names to see if the libary offers a way to check if their initialization call happened:
They won't find are_shapes_initialized() here unless scrolling through hundreds of additional function / class names.
Just going with is_shapes_initialized() could offer clarity:
As this displays all functions, now.
But how can using wrong grammar be a good approach? Shouldn't I just assume that the user should also ask IntelliSense for "are_initialized" or just look into the documentation in the first place? Probably not, right? Should I just give up on grammatical correctness?
The way I see it, a variable is a single entity. Maybe that entity is an aggregate of other entities, such as an array or a collection, in which case it would make sense to give it a plural name e.g. a set of Shape objects could be called shapes. Even so, it is still a single object. Looking at it that way, it is grammatically acceptable to refer to it as singular. After all, is_shapes_initialized actually means "Is the variable 'shapes' initialized?"
It's the same reason we say "The Bahamas is" or "The Netherlands is", because we are referring to the singular country, not whatever plural entity it is comprised of. So yes, is_shapes_initialized can be considered grammatically correct.
It's more a matter of personal taste. I would recommend putting "is" before functions that return Boolean. This would look more like:
bool is_time_initialized();
bool is_random_initialized();
bool is_shapes_initialized();
This makes them easier to find and search for, even if they aren't grammatically correct.
You can find functions using "are" to show it is plural in places such as the DuckDuckGo app, with:
areItemsTheSame(...)
areContentsTheSame(...)
In the DuckDuckGo app, it also uses "is" to show functions return boolean, and boolean variables:
val isFullScreen: Boolean = false
isAssignableFrom(...)
In OpenTK, a C# Graphics Library, I also found usage of "are":
AreTexturesResident(...)
AreProgramsResident(...)
In the same OpenTK Libary, they use "is" singularly for functions that return boolean and boolean variables:
IsEnabledGenlock(...)
bool isControl = false;
Either usage could work. Using "are" plurally would make more sense grammatically, and using "if" plurally could make more sense for efficiency or simplifying Boolean functions.
Here's what I would do, assuming you are trying to avoid calling this function on each shape.
void init_each_shape();
bool is_each_shape_initialized();
Also assuming that you need these functions, it seems like it would make more sense to have the functions throw an exception if they do not succeed.

How to name a function that creates fixpoint results on its input?

I have a function that decorates a string. If the decorated string is again fed to the function, it is guaranteed not to change. How is the standard naming convention for such a function? I'll probably create a namespace because I need to have a few of those functions.
I've come up with:
repetition_safe.decorate(me);
fixpoint_gen.decorate(me);
one_time_effect.decorate(me);
but I don't really like any of these.
How would you name the namespace or function?
How about:
StringDecorator.MakeImmutable(input);
I think "MakeImmutable" is better than "Decorate" as the later is ambiguous i.e. a user reading the code won't know what "decorate" does, whereas "makeImmutable" will inform the user that this function will make the input string immutable/non-changable.

Runtime method to get names of argument variables?

Inside an Objective-C method, it is possible to get the selector of the method with the keyword _cmd. Does such a thing exist for the names of arguments?
For example, if I have a method declared as such:
- (void)methodWithAnArgument:(id)foo {
...
}
Is there some sort of construct that would allow me to get access to some sort of string-like representation of the variable name? That is, not the value of foo, but something that actually reflects the variable name "foo" in a local variable inside the method.
This information doesn't appear to be stored in NSInvocation or any of its related classes (NSMethodSignature, etc), so I'm not optimistic this can be done using Apple's frameworks or the runtime. I suspect it might be possible with some sort of compile-time macro, but I'm unfamiliar with C macros so I wouldn't know where to begin.
Edit to contain more information about what I'm actually trying to do.
I'm building a tool to help make working with third-party URL schemes easier. There are two sides to how I want my API to look:
As a consumer of a URL scheme, I can call a method like [twitterHandler showUserWithScreenName:#"someTwitterHandle"];
As a creator of an app with a URL scheme, I can define my URLs in a plist dictionary, whose key-value pairs look something like #"showUserWithScreenName": #"twitter://user?screenName={screenName}".
What I'm working on now is finding the best way to glue these together. The current fully-functioning implementation of showUserWithScreenName: looks something like this:
- (void)showUserWithScreenName:(NSString *)screenName {
[self performCommand:NSStringFromSelector(_cmd) withArguments:#{#"screenName": screenName}];
}
Where performCommand:withArguments: is a method that (besides some other logic) looks up the command key in the plist (in this case "showUserWithScreenName:") and evaluates the value as a template using the passed dictionary as the values to bind.
The problem I'm trying to solve: there are dozens of methods like this that look exactly the same, but just swap out the dictionary definition to contain the correct template params. In every case, the desired dictionary key is the name of the parameter. I'm trying to find a way to minimize my boilerplate.
In practice, I assume I'm going to accept that there will be some boilerplate needed, but I can probably make it ever-so-slightly cleaner thanks to NSDictionaryOfVariableBindings (thanks #CodaFi — I wasn't familiar with that macro!). For the sake of argument, I'm curious if it would be possible to completely metaprogram this using something like forwardInvocation:, which as far as I can tell would require some way to access parameter names.
You can use componentsSeparatedByString: with a : after you get the string from NSStringFromSelector(_cmd) and use your #selector's argument names to put the arguments in the correct order.
You can also take a look at this post, which is describing the method naming conventions in Objective C

Common name for variable and constant

In programming (and math) there are variables and constants. Is there a name to describe both of them?
I was thinking value, but that's not it. A value is what variables/constants contain, not what they are.
I would call it a symbol. From google:
sym·bol/ˈsimbəl/Noun
1. A thing that represents or stands for something else,
esp. a material object representing something abstract.
...
From what I know Its called a field
How about:
maths and logic: term
programming: l-value and r-value.
There are a few different terms I use, depending on context. I'll give you a list of the terms I (might) use - sometimes I'll just default to calling everything 'variables'.
Field - a variable or constant that's declared as part of the class definition.
Parameter - one of the inputs specified when defining a method in a class.
Argument - the actual value that you provide for a parameter when calling a method.
Method variable - a variable declared inside a method.
Method constant - a constant declared inside a method.
In OOP, the attribute can be both a variable and a constant.
Identifiers
In computer languages, identifiers are tokens (also called symbols) which name language entities. Some of the kinds of entities an identifier might denote include variables, types, labels, subroutines, and packages.
Symbols are super set of Identifiers
https://en.wikipedia.org/wiki/Identifier#In_computer_languages
How about "data item"?
One definition: https://www.yourdictionary.com/data-item
Example showing it can be used for local variables/constants as well (unlike "field" or "attribute"): https://www.microfocus.com/documentation/visual-cobol/VC222/EclWin/GUID-A3B817EE-1D63-4F67-A62C-61DE681C6719.html

Boolean method naming readability

Simple question, from a readability standpoint, which method name do you prefer for a boolean method:
public boolean isUserExist(...)
or:
public boolean doesUserExist(...)
or:
public boolean userExists(...)
public boolean userExists(...)
Would be my prefered. As it makes your conditional checks far more like natural english:
if userExists ...
But I guess there is no hard and fast rule - just be consistent
I would say userExists, because 90% of the time my calling code will look like this:
if userExists(...) {
...
}
and it reads very literally in English.
if isUserExist and if doesUserExist seem redundant.
Beware of sacrificing clarity whilst chasing readability.
Although if (user.ExistsInDatabase(db)) reads nicer than if (user.CheckExistsInDatabase(db)), consider the case of a class with a builder pattern, (or any class which you can set state on):
user.WithName("Mike").ExistsInDatabase(db).ExistsInDatabase(db2).Build();
It's not clear if ExistsInDatabase is checking whether it does exist, or setting the fact that it does exist. You wouldn't write if (user.Age()) or if (user.Name()) without any comparison value, so why is if (user.Exists()) a good idea purely because that property/function is of boolean type and you can rename the function/property to read more like natural english? Is it so bad to follow the same pattern we use for other types other than booleans?
With other types, an if statement compares the return value of a function to a value in code, so the code looks something like:
if (user.GetAge() >= 18) ...
Which reads as "if user dot get age is greater than or equal to 18..." true - it's not "natural english", but I would argue that object.verb never resembled natural english and this is simply a basic facet of modern programming (for many mainstream languages). Programmers generally don't have a problem understanding the above statement, so is the following any worse?
if (user.CheckExists() == true)
Which is normally shortened to
if (user.CheckExists())
Followed by the fatal step
if (user.Exists())
Whilst it has been said that "code is read 10x more often than written", it is also very important that bugs are easy to spot. Suppose you had a function called Exists() which causes the object to exist, and returns true/false based on success. You could easily see the code if (user.Exists()) and not spot the bug - the bug would be very much more obvious if the code read if (user.SetExists()) for example.
Additionally, user.Exists() could easily contain complex or inefficient code, round tripping to a database to check something. user.CheckExists() makes it clear that the function does something.
See also all the responses here: Naming Conventions: What to name a method that returns a boolean?
As a final note - following "Tell Don't Ask", a lot of the functions that return true/false disappear anyway, and instead of asking an object for its state, you tell it to do something, which it can do in different ways based on its state.
The goal for readability should always be to write code the closest possible to natural language. So in this case, userExists seems the best choice. Using the prefix "is" may nonetheless be right in another situations, for example isProcessingComplete.
My simple rule to this question is this:
If the boolean method already HAS a verb, don't add one. Otherwise, consider it. Some examples:
$user->exists()
$user->loggedIn()
$user->isGuest() // "is" added
I would go with userExists() because 1) it makes sense in natural language, and 2) it follows the conventions of the APIs I have seen.
To see if it make sense in natural language, read it out loud. "If user exists" sounds more like a valid English phrase than "if is user exists" or "if does user exist". "If the user exists" would be better, but "the" is probably superfluous in a method name.
To see whether a file exists in Java SE 6, you would use File.exists(). This looks like it will be the same in version 7. C# uses the same convention, as do Python and Ruby. Hopefully, this is a diverse enough collection to call this a language-agnostic answer. Generally, I would side with naming methods in keeping with your language's API.
There are things to consider that I think were missed by several other answers here
It depends if this is a C++ class method or a C function. If this is a method then it will likely be called if (user.exists()) { ... } or if (user.isExisting()) { ... }
not if (user_exists(&user)) .
This is the reason behind coding standards that state bool methods should begin with a verb since they will read like a sentence when the object is in front of them.
Unfortunately lots of old C functions return 0 for success and non-zero for failure so it can be difficult to determine the style being used unless you follow the all bool functions begin with verbs or always compare to true like so if (true == user_exists(&user))
Why not rename the property then?
if (user.isPresent()) {
Purely subjective.
I prefer userExists(...) because then statements like this read better:
if ( userExists( ... ) )
or
while ( userExists( ... ) )
In this particular case, the first example is such horrible English that it makes me wince.
I'd probably go for number three because of how it sounds when reading it in if statements. "If user exists" sounds better than "If does user exists".
This is assuming it's going to be to used in if statement tests of course...
I like any of these:
userExists(...)
isUserNameTaken(...)
User.exists(...)
User.lookup(...) != null
Method names serves for readability, only the ones fit into your whole code would be the best which most of the case it begins with conditions thus subjectPredicate follows natural sentence structure.
Since I follow the convention to put verb before function name, I would do the same here too:
//method name
public boolean doesExists(...)
//this way you can also keep a variable to store the result
bool userExists = user.doesExists()
//and use it like a english phrase
if (userExists) {...}
//or you can use the method name directly also and it will make sense here too
if (user.doesExists()) {...}