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 1 year ago.
Improve this question
Hope you are fine. I started learning C# about 2 weeks ago.I’ve been watching videos since now. Now he is teaching Constructions . I don’t get it. When you can use all strings and all numerical values, why restricting them? I mean does it make things bad if you just let it to be default? I tried many ways but I couldn’t find my proper answer. Your reply is so much to me and I really like to know why?!
There are many reasons why one might want to use a constructor, but they are optional and depend on what the developer wants to do.
Constructors can receive parameters and set values based on the
passed values/objects. So you can have many different constructors setting up the object in different ways
Constructors can also include logic to determine how fields/properties should be set. If at all
Constructors can call other constructors of the same class
Constructors are needed if you are using dependency injection, or
readonly fields/properties.
If you want to create copies of your class object, then constructors
can be very useful way to do this. Especially deep copies.
You can also have a static constructor. It is invoked only once in
the class and it is invoked during the creation of the first
reference to a static member in the class.
Constructors can also be private. And you can have a mix of public
and private constructors.
Constructors are useful in inheritance, to ensure that parent
fields/properties are still set correctly no matter what the child does (the child can then change these of course
Sometimes it is as simple as if you are setting many default values,
it can be easier to read if they are all in the same place where you can group them together can comment on them together
BTW: Even if you don't create a constructor, the compiler will create a default one for you.
So simply put, C# provides you with lots of different options. It is up to you to select the one which suits you best for this specific task & class.
There are several topics you can explore that will show where it is necessary...
Dependency injection and Private Readonly Properties for example.
It can also just be convenient
new Uri(pathNameString) will generate the Uri object you can put in an http request by just providing the string at instantiation.
Related
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.
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
We are about to start a project right from scratch. As per the design discussions i am thinking to bring this topic.
Most of the times,I have seen that Abstract classes were being used just to provide some default/common behavior with some concrete methods.
So, i thought of defining those concrete methods as Extension methods for the Interface i am going to develop in place of Abstract classes.
Can someone guide me regarding my design decision. If you are not going to agree with my point please justify your argument with possible scenario/issues which we can face in case of doing so. So, that it will improve my knowledge.
Both approaches are very very different.
Using an abstract class and though abstract/virtual methods, you allow the derived classes to override a behavior which is not the case for extension method. Extension methods are extensions at the end of the day, they are not part of the type and are hard to spot when someone is examining the API and the features the type provides.
Second point, creating an extension method for a type that you create yourself is not that logical IMHO. Using a base Abstract class keeps your hierarchy clear and keeps your model open for modifications of overridden behaviors.
Extension methods were introduced in C# because a very particular requirement.
When they were designing LINQ they realized that they wouldn't want to create a new interface which would contain all known LINQ methods like Where or Select, because it would mean that any enumerable or collection implementation would need to implement it.
Above mentioned fact has an important drawback: it would need to extensively change the source code of a lot of classes from the Base Class Library and any third-party library or project implementing custom collections couldn't take advantage of LINQ at all.
Then they thought about an approach that could directly work with iterators (i.e. IEnumerator<T>) and that could be compatible with any IEnumerable<T> without having to modify any existing code but just adding new code to new assembly members.
And they invented extension methods, which would be implemented like static methods and they would act as instance members of a given type.
Since the inception of extension methods, they've been implemented in many other scenarios, but they always cover these two use cases:
I've a large code base and I want to offer a functionality to all types deriving (classes) or implementing (interfaces) some other type without having to modify them implementing a new interface across a lot of code (increasing the chance of introducing new bugs).
I don't own the source code of some project and I want to extend some types to support some new methods.
Anything outside these use cases is an abuse of extension methods.
Extension methods aren't a replacement to regular class-based object-oriented programming.
Basically you could extend every class or interface - nothing else is done with the Linq-extension methods.
However you can not define those methods directly in the interface, you allways need a static public class that contains those extensions.
To answer your questions I doubt that defining a default-behaviour within extension-methods is a good thing as it completely compromizes the actual intention of that interface. When creating an extension-method all instances of that (extented) class/interface share those methods, thus what you´re doing is to say every instance of my interface is able to be treated as my abstract class.
Having said this you should differ between the behaviour (the interface) and the actual processing (the class). Mixing both will eventually make your design quite complicated.
Next is by defining extension-mtehods you completely bypass inheritance. So what if you want to override the default-behaviour? You would be lost defining them as new or any different wewird workaround because your design was not open for inheritance at all.
Last point from my view is that you should use extension-methods for classes you don´t have control about. However when you can modify the code you´ll probably won´t use them.
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
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
what is your preferred implementation style for a factory pattern? For example, consider a website where I want to use a factory pattern to save to 2+ external systems. This is my first impression for a clean implementation:
Create a class named ExternalSystemManagerFactory
In the constructor of this class pass in an enumeration to indicate the target external system. For example: ExternalSystemManager.System1 or ExternalSystemManager.System2
Create a property on this class named ExternalSystemManager of type IExternalSystemManager
The constructor would set this property value based on the constructor argument
Create a method stub on IExternalSystemManager named SaveToExternalSystem
Create 2 concrete classes for my external systems that implement IExternalSystemManager (EsmSystem1, EsmSystem2)
Then in my client class, I could save to ExternalSystem1 like this:
new ExternalSystemManagerFactory(ExternalSystemManager.System1).ExternalSystemManager.SaveToExternalSystem();
Does this seem like a reasonable implementation? Do you see any potential issues with this implementation? Is this a fairly common implementation style or is there a general trend towards a different implementation style?
In my opinion when it comes to patterns, it typically has to do with how it "feels" when you use it. If you are comfortable with accessing your data in the way you have written it, then by all means go for it. I'm a firm believer that there really isn't a perfect way to implement a pattern and I actually avoid them unless my code blatantly has a need and they emerge naturally. So my advice is...Don't force it, but if it feel good, then do it.
The approach that you describe is ok, if it is only about two implementations. If the number of external systems that you want to access increases, you'd always have to change
the enum
the switch statement in the constructor that chooses the concrete implementation.
In the abstract factory pattern that the Gang of Four describes, you'd get rid of the enum and implement it like this:
An abstract base class/interface for the factory.
An implementation of the factory for each concrete external system.
You create the concrete factory at one spot in your code and always access it through the interface.
An advantage of this implementation is that you can easily configure which factory to create instead of using a switch statement in your code. Besides that you wouldn't have to adjust the switch statement each time you connect a new external system, it also allows you to create implementations for new systems without touching the assembly of the factory at all.
Another approach you might want to consider if you have lots of dependencies you want to create is to use an Inversion of Control Container. You register the types that should be created for an interface at the beginning of your application and ask the IOC container if you need an instance or inject it in the constructors of the classes. There are several IOC containers available, e.g. Microsoft Unity, Ninject, AutoFac, .... This will save you lots of time if you have several or huge factories.
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 3 years ago.
Improve this question
You have an immutable object, and you set its internal variables in the constructor which accepts couple of parameters.
Question:
Do you see any problems to VALIDATE constructor parameters in the constructor method of an immutable object and throw ArgumentExceptions if not valid?
(to me it makes sense but I wanted to ask in case there are some better ways or something not OK with this - for example if it is a better design to move validation from constructor to a factory)
Or if I generalize it by rephrasing the question:
Is it OK to put business rules-wise logic in the constructor methods? Or should constructors always do nothing more than setting object's internals?
Thanks
In a way, it makes sense to validate in the constructor itself because you know that all usages of it will pass through that single point, and any other developer that will use your code will be protected from making mistakes because of your "low-level" validations.
If you move the validation higher up the call chain, you leave the class code cleaner but you expose the code to the possibility of "you're using it wrong" bugs.
Constructor validation has a slight problem in case of invalid data: What do you do then? You have to throw an exception, which might be awkward and also a performance hit, if you create "invalid" instances often.
To get rid of try ... catch every time you instantiate the object, you would have to create a factory anyway.
I think the factory is a good approach, but in a slightly different way - validate the arguments given to the factory method and only then create a (valid) instance.
A class should, to the best of it's ability, document the guarantees it makes, and do its best to keep itself in a valid state at all times. Any incoming calls that are either inappropriate or would put the object in an invalid state should generate exceptions.
This holds true for constructors too. A constructor that doesn't validate its inputs makes it possible for others to create invalid instances of your class. But if you always validate, then anyone with a reference to your class can be confident that it is valid.
If it was me I'd validate the parameters before I pass them into the constructor. You never know how your code is going to evolve so doing the validation in a factory as you suggest should provide a bit more visibility and feels 'cleaner'.
If you have a choice for where to raise an exception, just go with wherever you're more likely to remember to surround it with a try..catch, it helps to consider other users of your codebase too. This more often then not depends on the purpose of the class, and how you see it being used. However consistency is also important.
Sometimes it's useful to not raise exceptions in either and instead have a separate ValidateInstance() function for immutable types. Your other choices are as you say class creation (via factory or constructor) or on class usage (usually a bad idea if an error can be thrown sooner.. but sometimes makes sense).
putting them in the constructor has the advantage that they will also surface in a Factory method, if you chose to make one later.
HTH