Have I reached the Refactoring Tipping Point? [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 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.

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.

Examples of undefined behavior in languages other than C and 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 10 years ago.
It strikes me as a bit odd that I have heard of loads of undefined behavior examples from C and C++ but not from other Languages, where I also know that C and C++ are used in many situations where reliability is paramount. A search for 'undefined behavior' here on SO yields almost exclusively C and C++ results.
In a course I'm teaching I would like to also give some examples of weird gotchas or undefined behavior from other major languages. Can someone give a few concrete examples similar to int i; if(--i == i++){...} which lead to undefined behavior in other languages?
For example I understand if(--i == i++){...} is undefined in c++ but defined in c# because of extra sequence points as described here Is (--i == i++) an Undefined Behavior?. I want examples of undefined behavior in other languages which are not unforced errors like forgetting to initialize a variable or not locking shared data.
The C and C++ language expect the programmer to do the hard work - this means there is no bounds checking, etc. The advantage of this is speed - if you know you are not going to write past the ends of your array (your algorithm forbids it), there is no need to check in every iteration. Many high level languages build in lots of safeguards - they will automatically assign variables when they are first declared, expand an array if you assign outside the current bounds, keep track of the length of a string for you, ...
This can lead to problems too - if you don't have to declare a variable, then a mistyped variable can lead to a hard-to-spot bug. This is why e.g. Visual Basic has the Option Explicit statement which overrides the default behavior and forces the user to declare every variable - catching many bugs along the way. The same thing (not declaring variables) can lead to unexpected scope issues - not the same thing as "undefined" behavior, but "unexpected".
In languages with "nice, easy" array manipulation - Python or Perl, for example, - you can run into an interesting (and, I think, undefined) behavior when you loop over an array whose contents you are changing:
for tup in somelist:
if determine(tup):
code_to_remove_tup
(in this example, looping over a list and removing tuples that meet certain criteria - from Remove items from a list while iterating)
When an array is either growing or shrinking during a foreach loop, all bets are off (and some interpreters will thrown an exception). Once again - it is "easy" to do the wrong thing, and get an unexpected result...

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.

Help me find a name for this method [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 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

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