Is it a good practice to start a method name with "Does" (in C#)? It looks a little bit weird to me, so I would like to get your opinion.
I am writing a method which check if an account exists or not, should the signature be
"bool DoesAccountExist(id)"? Is there a better name?
Thanks!
Personally I'd go with AccountExists(id) in this case, since it will look more natural in an if block
if (AccountExists(id)) { }
We always use Is for any method that will return a boolean, so in this case we would call the method
IsExistingAccount(id)
I usually leave off the Does and simply use AccountExists(id).
To me it looks more natural later in code such as:
if(AccountExists(id))
{
ValidateLogin();
}
The alternative would be something like:
if(!DoesAccountExist(id)) {}
seems odd to me. I would read that as if does account not exist? Which makes less then account does not exist.
The "Is" prefix idiom help clarify methods like Array "Empty" which might mean "empty the array" or "is the array empty?". If used consistently "IsEmpty" is clearly the bool return and by convention "Empty" becomes clear as the action of emptying.
In the context of the question I agree with #Andy Whites second suggest:
if (IsExitingAccount) ...
Here the 'Is' triggers a strong automatic implication of bool return constistant with its use else where (IsEmpty, IsNull, etc)
I think AccountExists is your best bet, but one other option is: IsExistingAccount. For methods or properties that return a boolean, it can be useful to use a naming convention where the method begins with the word "is". If you use "is," you'll have to rephrase the rest of the method name so that it makes sense to the reader.
Can or Is could be used like CanCopy or IsAccountExists is fine too. Following predefined conventions make code more readable. To be frank Does prefix looks a bit wierd to me as well.
Another Option is to use the standard C# plural of Is, Any.
AnyAccountsExist(id)
Related
Feel free to edit 'mutate' from the title if it's a poor choice of wording.
My question is, relatively, simple.
Take the following example:
myCollection.OrderBy(o => o);
How do I know whether OrderBy will/will not order myCollection or whether an assignment (following) is necessary:
myCollection = myCollection.OrderBy(o => o);
Is it a case of having to build it and check every time I encounter an extension I'm unfamiliar with?
Please note: I'm not asking whether this will or will not affect myCollection, I already know the answer to that from using it hundreds of times previous, I'm asking how I'd know.
You can't tell from just the signature.
The best you can do is to investigate the actual code, for example by looking at the .NET Reference Source. Another thing you could do is check the return type. If it is the same as the one it's being called on, it probably doesn't change it, it most likely returns a new instance. Is it a void, then it probably does change something inside.
For your specific case for example, OrderBy: no. See here. It 'just' returns a new OrderedEnumerable.
You can check for the Pure attribute in the class decoration as Steven Liekens said. But in its absence, the only way to know for sure is by:
Experimenting: for example, get an instance of the class and serialize it. Use the method and then serialize it. Compare the results. May not be accurate every time.
Reverse engineering the method: and I hope you have the source code. If you don't, you can use reflection. This will require some judgement if the method is somewhat complex, but this complexity here is subjective.
Reading the docs and trusting them - if the doc is present. This is the sensible thing to do with the .NET Framework types, and an exercize of faith otherwise.
One way is to find out if the method or its class is marked as [Pure]. Pure code does not modify input values.
I have a method for pulling data from a database, and I want it to get this:
Limit of Five entries,
Item type is Newsletter,
Needs to be active (PublishDate < DateTime.Now)
So I'm thinking of naming it GetFiveActiveNewslettersByCreatedDate()
This seems a little long to me. I looked on the site for a good way to name things like this, how would you handle it?
How about something like this instead?
public IEnumerable<Newsletter> GetActiveNewsletters(int maxRecords = 5)
{
// ...
}
Top 5 is still the default, but it's not overly specific anymore.
The reason I would avoid baking "five" into the name, personally, is what it might mean down the line.
For example, what if later, there were some demand for 10 newsletters in certain scenarios instead of 5? Well, you'd create an additional method GetTenActiveNewslettersByCreatedDate(). And now, you have a 'design pattern' that subsequent developers will follow when 20, 50, 100 newsletters are needed. This is a design that will rot, and you can stave it off now by parameterizing the five.
Of course, this might be YAGNI/speculative generality. If 5 really is some kind of magic, hard-fast, will never change rule, then you might cautiously bake it in. I just find that I've regretted doing and seeing things like that far, far more often than not.
I would recommend renaming it to: GetNewsletters(int recordCount=5)
The number of newsletters would be a parameter for the method.
The rest could be assumed and described in the ///Summary.
To avoid this specific naming I would think about making the method generic. Something like:
GetNewsLetters(int amount, bool onlyActive, SortOrder orderBy)
Name it so that it is evident to any developer what the method does. Self commenting code is king. If your method name gets too long, you're probably doing too many different things inside of it and would be a candidate for refactoring.
As for your specific example, I don't have a problem with the name you've given.
I would add parametrized method, like
GerEntries(T typeofEntity, DateTime date, int maxNumber)
And naturaly document method with comments
I have this method (modified code) :
public static void PublishXmlForCustomTypes(MyOwnClass DefaultOutputInformation)
{
if (DefaultOutputInformation != null)
{
///lot of code
}
}
and my whole code was inside the if statement and after thinking about it, I changed to this :
public static void PublishXmlForCustomTypes(MyOwnClass DefaultOutputInformation)
{
if (DefaultOutputInformation == null)
{
return;
}
///lot of code
}
As far as I tested it, it seems to be strictly equivalent but is that really the case ?
I mean, the "return" statement get us out of the method right ?
This is strictly equivalent and the second version is the way to go :)
Yes, that's absolutely fine.
Some people dogmatically stick to "one exit point per method" - which was appropriate when it was relatively tricky to make sure you always did the right amount of clean-up at the end of a function in C, for example... but it's not really necessary in C#.
Personally I think it's appropriate to return as soon as you know that you've done all the work you really want to in a method. Use try/finally or using statements to perform any extra "clean up however I exit" work.
yes return gets you out of the method; if you have a finally block and you call return from the try block, the finally block is executed anyway.
Yes, the return statement ends the method.
Yes, the return will exit you out of the code. It's generally good practice as the very first step in a function to verify that the parameters that were passed in are what you think they are and exit (via the return or throwing an exception) so that you don't do any unnecessary processing only to have to abort later in the function.
Yes, your assumptions is correct.
For some background, learn about duality.
Yes, it is exactly the same, you can read the MSDN documentation about the keyword return to fully understand how it works : http://msdn.microsoft.com/en-us/library/1h3swy84.aspx
As to decide which way is better : both are good, but the second version makes it more readable because then your whole code isn't inside an if block. This way, you can see what the condition does really easily instead of reading the whole code of the method.
Indeed the return gets you out of the method, so it is equivalent to the first way you used. Which way is better depends on your code, although generally I would prefer the second version.
Looking at the revised code, the second one is the way to go. While being functionally equivalent, think about the case where you passed in 4 different variables to a function that you want to check. Instead of having a do a nasty 4 level if statement with {'s everywhere, the second method allows you to clean up the appearance of the code and not add unnecessary levels of brackets. If you're writing in C/C++, you can even make this a macro such as VERYIFY_NOT_NULL(x) and make the code nice and neat.
Readable/maintainable code trumps nano-seconds of performance 99% of the time.
When using extremely short-lived objects that I only need to call one method on, I'm inclined to chain the method call directly to new. A very common example of this is something like the following:
string noNewlines = new Regex("\\n+").Replace(" ", oldString);
The point here is that I have no need for the Regex object after I've done the one replacement, and I like to be able to express this as a one-liner. Is there any non-obvious problem with this idiom? Some of my coworkers have expressed discomfort with it, but without anything that seemed to be like a good reason.
(I've marked this as both C# and Java, since the above idiom is common and usable in both languages.)
This particular pattern is fine -- I use it myself on occasion.
But I would not use this pattern as you have in your example. There are two alternate approaches that are better.
Better approach: Use the static method Regex.Replace(string,string,string). There is no reason to obfuscate your meaning with the new-style syntax when a static method is available that does the same thing.
Best approach: If you use the same static (not dynamically-generated) Regex from the same method, and you call this method a lot, you should store the Regex object as a private static field on the class containing the method, since this avoids parsing the expression on each call to the method.
I don't see anything wrong with this; I do this quite frequently myself.
The only exception to the rule might be for debugging purposes, it's sometimes necessary to be able to see the state of the object in the debugger, which can be difficult in a one-liner like this.
If you don't need the object afterwards, I don't see a problem - I do it myself from time to time as well. However, it can be quite hard to spot, so if your coworkers are expressing discomfort, you might need to put it into a variable so there are no hard feelings on the team. Doesn't really hurt you.
You just have to be careful when you're chaining methods of objects that implement IDisposable. Doing a single-line chain doesn't really leave room for calling Dispose or the using {...} block.
For example:
DialogResult result = New SomeCfgDialog(some_data).ShowDialog();
There is no instance variable on which to call Dispose.
Then there is potential to obfuscate intent, hurt rather than improve readability and make it tougher to examine values while debugging. But those are all issues particular to the object and the situation and the number of methods chained. I don't think that there is a single reason to avoid it. Sometimes doing this will make the code more concise and readable and other times it might hurt for some of the reasons mentioned above.
As long as you're sure that the object is never needed again (or you're not creating multiple instances of an identical object), then there's no problem with it.
If the rest of your team isn't comfortable with it, though, you might want to re-think the decision. The team should set the standards and you should follow them. Be consistent. If you want to change the standard, discuss it. If they don't agree, then fall in line.
I think thats ok, and would welcome comments/reasons to the contrary. When the object is not short lived (or uses unmanaged resources - ie COM) then this practice can get you into trouble.
The issue is readability.
Putting the "chained" methods on a separate line seems to be the preferred convention with my team.
string noNewlines = new Regex("\\n+")
.Replace(" ", oldString);
One reason to avoid this style is that your coworkers might want to inspect the object in a debug mode. If you compound the similar instantiation the readability goes down a lot. For example :
String val = new Object1("Hello").doSomething(new Object2("interesting").withThis("input"));
Generally I prefer using a static method for the specific example you have mentioned.
The only potential problem I could see is - if, for some reason, new Regex were NULL because it was not instantiated correctly, you would get a Null Pointer Exception. However, I highly doubt that since Regex is always defined...
If you don't care about the object you invoke the method on, that's a sign that the method should probably be static.
In C#, I'd probably write an extension method to wrap the regex, so that I could write
string noNewlines = oldString.RemoveNewlines();
The extension method would look something like
using System.Text.RegularExpressions;
namespace Extensions
{
static class SystemStringExtensions
{
public static string RemoveNewlines(this string inputString)
{
// replace newline characters with spaces
return Regex.Replace(inputString, "\\n+", " ");
}
}
}
I find this much easier to read than your original example. It's also quite reusable, as stripping newline characters is one of the more common activities.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 months ago.
Improve this question
Background
In a C# command-line app I'm writing, several of the parameters have "yes" and "no" as the possible values.
I am storing their input using the Enum type shown below.
enum YesNo
{
Yes,
No
}
Which is fine - the code works. No problem there.
NOTE: Yes, I could store these as bool (that's how it used to work). My design choice is to be explicit about the Yes/No choice made by the user because they will see this printed in other contexts and I'd like it to be more obvious what the choice was.
My Question
It just seems odd to have an enum called "YesNo" - what are some suggestions for better names for an enum for "yes" and "no" values.
So Finally
I asked this question relatively early in StackOverflow's life. It wasn't fake question - I really did have this situation. I just thought it would be nice to use it see what the community would do. Because it is, I admit a somewhat odd question.
First, thanks to all who spent the time replying. I'm trying to pay that back with a thoughtful conclusion.
Comments on the answers
switching to bool. I understand your motivation, but I feel I need to point out that having a binary choice (and by that I mean a choice between any two values - alive/dead, married/unmarried, etc.) is not the same as boolean choice between true and false. We find as programmers switching between yes/no and true/false easy - fair enough. Had my choice in this case been for example "Democrat" or "Replication"" (contrived example, I know) then you can see possibilities for confusion or at least awkwardness. I do think the bool option is valid in this case, but less so in other binary choices.
localization - great point. In my specific case it didn't matter - this was not and is never going to be localized, but for other situations it is something to consider.
more than three options - In fact, later on I had to add a third value called to represent the valid (in my application) condition of a user specifically not making the choice.
There were a lot of good comments, thank you all!
You say you don't want to use bool because it will be printed out for the user to see amongst other contents. That suggests the problem isn't in storage but in display. By all means present true/false as Yes/No, but there's no need to create a whole new type for it IMO.
EDIT: In addition to suggesting you don't use an enum in the first place, I'd strongly recommend that if you do use an enum, you change the order or use explicit values. Having Yes=0, No=1 will be really confusing if you ever end up seeing the values as integers.
I'd suggest you use a name that indicates the Value which is set to Yes or No.
E.G.
public enum Married
{
YES,
NO
}
I would be confused to see an enum used for a boolean. You say that:
NOTE: Yes, I could store these as bool (that's how it used to work). My design choice
is to be explicit about the Yes/No choice made by the user because they will see this
printed in other contents and I'd like it to be more obvious what the choice was.
I fail to see how a "Yes" or "No" is any more "explicit" than a true or false.
ResponseEnum or EResponse or UserResponse depending on your conventions.
I wouldn't limit yourself to only Yes or No as in the future you may want to add functionality that required an Unsure response also.
I'd want to call it:
enum Boolean
{
Yes,
No
}
No, wait, there is already a built in boolean type you can use.
If your only reason for using an enum here is because there is a convenient conversion to/from a string that you want to show the user, then you are going to get bitten very badly down the track as you do more sophisticated things. A separation of model from view will server you well. Read up on MVC and/or MVVM patterns.
I might also suggest that a simple boolean with some custom attributes that define the display strings to use in place of "true" and "false" might suffice here. You can then write your own to/from string methods that look for your custom attributes.
YesNo
Choice
BinaryChoice
Or just use a boolean.
I would not use a enum at all, just roll your own typeconverter and use booleans.
I think YesNo is just fine. Consider things like "MB_OK" and "MB_YESNO" ... I know it's not a type but anything that's self-explanatory should be fine.
Is there any possibility for having option other than yes/no.For just 2 option stick with boolean.Try to modify the display area alone
(Humour - please don't take this seriously...)
I'm surprised no-one's suggested this yet:
public enum UserWtf
{
No,
Yes,
FileNotFound
}
I guess there is a problem with displaying bool values.
It is better to create simple wrapper that stores boolean allowing you to display them as Yes/No or True/False.
I read your updated explanation, but I still feel this is a poor choice. Booleans exist exactly for this purpose. It is your responsibility to ensure that when "they will see this printed in other contents" appropriate text is outputted. This could be as simple as:
Console.WriteLine(_("Using Foo: ") + (useFoo ? _("Yes") : _("No")));
while still having full support for localization. useFoo is of course a parameter telling the function whether it is using foo. :)
The _ is short for the gettext function (http://www.gnu.org/software/gettext/), which is available for C# (http://www.gnu.org/software/automake/manual/gettext/C_0023.html).
EUserAction ?
You described it as some user action. You could also be more specific, though. The name allows for some additional choices in the future. (The name should be what the choice is for, not what the choices are)
However, for your other, subtle question:
because they will see this printed in other contexts and I'd like it to be more obvious what the choice was.
it shouldn't really matter what the user sees. The data model can be very different from what you present to the user. A bool would have sufficed. Is there a possibility for additional actions in the future?
When I have need something like this, I use the word Flag, as in Flag.Yes, MarriedFlag.No, etc.
Example of when this is useful: you know there are only Yes and No values today but you suspect there might be additional values (like Maybe) in the future.
I don't see the point of this enum unless there were some other values besides Yes and No. That's just a bool. And making an enum just so you don't have to type out yes or no seems kind of silly.
Use a bool, combined with bool.TrueString and bool.FalseString for display purposes.
I use OptionalBinaryFilter for:
Yes, No, All
But if you have only Yes and No, seem more suitable use of Boolean in a member.
enum Confirmation {
Yes = 'yes',
No = 'no'
}
or
enum Confirmation {
Yes = '401efbce-ad94-41cf-94cf-2313611e94c2',
No = '8f836daa-40fb-46ec-9708-28a40bc6fead'
}