As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
Very simple question, but I want to start using a consistent naming convention for validation methods and I can't think of the best way!
Do people tend to use IsDataValid() style? or are there any others that are more descriptive and meaningful?
Cheers
It depends what your validation method does.
If it returns a Boolean, then probably starting with Is and ending with Valid is a good place to start. Using is for Boolean calls generally leads to readable code in if statements.
If your validation method throws an exception, then I'd usually start the method name with something like Check instead.
However, also worth considering (as methods should usually use verbs) is beginning the method name with Validate. The Is style is generally more applicable to properties.
As with anything involving naming conventions, there's no such thing as a right answer, but there's a lot of common problems with validation methods that lend themselves towards a certain approach, namely:
If everything is OK, you typically only need the boolean status of the validation.
If there are problems, you usually need to know details about the problem.
You usually want objects to have similar approaches to validation.
One approach I've found to be useful is to have a seperate validator class for each model object I want to validate that implements a common IValidator interface, usually with the following methods:
A constructor that takes the object to be validated in.
A property named IsValid(), that validates the object, returns a boolean, but stores specific errors in private variables so validation doesn't need to be recalculated when you do want the errors.
A property named ErrorMessages, that validates the object (if it hasn't been validated yet), and returns a list of errors with the object.
This allows a pretty natural usage within your business logic:
BusinessObject obj = new BusinessObject();
// populate fields
BusinessObjectValidator objValidator = obj.GetValidator();
if (objValidator.IsValid) {
obj.Save();
} else {
foreach (var errorMessage in objValidator.ErrorMessages) {
// output message
}
}
Do people tend to use IsDataValid() style?
I typically use the 'Is' MethodName style when the method returns a single Boolean value. It is perfectly acceptable in terms of naming. A lot of times data validation is done within the Set of a Property rather than a method so in this case you don't need to change the property name to indicate it validates the data set on it.
Here is a link that gives some general naming guidlines which you might find interesting as well:
Naming Guidelines:
http://msdn.microsoft.com/en-us/library/xzf533w0(v=vs.71).aspx
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'd like to know wich way is the best one to create methods that receives a low ammount of parameters like 1 or 2.
First One: Passing an entity class object as parameter.
MyClass entity = new MyClass();
BDClass bd = new BDClass();
entity.Name = "Alan";
bd.InsertName(entity);
public void InsertName(MyClass entity)
{
///A simple Insert/Select
}
Second One: Even programming on OO, use variables as parameter, instead of the entity class.
BDClass bd = new BDClass();
string name = "Alan";
bd.InsertName(name);
public void InsertName(string name)
{
///A simple Insert/Select
}
I'd like to know wich one is the best considering performance and good practice of programming. Or it depends of the situation ? I Mean, I guess it's better to use entity class as parameter only when it's a big amount of class, and the variable with low quantity of parameter.
I know its nothing to do with codes itselves, but I just want to learn wich one is the Correctly way to programm
There's no big differences and a correct answer. Since you can write it in the 2nd form, and the method name is InsertName, I prefer the 2nd one.
Why? First, it needs only a name(string), otherwise only one parameter is not enough. Second, you can pass any name to it no matter it comes from MyClass or anywhere else.
If you really need to pass the MyClass object with a given type, it must be the case that you need more than just a name from it, where you can't replace with only passing a name string. And in that case, MyClass may be a dependency of BDClass.
It depends on situation which you are handling. If your about to add whole object of entity class and your method is written in some c# Library project and you want to use that method in other project where your collecting whole information about that object of Entity Than first method approach suits you... But at the end it is completely up to you what you want to do.
It depends.
If your method is processing an (data/domain) entity, is should not even be a class; but rather an interface - which you will feed it to the method my means of a IoC framework.
If it needs to frequently pass it to other code blocks, in form of another class; then perhaps it's easier to use an entity class, which will be mapped to the result type.
It it's a pure function which is just calculating something (and it's algorithm does not change and you do not use something like a Strategy Pattern) then you can use just named parameters.
These are not ALL possible situations. These are just (IMHO) good ways of performing this task.
And I always start with simple named arguments! Avoid premature optimization! Wait for patterns in your code to emerge.
Both are correct, when correctness is defined as valid in C#.
Depending on use, one may pick one pattern or the other. There is no cookie cutter approach, and you won't see any performance differences.
For instance, if you wanted to validate an existing object of type MyClass then you would expect a whole item. The same goes for passing in objects with lots of properties, or when the number of parameters needed will increase over time.
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'm developing software in C# and I remember that I read an article with the following statement:
Design the methods of a class like this:
use a void method with argument(s) in order to change state of the class instance. method will do some changes on the data of the class
use return value with a method without any arguments in order to retrieve data from the class
I can't find the article anymore and I'm wondering about the benefits and drawbacks of such a convention in order to improve the quality and maintainability of the code I'm writing.
My question is: do you know any references/articles for this question? Does it make sense to follow these statements?
C# has properties which I think makes these suggestions less practical. The big point to take away is that data inside a class should be encapsulated (the outside world cannot access it directly) and abstracted (the details are hidden). This is one of the primary purposes of a class. For this reason I think this advice would make more sense for a language like C++ that doesn't have properties.
One of the problems though is that people would write a class with private fields then have to write a getter method and a setter method for each private field and this results in redundant boiler plate code. Properties help streamline this strategy while still maintaining encapsulation and abstraction. For example,
UserInfo user = new UserInfo();
user.Username = "foo";
Console.WriteLine(user.Password);
In the above example I have set the username to foo and retreived the password for the user. Exactly HOW I set and retreived the information is hidden. It may be saved in an .xml file right now but later I decide to change to saving it in a database or directly in memory. The outside world that uses this classes is never the wiser. This is one of the many beauties of OOP.
The two bullets in your question can respond to a getter and a setter of a property. If I want to retrieve data from my class without any arguments it makes more sense to have a property. Likewise if I want to change the state of my object I can use a setter property. I can perform validation on the input, make it thread-safe, add logging, everything I could do with a method that takes a single argument.
I suppose the bullet points are referring to Command Query Responsibility Separation. In practice you could still need to pass some argument to a return method in order to filter the results for instance. Using voids to change the state is sensible, and also making your return methods so that they don't change the state is good too, but really the number of arguments you pass in is not decided by whether you have a getter or setter method. It is really a factor of what a method needs to know to get it's job done.
The amount of arguments that you pass in should be kept to a minimum however. If you have more than one argument you should really consider if your method is doing more than one thing. I suppose the message is, "Have your methods do one thing and do it well". You can get loads of information about this from Uncle Bob, Bob Martin's Clean Coders series is a great source of information on this subject.
Having a get method that returns a value and doesn't take any parameters makes it very clear what your method is doing.
GetFirstName() is clearer about what it's doing than GetName(bool first) or GetFirstName(User user).
Clarity is key. The method signature may seem like it's fairly clear, but when you read GetName(false) in the code somewhere then it's going to cause some confusion.
These types of getter methods are also not really my standard in C# where I am more likely to use a property for a getter of that nature.
When it comes to void methods with arguments, then this mainly comes into play for setters where you are setting the state of something in the object. Again, easily handled with properties in C#.
Most of the time these guidelines are there to help keep your code testable.
Methods that have fewer parameters are more easily tested -- assuming you are injecting dependencies into the method signature and not creating new objects in the method itself, which can be difficult to mock and test.
Think of how many test cases you may need to cover if you have a method that accepts 5 parameters.
In the end, these are general guidelines that are good for testability and clarity of your code, but there are certainly times when you will find that it doesn't make sense to follow these guidelines.
As with any coding, just be aware of what you are doing and why you are doing it.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a form whose constructor I've overloaded to pass in an enumerated type and a List<int>.
Now I realize I also need to pass in another int (that doesn't belong in the List<int>).
At what point is it considered "good form" (no pun intended) to regroup and refactor and encapsulate all those parameters into a class and pass that?
Or is there a better way (that doesn't require Houdini-esque sleight of hand)?
You could expose the fields as public properties and use the following syntax:
var myinstance = new MyType
{
Prop1 = val1,
Prop2 = val2,
Prop3 = val3
};
This saves you needing to alter the constructor time after time. I regards to your "when is it best to..." question, I personally go with if I expect it to grow beyond 2 or three (now or in the future) I will create a parameters class. This may be open to quite a bit of debate though!
Things to consider before you up and make a new object for this function
How often are you using this function?
Do you have duplicate code? Will creating this class help remove duplicate code?
Does it increase efficiency (code performance and maintenance)?
Which is faster? Customers don't care about a lot of this.
Adding another constructor with more parameters isn't going against any practice, though if you have a crap load of constructors that call themselves in weird orders I'd suggest rethinking it...
If your application requires it, add it. Having:
public FormConstructor(List<int> someInts, MyEnumThing anEnumYay, int anotherInt)
Isn't bad - except for my naming....
My oppinion? I'd add the Int if I didn't see any potential gains for creating a class.
Creating a class "solely because" you don't want many input parameters is the wrong reason to create said class.
I guess it all depends on how much refactoring you'll have to do elsewhere as a result of the change. If you push everything into the new class, will other parts of the application stop working as a result? How many bugs might this introduce? IMO three or four parameters is fine, but once I start pushing 5 or more into the signature, I tend to create a class to handle the job.
Quotes and such can become a factor, because, if you have to get the job done in an hour, but it will take you three to create a class, update other bits of code, and test, you might just have to add a new parameter and revisit it later.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I want to give a meaningfull name for method which i am not able to find enough good. Method should to lock and unlock user by parameter .
Candidates signs are:
void LockUser(int userid,bool #lock)
void LockUser(int userid,bool #locking)
void LockOrUnlockUser(int userid,bool #lock)
void LockUser(int userid);
void UnlockUser(int userid);
problem at first and second is method name says lockuser but it is also able to unlock user by lock parameter so this is confusing. LockOrUnlock method name is more meaningfull but i couldn't find better parameter name for it. It can be shouldLock ?
Another apporach is seperate them to different methods and this provide more meaningfull names for methods but i want to just use one method instead of both.
Waiting suggestions.
Martin Fowler suggests using separate methods. Otherwise you implement a Flag Argument method, which he believes to be a bad design choice.
A flag argument is a kind of function argument that tells the function
to carry out a different operation depending on its value.
My general reaction to flag arguments is to avoid them. Rather than
use a flag argument, I prefer to define separate methods.
Replace bool #lock with an enum - that's arguably better design-wise. As for naming, maybe ToggleUserLock(int userID, UserLock #lock)?
"SetUserLock(int userid, bool #lock)"
"ToggleUserLock(int userid)"
How about SetUserLockStatus()
as technically you are setting the Lock/Unlock status from parameters
How about
ChangeUserLockStatus
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have two specific C# coding conventions I've been practicing with mixed feelings.
I'd be curious to hear what people think. They are:
#1. Name instances after the class it's an instance of, camelCased
#2: "Matching property names"
Here's the rationale:
#1. Name instances after the class it's an instance of, camelCased
I use this as my default setting for naming convention. Of course, there are exceptions. But used consistently it dramatically improves code clarity and maintainability. The code looks like this:
var dataConnection = new DataConnection();
//not: var dataConn, dbConn, sqlConn, myDbPickOfTheDay etc.
FileInfo fileInfo = new FileInfo();
Timer timer = new Timer();
//etc.
I'm at the point where code like this causes me physical pain:
DataConnection dbConn = new DataConnection();
I can't stress enough how this convention has taken away the pain and anger of the variable name game.
This convention is in sharp contrast to attempting to name things in ways that try to indicate what the instance is doing, which amounts to trying to creatively embed the business case in code. Code has a way of getting refactored to the point where those original names are misleading at best.
To me this convention is gold. It also prevents the horrible practice of slightly tweaked variable names for the same thing.
An example of this convention in practice is:
class Person { ...
public string FirstName { get; set; }
//and then
var person = new Person();
person.FirstName = firstName; //where firstName comes from somewhere else.
Very easy to read. Very boring. Boring is good when it comes to maintaining code.
However, this convention leads me to #2:
#2 "Matching property names" ( for lack of a better title )
Here's an example:
public class ShoppingCart { ..
private Item item;
public Item Item { //<---- ?
get { return this.item; } ...
The compiler is perfectly happy with this. And, in fact, it exposes a very nice interface:
//notice how tempting it is to just say "ShoppingCart cart ... "
ShoppingCart shoppingCart = new ShoppingCart();
shoppingCart.Item = item;
Now, the alternative is to be creative -- You actually need to drum up two good variable names for Item: the public property name and the private member variable name.
How many times have you seen this and just want to retire immediately?
public class ShoppingCart { ..
private Item cartItem;
public Item ShoppingCartItem {
get { return this.cartItem; } ..
///....
ShoppingCart userShoppingCart = new ShoppingCart();
userShoppingCart.ShoppingCartItem = userSelection;
I feel strongly enough about convention #1 that I think I can live with #2.
What do you think ?
in case you were not aware and if you care , C# already has a naming standard
http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx
Also, looking at your conventions again ... here's some more suggestions.
fileInfo looks pretty next to FileInfo but it has no meaning other than it's type which I can quickly get by mousing over the type or in intellisense. I would suggest naming your variables with meaning and some context if available. remoteWebServerLog, localWebServerLog, or even localWebServerLogFileInfo if you like the type in the name.
If I can hand off any advice from coming back to code you've written 6+ mos later. You will be scratching your head trying to figure out and track down what the heck all your dbConn and fileInfo's are. What file? What db? Lots of apps have several dbs, is this dbConn to the OrdersDB or the ShoppingCartDB?
Class naming should be more descriptive. Wwould prefer ShoppingCartItem over Item. If every ListBox, DropDown etc named their collection items "Item" you'd be colliding with a lot of namespaces and would be forced to litter your code with MyNameSpace.ShoppingCart.Item.
Having said all that ... even after years of coding I still screw up and don't follow the rules 100% of the time. I might have even used FileInfo fi = ... but that is why I love my Resharper "Refactor->Rename" command and I use it often.
Convention #1 can become confusing. If you were to have two FileInfo objects in the same method-- say a Source and a Target-- you'd need to deviate from the convention in order to name the two.
Variable names should be mnemonic-- to indicate to the casual observer the intent of its use.
Perhaps you'd be happiest with a combination of the two conventions... such as sourceFileInfo and targetFileInfo, per this example.
Obviously, you can't name every System.String in your project string*, but for things you don't use a lot of, esp. things you only need one of, and whose function in your code is obvious from its name, these naming conventions are perfectly acceptable.
They're what I do, anyway.
I would go with a more specific name for, say, the Timer object. What's it a timer for?
But I would definitely name a DataConnection dataConnection.
*Even if "string" wasn't a keyword...
I do 1 all the time and find it very readable. I'm on the fence with 2. I find it confusing in certain situations, mainly because it's hard to distinguish the type from the property due to the identifiers being identical.
I would normally follow convention #1, although for long class names I tend to just use the initials of the class. If I am referring to more than one object of the same type then I would pre-pend the type name with a name indicating which one it is or what it’s used for.
I quite often use convention #2 if it makes sense. There is nothing worse than having something like the example you listed of cart.ShopingCartItem, the very fact that it is a property of ShoppingCart makes that part of the property name totally redundant. However I would quite likely name the class ShoppingCartItem and the property Item. Item is a little too generic a name whereas ShoppingCartItem tells you what kind of item you are working with.
I follow convention 1 all the time. Although, I do add an additional qualifier if there are two objects side by side.
But having said that, making this convention mandatory may be problematic:
In a certain context cart may be a good enough name for a ShoppingCart object (if, for example, there is no other 'cart' in the same function to be confused with).
Sometimes the convention may completely obscure the purpose of the declared object. For example Window scoreBoard = new Window() says that we have an object which is indeed a Window but is being used as a scoreBoard. Very expressive. But following convention 1 you'd have to write Window window = new Window() which totally hides the intention behind this window.
So I'd say use this naming idea everywhere except when it hinders meaning or appears unreasonably demanding.
About convention 2, I totally agree. Keeping property names succinct and letting the object name complete the full meaning of its invocation is an elegant thing. It works perfectly with well named objects. So there's little reason to be shy of using it.
I strongly dislike the notion of having multiple identifiers in scope which differ only in their usage of upper/lower case; if I had my druthers, code which used an identifier would be required to use the same combination of upper/lowercase letters as its declaration, but code would neither be allowed to declare two identifiers in the same scope which differ only by case, nor access any identifier which would--except for case--match an identifier in an inner scope. Although no language I know of (certainly not VB nor C#) enforces such rules, code written in compliance with such rules could be freely portable between case-sensitive and non-case-sensitive languages without having to rename identifiers.
Consequently, I dislike the pattern #2. CLS compliance requires that any identifiers of that style be restricted to private or internal scope. Since both vb.net and C# allow names to start with underscores, if a property is named Trait, I see no reason to favor trait over _trait. Use of the latter name would clearly distinguish cases when the programmer wanted to write to the backing variable from those where his finger slipped on the shift key.
As for pattern #1, in cases where the whole purpose of a type or method resolves around a single encapsulated object of some particular type, I prefer to prefix fields with my or parameters with the. Even in cases where the compiler would allow the same names to be used for instance members and parameters, using distinct prefixes avoids the possibility of accidentally using one where the other is required.