Is there any sense in such kind of refactoring? [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
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.

Related

two differents method or additional parameter? [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 5 years ago.
Improve this question
I have a method set in an POCO entity that set the basic property and the navigation property. In some cases, I don't need to verify some conditions, but in another cases I need to verify to ensure that the information is coherent in the database, but this verification makes me to get extra data from database.
So by the moment I have my basic method that is this:
public void setMyProperty(MyType paramProperty)
{
this.Property = paramProperty;
this.IDProperty = paramProperty.IDPorperty;
paramProperty.MyNavigationCollection.Add(this);
}
For the method that verifies the data, I guess that I have two options.
First one, I can create a new method for business logic, somthing like that:
public void setPropertyBi(MyType paramProperty)
{
//check conditons
//If all OK then
this.setPorperty(paramProperty);
}
But I have another option, use only one method, not the basic method and the other for business checks. Something like that:
public void setProperty(MyType paramType, bool paramDoChecks)
{
if(paramDoChecks)
{
//Do checks
}
//if all OK
this.Property = paramProperty;
this.IDProperty = paramProperty.IDPorperty;
paramProperty.MyNavigationCollection.Add(this);
}
Which is the recommended option? or there are another ways?
People here seem to prefer the flag, I personally think it is horrible.
You want to achieve two different things: just set a property; validate AND set a property. IMHO it should be two separated methods.
Just don´t write two different Methods if it´s one equaly functionality. Just add a Parameter which makes the validation-difference like you´ve written last.
But don´t forget to enter the behaviour if validation failed. separate it well.
You could add a Boolean ValidationRequiredproperty to MyType which you can set before the call to setMyProperty().
I prefer to have two methods: CanSetProperty and SetProperty.
CanSetProperty: just check the condition, does not change anything in the parameter.
SetProperty: will modify the paramenter.
I think this code is a good candidate to follow the Command Query Separation Pattern
The fundamental idea is that we should divide an object's methods into
two sharply separated categories:
Queries: Return a result and do not change the observable state of the
system (are free of side effects).
Commands: Change the state of a
system but do not return a value.

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.

Database class one method vs lots of methods [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
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.

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

Equality methods -- naming convention [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 9 years ago.
Improve this question
I often experience difficulties in designation of my methods. For instance, now I have a static method which compares two hashes, and I stuck with its name. HashesEqual(string h1, string h2)? AreHashesEqual(string h1, string h2)? Your better version? This is generic question -- I have a lot of such stuff. Is there any authoritative source where I can read about naming conventions?
From Names of Type Members on MSDN:
Do give methods names that are verbs or verb phrases. Typically methods act on data, so using a verb to describe the action of the method makes it easier for developers to understand what the method does. When defining the action performed by the method, be careful to select a name that provides clarity from the developer's perspective. Do not select a verb that describes how the method does what it does; in other words, do not use implementation details for your method name.
Do name Boolean properties with an affirmative phrase (CanSeek instead of CantSeek). Optionally, you can also prefix Boolean properties with Is, Can, or Has, but only where it adds value.
I think others will agree that any naming convention is good as long as it makes sense and you use it consistently.
Alternatively, consider creating an extension method for the string class that provides this functionality. Then you can simply do:
var equal = h1.EqualsHash(h2); // or similar, based on the naming you choose
Or write a custom Hash class that keeps the hashed values internally, and override/overload its Equals method and ==/!= operator(s), giving way to this:
var h1 = new Hash("string1");
var h2 = new Hash("string2");
var equal = h1 == h2;
// or
var equal = h1.Equals(h2);
Or make your utility class stand alone (e.g. HashUtil or something), and keep the word "hash" out of its method(s) entirely:
var equal = HashUtil.AreEqual(h1, h2);
Also see: Guidelines for Names
I'd suggest all developers read the .NET Design Gudelines (linked is the specific section on type members). In your instance, because the return type is also a boolean value, I'd recommend you try something like:
IsHashEqual(string testHash)
The only method name suggestion provided by the .Net Framework Guidelines is that methods should be
DO give methods names that are verbs or verb phrases
I think that Are do qualifies as "verb phrases" and would work here.
In this case though you aren't defining something new but rather a specific form of a well established pattern: Equals. Given that my inclination would be to prefix the function with Equals so that it shows up close to Equals in features like Intellisense, Search, etc ...
EqualHashes(string p1, string p2)

Categories