Basically, I have something like the following:
public string SomeDBMethod(string server, string dbName, string userName, string password,...)
Is it good practice to refactor it to the following:
public string SomeDbMethod(DBParams parameters, ...)
Where DBParams is defined as follows:
public struct DBParams
{
string Server {get;set;}
string DbName {get;set;}
string UserName {get;set;}
string Password {get;set;}
}
My point is really to be able to pass around less parameters as I find functions with long parameter lists really quite ugly.
I have also found that there are some limitations to this approach: if SomeDbMethod is to be exposed as a web service method, I cannot use the DBParams struct as a parameter (as far as my understanding on the subject of web services go...which isn't very far).
So, is this too much trouble for little benefit or am I on to something here?
Unless you actually need to pass around this set of parameter very frequently (with the same data), I don't see any need. Long parameter lists are sometimes a sign of a need to refactor your code, but then again are sometimes inevitable. (In your situation is seems more like the latter.) So, simply go with the straightforward method of passing the parameters directly unless you find yourself needing to store the parameter sets (at least temporarily) - you really won't be saving any code otherwise, and certainly not increasing readability.
The method use a struct does not impose any limitations in relation to web services. You just need to make the type as serialisable (DataContract
in WPF, I believe), and there shouldn't be any problems.
I always group parameters that go together into a single object - the code is cleaner this way, it is obvious that they are related to each other and always used together.
However, in most cases I use a class and not a struct. The benefits of structs were never clear to me, and they are pain in the back in many situations (I guess the webservices scenario is just one example).
You can make a class immutable if you don't want people to change it (if this was the reason to use struct)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With