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 9 years ago.
Improve this question
I often experience difficulties in designation of my methods. For instance, now I have a static method which compares two hashes, and I stuck with its name. HashesEqual(string h1, string h2)? AreHashesEqual(string h1, string h2)? Your better version? This is generic question -- I have a lot of such stuff. Is there any authoritative source where I can read about naming conventions?
From Names of Type Members on MSDN:
Do give methods names that are verbs or verb phrases. Typically methods act on data, so using a verb to describe the action of the method makes it easier for developers to understand what the method does. When defining the action performed by the method, be careful to select a name that provides clarity from the developer's perspective. Do not select a verb that describes how the method does what it does; in other words, do not use implementation details for your method name.
Do name Boolean properties with an affirmative phrase (CanSeek instead of CantSeek). Optionally, you can also prefix Boolean properties with Is, Can, or Has, but only where it adds value.
I think others will agree that any naming convention is good as long as it makes sense and you use it consistently.
Alternatively, consider creating an extension method for the string class that provides this functionality. Then you can simply do:
var equal = h1.EqualsHash(h2); // or similar, based on the naming you choose
Or write a custom Hash class that keeps the hashed values internally, and override/overload its Equals method and ==/!= operator(s), giving way to this:
var h1 = new Hash("string1");
var h2 = new Hash("string2");
var equal = h1 == h2;
// or
var equal = h1.Equals(h2);
Or make your utility class stand alone (e.g. HashUtil or something), and keep the word "hash" out of its method(s) entirely:
var equal = HashUtil.AreEqual(h1, h2);
Also see: Guidelines for Names
I'd suggest all developers read the .NET Design Gudelines (linked is the specific section on type members). In your instance, because the return type is also a boolean value, I'd recommend you try something like:
IsHashEqual(string testHash)
The only method name suggestion provided by the .Net Framework Guidelines is that methods should be
DO give methods names that are verbs or verb phrases
I think that Are do qualifies as "verb phrases" and would work here.
In this case though you aren't defining something new but rather a specific form of a well established pattern: Equals. Given that my inclination would be to prefix the function with Equals so that it shows up close to Equals in features like Intellisense, Search, etc ...
EqualHashes(string p1, string p2)
Related
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 3 years ago.
Improve this question
With conventional I mean i.e. what the standards or most used versions are.
The int i are well known, and in many cases string str or the even shorter string s, as a generic naming of variables. What are the conventional naming schemes for the remaining C# built-in types?
bool
byte
sbyte
char
decimal
double
float
int
uint
long
ulong
object
short
ushort
string
Edit:
As many people here won't answer without a background reasoning; the reason for not naming these into length, name, age etc. is because it lays in a library class to provide functionality to many projects where all the variables can be assigned to different things based on the use case.
Compare this to the new List<int>().Add(int i); (I know it's written as T item), but here I need to use multiple types in the same method, and item1, item2, item3 etc. won't make the cut.
Appart from for loops where i,j,k are admitted, I would strongly advise not to use short names. Variable are understood by the compiler whatever name you choose. However humans need a precise meaning to understand and work with your code.
Take a look at:
int i;
bool b;
versus:
int weight;
bool isAdult;
Doest it make any difference?
If you plan on following a standard convention, Follow the Microsoft Naming Convention Here, otherwise, you may stick to whatever convention you/your team is familiar/comfortable with.
As for the abbreviation :
DO NOT use abbreviations or contractions as part of identifier
names.
For example, use GetWindow rather than GetWin
Basically its better to:
consider using names based on a parameter/field’s meaning rather
than it’s type.
Here is the general Naming Convention which explains everything you need.
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 years ago.
Improve this question
I have a method set in an POCO entity that set the basic property and the navigation property. In some cases, I don't need to verify some conditions, but in another cases I need to verify to ensure that the information is coherent in the database, but this verification makes me to get extra data from database.
So by the moment I have my basic method that is this:
public void setMyProperty(MyType paramProperty)
{
this.Property = paramProperty;
this.IDProperty = paramProperty.IDPorperty;
paramProperty.MyNavigationCollection.Add(this);
}
For the method that verifies the data, I guess that I have two options.
First one, I can create a new method for business logic, somthing like that:
public void setPropertyBi(MyType paramProperty)
{
//check conditons
//If all OK then
this.setPorperty(paramProperty);
}
But I have another option, use only one method, not the basic method and the other for business checks. Something like that:
public void setProperty(MyType paramType, bool paramDoChecks)
{
if(paramDoChecks)
{
//Do checks
}
//if all OK
this.Property = paramProperty;
this.IDProperty = paramProperty.IDPorperty;
paramProperty.MyNavigationCollection.Add(this);
}
Which is the recommended option? or there are another ways?
People here seem to prefer the flag, I personally think it is horrible.
You want to achieve two different things: just set a property; validate AND set a property. IMHO it should be two separated methods.
Just don´t write two different Methods if it´s one equaly functionality. Just add a Parameter which makes the validation-difference like you´ve written last.
But don´t forget to enter the behaviour if validation failed. separate it well.
You could add a Boolean ValidationRequiredproperty to MyType which you can set before the call to setMyProperty().
I prefer to have two methods: CanSetProperty and SetProperty.
CanSetProperty: just check the condition, does not change anything in the parameter.
SetProperty: will modify the paramenter.
I think this code is a good candidate to follow the Command Query Separation Pattern
The fundamental idea is that we should divide an object's methods into
two sharply separated categories:
Queries: Return a result and do not change the observable state of the
system (are free of side effects).
Commands: Change the state of a
system but do not return a value.
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 6 years ago.
Improve this question
I have a class/object called "User" that has about a dozen properties (eg: UserGUID, UserName, etc.). It has a constructor, static methods, couple other helpers/support methods, etc.
The website has hundreds of functions/methods where 2+ parameters come from the User object. For example:
public string HelloWorld(Guid userGUID, Guid accountGUID, bool somethingElse)
{
//Do something
}
I really want to pass in the User object itself to make the call cleaner and not have to keep adding parameters everytime I need a new value from the User object. Like this:
public string HelloWorld(User user)
{
//Do something
Guid userGUID = user.UserGUID;
}
So my question is, at what point is passing in the object good/bad vs passing in several parameters? Does it depend on the size of the object? How would I determine what's "too big" vs "OK"? Is it the number of parameters? How many params is too many?
You should think about what the method is supposed to do . Why does the method exist?
The semantic of the method will determine its arguments. So, for example, if HelloWord is supposed to print some stuff out, like a userId, and something else, then the signature should contain userId and something else as arguments.
On the other hand, if HelloWord is supposed to print out some information about a User, then the method signature should have the object User as a parameter.
It all depends on the method semantic.
In Clean Code, Robert Martin says to prefer 0 arguments, 1 or 2 arguments are acceptable and 3 is too many.
In my opinion as long as you're in the same process I think passing the object is preferable to passing arguments. You wouldn't want to send (or receive) more than is needed to another process (say a web service).
I highly recommend Clean Code, it's a good read and has a lot to say about structure.
There is a very important difference here, and this is not an opinion.
I have a class/object called "User" that has about a dozen properties
Given the above situation, if you were then to allow (User user) as opposed to only allowing (Guid userGUID, Guid accountGUID, bool somethingElse) you have just introduced a security hole.
Clients would be able to send more data than they were supposed to have access to by posting the extra names of the User class. For example, it is possible for a client to alter foreign navigation property keys in this fashion if you make the entire class available (and it had foreign relations). It is also possible for clients to alter timestamps, and even logical separations depending on information stored in that class.
Preventing this type of breach is easy to do if you allow the entire class to be accepted, you just need to then manually inspect each property to make sure it wasn't erroneously sent, or screen it by only selecting the subset of information sent. Either way, this is a bad idea.
While there may be no difference in using a User class with the same properties as the 3 shown, allowing the model binding of a User class which has a larger set than the 3 can be problematic if left unchecked.
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 8 years ago.
Improve this question
Given web service method:
public void FindSomeEntities(int? Id, string param1, int? param2, ...)
Refactored:
public void FindSomeEntities(SelectionParameters selectionParameters)
class SelectionParameters
{
public int? Id;
public string param1;
public int? param2
...
}
Pros:
too many parameters in original web service method reduced to the
only one
if there is need to change we won't have to change the
interface of the method - only the definition of SelectionParameters
Cons:
class SelectionParameters hasn't any business value - it's used only
as helper class and it's used in a single method. As a result we'll
have many methods with 1 parameters and plenty of one-off classes
Actually the interface IS changed, we just push these changes a bit
deeper.
This refactoring is called Introduce Parameter Object. It is likely to be a good idea if the parameters are naturally related to each other, and especially if they're frequently used together as parameter lists to multiple methods.
I'm not sure there is much value in this kind of refactoring because as you say, the number of supporting classes will/could be a pain to maintain and serve no other purpose.
If the parameters have distinct purposes, such as in your example 'ID' then I would think it would be sensible to keep them separate so as to make it easy to identify them and what you want to do with them in the method body.
If however your params are just a collection of values which perform similar/the same functions in the method body, you could look at using the params keyword and defining your method like this:
public void FindSomeEnteties(params object[] theParameters)
It depends whether you want to have to dig through an array to pull out index 0 and treat it as the ID, etc etc, or whether your method simply wants to do the same thing to all the parameters passed.
If there is any reason to believe that the same (sub)set of parameters is shared by other web services, this is reasonable.
Whether you do it not, you have a defacto struct as the argument list anyway. This observation is realized in our PARLANSE programming language, which has always a single argument to function, named '?' (sort of like "self" in OO ). That argument has a type; it can be a scalar or complex variable (int or string), or it can be struct. Normally one defines a struct by a struct declaration; in PARLANSE, writing what appears to be multiple arguments implicitly defines a struct. In those cases where the argument list is passed to a child function, one can simply call that child function on '?' and the entire argument list is passed.
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 6 years ago.
Improve this question
The problems are:
GUI libraries like to use ToString as a default representation for classes. There it needs to be localized.
ToString is used for logging. There it should provide programming related information, is not translated and includes internal states like surrogate keys and enum values.
ToString is used by many string operations which take objects as arguments, for instance String.Format, when writing to streams. Depending on the context you expect something different.
ToString is too limited if there are many different representations of the same object, eg. a long and a short form.
Because of the different usages, there are many different kinds of implementation. So they are too unreliable to be really useful.
How should ToString be implemented to be useful? When should ToString be used, when should it be avoided?
The .NET Framework documentation says:
This method returns a human-readable
string that is culture-sensitive.
There is a similar question, but not the same.
It seems you have great expectations from a tiny little method :) As far as I know it's not a good idea to use a general method in so many different contexts specially when its behavior can differ from class to class.
Here is my suggestions:
1.Do not let GUI libraries use ToString() of your objects.Instead use more meaningful properties (Almost all controls can be customized to show other properties than ToString)
for example use DisplayMember.
2.When getting some information about an object (for logging or other usages) let somebody decide (another object or the object itself)what should be provided and how it should be displayed.(A strategy pattern may come in handy)
Here is a nice article which explains Overriding System.Object.ToString() and Implementing IFormattable
It depends on the indended usage of your class.
Many classes don't have a natural string representation (i.e. a Form object). Then I would implement ToString as an informative method (Form text, size, and so on) useful when debugging.
If the class is meant to give information to the user then I would implement ToString as a default representation of the value. If you have a Vector object for instance, then ToString might return the vector as an X and Y coordinate. Here I would also add alternative methods if there are other ways to describe the class. So for the Vector I might add a method that returns a description as an angle and a lenght.
For debugging purposes you may also want to add the DebuggerDisplay attribute to your class. This tells how to display the class in the debugger, but it doesn't affect the string representation.
You may also want to consider making the value returned by ToString to be parseable so that you can create an object from a string representation. Like you can do with the Int32.Parse method.
Another wrinkle to consider is the tight integration between ToString and Visual Studio's debugger. The Watch window displays the result of ToString as the value of the expression, so if your method performs any lazy-loading, has any side-effects, or takes a long time, then you may see strange behavior or the debugger may appear to hang. Granted, these qualities are not the mark of a well designed ToString method, but they happen (e.g. a naive "fetch the translation from the database" implementation).
Consequently, I consider the default ToString method (without parameters) to be a Visual Studio debugging hook -- with the implication that it should not generally be overloaded for use by the program outside of a debugging context.
While those in the know leverage the debugging attributes (DebuggerTypeProxyAttribute, DebuggerDisplayAttribute, DebuggerBrowsableAttribute) to customize the debugger, many (including myself) generally consider the default output as generated by ToString and displayed in the Watch windows to be good enough.
I understand that this is a rather strict perspective -- writing off ToString as a debugger hook -- but I find that implementing IFormattable seems to be the more reliable and extensible route.
Personally, I don't implement ToString that often. In many cases, it wouldn't make a whole lot of sense, since a type's main role may be to define behavior, not data. In other cases, it simply doesn't matter because no clients ever need it.
In any case, here are some cases where it makes sense (not an exhaustive list):
If the result of ToString could conceivable be parsed back into an instance of the type without data loss.
When the type has a simple (i.e. not complex) value.
When the main purpose of the type is to format data into text.
I don't agree that there is a conflict between the usage scenarios that you list. When display is the main purpose, ToString should provide a user-friendly text, but for logging (or rather, as you describe it, for tracing) I would say that you shouldn't be tracing a UI-specific element in any case, but rather an object whose purpose is to write detailed trace data.
So there is no conflict because it should not be the same type according to the Single Responsibility Principle.
Remember that you can always overload the ToString method if you need more control.