Database class one method vs lots of methods [closed] - c#

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
I'm doing a Database class for my application to connect to a Sql Server database and I'm thinking in centralize queries and procedures execution in it. But I'm in doubt between having one method for each action (this will probably get to a hundred methods) or creating a more "generic" method.
Examples:
1) One method for each action:
public bool TryLogin(string username, string password) {
[do query/procedure things and return]
}
2) A "generic" method:
public DataSet procedure(string name, Dictionary<string, object> values) {
[run through the values dictionary to
define the parameters, run and return a dataset for caller class]
}
I thought about the first one, but I'm wondering if having too many methods wouldn't be bad for performance.
For the second one, I thought about using SqlParameter AddWithValue(string, object), though I'm not sure how it works.
Which of them is better? Or is there a better solution?
Thanks in advance and sorry for english errors.

I prefer the first, although you could combine the two and have your TryLogin method call down to the procedure method to do the database call. Then you only need to re-implement the database call if there is a special need for one of your stored procedures. With a helper method to construct the values argument you may save a bit of code overall.
With the "generic" method alone you are forcing callers to construct Dictionaries and it looks like you're also forcing callers to know procedure and parameter names. So now you've created unnecessary complexity for callers, forfeited type checking on parameters and your data layer is leaking into your business objects.
I wouldn't encapsulate all of my database calls into a single class, either. That sounds like a maintenance nightmare. At the least I would break them down by their domain.

Related

Use a single dictionary object instead of multiple method parameters (similar to args[] in Main method) [closed]

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 2 years ago.
Improve this question
Can a single dictionary object be used in place to replace method parameters (similar to args in Main method) is this a good idea or if bad? what would be a better approach than this?
private async Task<OperationResult> AddOrUpdateRecord(Dictionary<string, object> args)
{
args.TryGetValue("record", out object record);
...
... etc
var recordExists = new RecordExists(record as RecordDto, _dnsCommonActionsRepo);
}
is this a good idea or if bad
This is in the vast majority of cases a very bad idea. The caller will have no idea what parameters are needed. You cannot pass any typed object, so you lose all type safety. You will have no compiler checks to catch potential errors. You are also likely to reduce performance if that is a concern.
what would be a better approach than this?
In most cases, regular parameters. In some cases, where you have way to many parameters, and is unable to refactor the method, a parameter object that gathers many different parameters might be motivated. The only use case I can think of for something like this is when you are getting untyped parameters from some source, for example, key-value pairs from a database or file.
If the problem is breaking builds due to signature changed, that is intentional. The compiler saves you from shooting yourself in the foot. Good refactoring tools, like R# allows modification of signatures, but if you add a parameter, chances are you need to fix call sites by hand.

How to determine if passing in an object is better than several parameters (int, string, etc) [closed]

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.

The best way to pass values between classes in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
First case:
If I have a set/get method for a value inside the class A, I can
set that value from the class B and use it inside A.
Second case:
I can just pass the value in a traditional way like Method(value);
Please, explain me which way is better.
I appreciate your answers.
Properties (what you call the set/get method) are essentially a "syntax sugar" on top of regular C# methods. There will be no performance difference between using properties and using regular methods.
Generally, though, you should prefer properties to methods for readability, i.e. when they present an appropriate semantics to the readers of your class.
Setters and Getters should be used for general properties of classes, used across several methods.
A parameter to a method call is appropriate for a variable tied to that one method (though possibly stored and used elsewhere, for instance if it is part of initialisation).
As always, do what looks best and works well in your context. If the using code feels awkward, look for another way. If it feels right, it's probably OK.
The goal of Object oriented programming is to have your data and operations together.
The goal is to reduce coupling between different kinds of objects so that we can re use the classes.
Never expose the data inside the class to the outside world but provide interfaces to do so

Is there any sense in such kind of refactoring? [closed]

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.

Best Practices - Is it necessary to check for certain preconditions if another method does so? [closed]

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 4 years ago.
Improve this question
Here's an example. I saw a "ReadOnlyDictionary" class online and it had the following code:
void ICollection.CopyTo(Array array, int index)
{
ICollection collection = new List<KeyValuePair<TKey, TValue>>(this._source);
collection.CopyTo(array, index);
}
For example, should I check array for a null argument, or should I let the the CopyTo method do that for me? It just seems a bit redundent, but if best practices say to check everything in your own method, then that's what I want to do. I'm just not sure what "best practices" says to do.
I think it wise to say if you plan to do something with array that relies on it NOT being null then you should check this. But if it just a pass through then I don't see a reason why you should check.
Another thought is if the method gets complicated in the future. You might still want to check for it because someone may modify the code and use array without realizing that it might be null. This is only for maintaining good code in my opinion.
If somebody else's library or API* is going to complain about my inputs, I don't want to give it those inputs, I want to validate and/or complain first. This is especially important if calls into external APIs are expensive, such as a database or web service call.
You know what inputs the API is going to reject. Don't send those, invalidate them in your own public API.
*Note: I consider my own public boundaries to be the same thing. If I have class Foo that does not like given arguments, if I invoke Foo, at some level before doing so, I'm going to validate my arguments. You don't do this at every level (assume there are layers of indirection, maybe, private methods calling into private methods, etc.), but at some reasonable public boundary, I will validate. Validate early, don't let complicated logic or work be done when it's just going to be rejected anyway.

Categories