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.
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.
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've been reading a bunch of blog posts espousing the virtues of the Test Data Builder Pattern. It seems like a good idea, but all of the posts are years old.
When C# introduced Object Initializes, did it make the Test Data Builder pattern obsolete?
Before Object Initializers, you would have needed the following code to initialize a person object:
Person p = new Person("John", "Doe", "555-555-1234");
At the time, having a builder would have cleaned up the code like this:
Person person = new PersonBuilder()
.WithFirstName("John")
.WithLastName("Doe")
.WithPhoneNumber("555-555-1234");
Now with object initializers, it can look like this without writing any builder methods:
Person p = new Person() {FirstName="John", LastName="Doe", Phone="555-555-1234"};
In this simple example, it would seem that the builder pattern is not needed. Am I missing something? Do people still use the builder pattern? If so, what are the benefits?
In many cases you can replace builders with object initializers.
However, there are a few cases where builders are still a good option.
Immutable objects is one example.
e.g. Jon Skeets protobuff implementation is a good example of real world builder pattern for immutable objects.
(https://codeblog.jonskeet.uk/2008/08/20/lessons-learned-from-protocol-buffers-part-1-messages-builders-and-immutability/)
Person john = new Person.Builder()
.SetFirstName("John")
.SetLastName("Doe")
.Build(); //creates an immutable person
Other cases might be to apply preset values.
eg.
Rectangle rect = RectangleBuilder.MakeSquare(10).Build();
Car car = CarBuilder.MakeVolvo().PimpIt().SetColor(Color.Red).Build();
In this case you might set multiple properties at once so you can start from a prototype of some sort and continue from there.
Take StringBuilder for example. it is still useful and required in order to build a new string
with high performance (As optimizations in the compiler will not cover all scenarios).
Same goes for other immutable objects, as was comented already.
Also, when using a builder pattern , it is easier to replace the initalized type, which give you loose coupling (for dependency injection).
It may not always be required for test purposes, but might still come in handy at times.
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.
Just wonder which approach is faster and better to use or which do you prefer
bool userHavePermission = user.Permissions.Any(x => x.UpperName == "ADMINISTRATOR");
or
foreach (Permission p in _Permissions)
{
if (p.UpperName == name.ToUpper())
return true;
}
return false;
Thanks
It's almost same code, the only difference being that with the second code snippet you're gonna get a NullReferenceException at runtime if the name variable is null because you will be calling the .ToUpper() method on a null instance. The first looks shorter, safer and more readable, it's what I would use. And to ensure that there won't be any NREs:
return user
.Permissions
.Any(x => string.Equals(x.UpperName, name, StringComparison.OrdinalIgnoreCase));
Using Any is the better approach as it is one line. It reads easier and takes up less space.
Additionally it is unclear what the Permissions object is but if it's a entity of somekind representing a database table then Any is definitely better as you only return the result of the query where the foreach is going to resolve the entire list of Permissions before the iteration begins.
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