Help me find a name for this method [closed] - c#

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

Related

The Best way to create methods that receives parameter [closed]

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.

Not sure where to ask, which 1 is actually better? [closed]

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.
Customer cust = new Customer();
cust.RecId = lblRecId.Text;
cust.CustCd = txtCustCd.Text;
cust.CustName = txtCustName.Text;
cust.Save();
OR
cust.SaveRecord(lblRecId.Text , txtCustCd.Text, txtCustName.Text)
both doing the same job, but which 1 is actually better? I and lead actually have an argue on this, I using the top method, as I can freely assign the value in any order, but he insist that the bottom 1 is better? no idea what actually to search, any 1 mind to give me some guideline on this
First one is much better approach. but it's a personal view.
Save should persist the current state of object. and state can be updated in other parts of program.
However having an overload Save is also not bad idea. but as the no. of fields increase the latter version becomes bulky and un-maintainable.
The first approach is great if you already have all the data for a customer in a customer class.
If you do not have a customer class with data the second approach is better.
We often use the first approach, but then we also have some static methods to retrieve the customer with a specific key e.g.:
// A static method in Customer class.
public static Customer Get(string key)
{
Customer customer;
FCustomers.TryGetValue(key, out customer);
return customer;
}
This comes with a static constructor that loads all customers into memory and methods to Create, Save and Delete customers from database as well.
This is ofcause only relevant for data that is needed all the time, I don't think that customer is that kind of data.

What is the preferred coding style for checking if something is false? [closed]

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.
Given the following:
bool isCorrect = theAnswer == 42;
Which is the preferred way of testing false boolean logic in C# (programming in general)?
if (!isCorrect)
// throw exception
or
if (isCorrect == false)
// throw exception
The reason I ask is because one of our senior developers at work suggests we should always use the latter approach as it enhances readability and ensures other developers can clearly see the false check; an exclamation mark is easy to miss. I much prefer the former as it's more concise and readable enough to me.
I understand that this may be a subjective issue so was wondering if there was a concrete preference mentioned in any coding style.
I have seen production code from senior developers containing such code:
if (isCorrect.ToString().Length == 5)
But I'm still using:
if (!isCorrect)
Use what you think is more readable for you, there is no statistics among all developers))
The preferred way (I'm not sure if it actually is a best practice, but it definitely should be) is to not test false
// First question: "Is the answer correct ?"
bool isCorrect = theAnswer == 42;
// Second question: "What if it is ?"
if (isCorrect)
{
}
else //Third question: "What if it isn't ?"
{
}
It's not only more logical, but saves you from scrolling around to skip error handling if you need to follow the actual flow of your code.
Also, it's worth pointing out for completeness that boolean names should always be positive: think isCorrect VS isNotWrong ... isPositive VS isNotNegative ... much easier not only to read but to understand too.
Given the following:
bool isCorrect = theAnswer == 42;
The clearest way to check the inverse is (IMHO!):
bool isWrong = !isCorrect;
...
if (isWrong)
// throw exception
You are right that (!condition) is more concise.
The senior dev is right that (condition == false) is more 'visible' (or readable if you like).
Since it just boils down to preference, you should just do what the senior dev suggests and keep everything consistent whether you like it or not. When you are the senior dev you can go back and change everything.

Have I reached the Refactoring Tipping Point? [closed]

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.

Validation naming conventions? C# [closed]

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

Categories

Resources