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
Good Morning,
I am working on WindowsForm. I came up with 2 solutions. I wanted to know which solution is good practice to follow?
Solution 1:
I have a written a common static methods for validation like phone-text box, mandatory_textbox-key press etc.I have many common methods like this. So what i did is i created a utility class and placed all these static methods in it. Then used these methods across the application.
Solution 2:
i got an idea, so what i did is i created a baseform-inherited Form class, Then i inherited this baseform in all the other forms(Multi-level inheritance).
In the baseform i moved all the validation methods from Utility class and made then non-static.
I also taught about UserControl. If i do that i have work with the alignment tasks again. So that only came up with the two solutions
So Can you suggest which to follow?
You can move the static methods inside non static classes, and pass concrete objects (maybe through interfaces) to the classes/methods who needs that functionality. This way you keep your code easy to test, and decoupled.
By example if you have a class PhoneNumberValidator implementing the interface IValidator which have a method bool Validate(string phoneNumber), and pass it where you need to validate a phone number.
I guess this wuould be the best practice to have a decoupled application.
There in no straightforward answer on whether one should declare methods as static or not. It depends on the context and functionality of your application.
Going with some assumptions for your situation, consider following thoughts on high level -
If the validation is related to one particular form only, and not applicable for other forms, declare it within your form class ans private method. If these validations do not require any class instance, you may declare them static.
If some validations are common for different form, you may declare them as static. Do take caution and do not pass controls to these methods, instead pass the values that you want to validate for better design.
Consider declaring validations in base form only if those are applicable to all or if not most of the forms, and again, if they do not use any instance object, you may mark them as static
A good discussion here.
Use User Control instead of a separate form, if these common controls are being used in every form. Static methods are supposed to be used for utils kind of requirements.
Some times ago I tried to use both solution described by you for different tasks. Every of this have own pluses and minuses.
So, in first case we have only one ststic class and one implementation of every static methods in memory. We can apply this methods to any quantity of other object instances. But we need access this class in every namespace where we will use it.
So, if we will make some changes in any code of this class, it will be applied to all object instances related this class. Sometimes it's convenient, sometimes not.
In second case we will got new instance of base form in memory (less efficient), but we also have one base implementation of methods for inherited forms like first approach. As additional benefit we always can override methods for special cases (if it's needed) for some specific instances only.
In any case, only you can make right decision based on your task context.
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 7 years ago.
Improve this question
I am trying to restructure an application, and right now there are two classes which are subclasses of another class.
Both of these classes have a method. This method essentially does the same thing (get user information) but from different data sources and parses them differently (say one uses the Facebook API and the other a database). They also take in different parameters.
Does it structurally make sense to leave both methods in the subclasses with the same method name? Or is there a cleaner way of organizing the methods within the subclasses?
Even though both methods are logically GetUserInfo, it is also correct that one is logically GetUserInfoFromFB and the other GetUserInfoFromDB.
You could create an abstract GetUserInfo method, but since the methods get different parameters, it could easily get messy. It is easily feasible, however, if the parameters can be logically refactored as properties of the subclass (or properties of logical class to hold them together, that being a property of the subclass).
Edit: The strategy pattern is applicable here, but is what I would consider "messy". Your case as you presented it is small in scale, so the the strategy pattern just might be an overkill.
tl;dr If you do not think your case justifies the strategy design pattern, it is perfectly fine to leave it as it is.
This is a perfect place to apply the strategy pattern.
Rather than having a different GetUserInformationMethod call for each class, create a new class (or a delegate type) that exists just to get user information. Have a UserInformationGetter attribute which is an instance of your user information fetching class/delgate in the base class, and have the base class's GetUserInformation method invoke the delegate/class to get user information.
The challenge of different parameters could be handled in a number of different ways, which depends on the parameters. If the parameters are related to the details of implementation (e.g. database connection strings), and not variant across users then you should tie that information to the UserInformationGetter class.
If the information is dependent on the user, there are a number of strategies. I would suggest you create a type that encapsulates all the information about the user that is used to fetch user data in either case. Then you can pass this object to the methods, rather than parameters that vary accoridng to the method of data access.
This way, you can vary the user information fetching strategy of your base classes independently of anything else which might vary between the classes. Additionally, you can vary the way you get user information at runtime, allowing your program to adapt to changing requirements easily.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My application is mainly composed of Campaigns. They are the main object of my model.
I have two types of campaign:
Ad hoc: Campaigns that are run once immediately
Scheduled: Campaigns that are scheduled for future and can be run multiple times according to their schedule.
There are shared attributes between these two and there are attributes that are specific to each. What is the best way to design this data model? Interfaces or Abstract classes?
Let's say both types of campaigns can have an Id and a Name and:
Only Ad hoc campaigns have a DataTable called Recipients
Only Scheduled campaigns have a List<DateTime> called Schedule
If you're kind enough not to vote me down or ask to close this question, please provide a basic structure of your recommended model including access modifiers and the abstract/virtual or another keyword that will help me have a better structure for my model.
This is very difficult to answer without a very good understanding of what you're doing and it is unfortunately very opinion based.
However at a very simple level if you use an interface you will often have to duplicate code between the implementing properties (methods, properties and so on). A base class provides this functionality to them. For this reason I often use a base class unless there's a specific reason why an interface is more appropriate.
I would suggest different types of campaigns are all campaigns in essence and so have a base class. However they will target different entities (people, charities, companies) which will all need a way of contacting them (email/phone/address) I'd suggest that these unrelated entities (beyond the fact they can be targeted by a campaign) are a better example of when to use an interface.
However you will need to think about which methods you would override and which is the cleaner solution.
Generally speaking, if they share common behavior (code), that code should exist in an abstract class. If they perform the same role, put them behind an interface.
In your case you seem to have two shared properties, both a simple value, which does not really define behavior, so just based on those properties I'd go for just an interface.
If you do decide to create an abstract class (perhaps there is some code both types would like to share), you could still keep the interface. You could some day have a third campaign type that does not share behavior with the other ones (so does not implement the same abstract class), but does perform the same role (so does implement the same interface).
As for access modifiers in an abstract class, if both classes share only two properties, you just define them in the abstract class without abstract or virtual keyword.
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
Consider for the question this String.Split overload, which takes a StringSplitOptions enum as a parameter.
Isn't it bad that the enum itself is public and accessible to everything that includes the System namespace? I mean, the enum is completely specific to options of the Split method, yet it's available outside of it's scope.
Perhaps there is a better way to model this, like putting the enum inside the String class itself, and accessing it by using String.SplitOptions for instance? I very rarely see this (I actually can't remember any such case now), so I assume it is not preferred for some reason. In general, I think reducing the scope of things is a best practice because you lower the chance of problems occurring by using a class/member in an incorrect scope, so to speak.
I'm using Split as an example here, but it is quite common for a Enum to be used only by a method or class in our code base too. I generally create the enum as a public type in a separate cs file like any other class, but I would love to hear other approaches to this 'problem'.
Update:
I just found this article that attacks this exact problem, with a Folder class and a Filter enum but again seems go against what I believe would be more correct in that case (placing the enum inside the class somehow). One of the comments in there from ToddM (which I happen to agree with) states:
...
But, even then, I feel your logic is wrong. Your main complaint
against embedding the enum inside of the class is that it will take
too long to type. Given how verbose C# tends to be, this is not really
a sensible argument. In VS, CTRL+SPACE is your friend.
Logically, I feel placing the enum inside of the class is far more
correct. Take your example: what is a MyNameSpace.Filter? Where does
it apply? I guess it's a filter for your namespace? It's impossible to
tell, especially if your namespace grows to contain dozens of classes.
Now consider MyNameSpace.Folder.Filter -- it is, in my mind, far more
intuitive that Filter applies in some way, shape, or form to the
Folder class. Indeed, another class can be added to the namespace with
its own concept of filter, one of whose members may be 'File'. Just
because you've introduced a new class into the namespace doesn't give
you the right to pollute that namespace with various 'helper' types.
If you are developing as part of a large development team, your style
is, well, rude.
...
It's an interesting idea to nest the enum in order to suggest that it has a reduced scope, or to give it better semantics. I have used this idea before in order to have both error codes and warning codes in a post-compiler I developed. This way, I could use the same enum name Code nested either in the Error class or the Warning class.
On the other hand, public nested types are generally discouraged. They can be confusing to clients who have to qualify them with the outer class name. Look at the related guidelines on MSDN. Some that are relevant:
DO NOT use public nested types as a logical grouping construct; use namespaces for this.
AVOID publicly exposed nested types. The only exception to this is if variables of the nested type need to be declared only in rare scenarios such as subclassing or other advanced customization scenarios.
DO NOT use nested types if the type is likely to be referenced outside of the containing type.
For example, an enum passed to a method defined on a class should not be defined as a nested type in the class.
I believe those guidelines were followed when developing the StringSplitOptions enum, and most of the others in the BCL.
String.Split() is public, so StringSplitOptions has to be public too. Both String and StringSplitOptions exist in the System namespace. Both have public scope. Neither is "available outside of [the other's] scope".
I think one of the reasons is that it would make every call using an embedded enum wider (the name of the class becomes a mandatory prefix).
I personally wouln't appreciate having to use ResultSetTransformer.ResultSetTransformerOptions every time I have to use this enum, it would make my line horribly long.
But as others pointed out, I don't think it's standard in the framework to embed enums in classes at all, possibly for this reason.
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'm trying to learn the correct way to use classes in my code, when it's not something obvious like a set of customers, dogs inheriting from animals, etc.
I've broken off large sections of code into "features" such as Installer.cs, Downloader.cs, UiManager.cs. The only way I can find to have those classes interact with each others' properties and methods is to make them all static, which I've been told in another question is the wrong way to go.
So my problem is one of 3 things:
There is a way to make classes talk to each other that I just don't understand yet.
Classes should never try to talk to each other, but perform one-off actions and then return something back to main/form1, which the main class can then use to pass into another class for a one-off action.
Classes are really only useful for making lots of instances, and there's some other structure entirely I need to learn about for abstracting large chunks of functionality out from the main class.
All the tutorials I can find and lectures I watch seem to only tell you how classes work, but not when and how to use them in a real product.
EDIT - A more specific example:
Say I have one string that is central to the entire app, and needs to be seen and/or modified potentially by every class. How do I move that information around the code without either having everything in one class or making it static?
I can't see a way to let that string live in Form1 without making it static (because all the form events and functions would need to be able to see it to pass it to a class).
I can't see a way to put the string into another class without having to make the string and the whole class static, so other classes can see into it.
Maybe there's something I'm missing about actually instantiating the classes, and making objects interact with each other.
I think all your intuitions are right.
No, there's not. Static or instance.
It's a design choice (and there's a lot out there). I'm a pragmatic, so I consider a design pattern that generates spaguethi code a bad design pattern choice. But a bad design pattern for a project can be a good design pattern for another project. Try to read the Head First Design Pattern book.
Yes, there are interfaces and abstract classes.
A few more thoughts:
I don't think the use of static methods or classes must be avoided. What must be avoided is the miss use of a static method or class, like the miss use of everything inside a language. But is very hard to define what's a miss use of a static, and because static methods or classes are particulary dangerous, people like to say to avoid the static keyword at all. A static method will be in memory unless you end your application, so if you don't dispose a connection inside a static method, you will have a very bad day.
I have a utility project, and inside the utility project I have a data class. The data class provides access to the database. It's a static class. Why?
Well, first of all, it is static because the connection string comes from the webconfig. So I have a static constructor (runs once when the application starts and the class is mentioned) who reads the webconfig and store the string in a static private member variable. I think it's a lot better than read the webconfig file and create a scoped variable 10 bilion times day. The methods are static because they are simple enough, meaning that they don't need a lot of configuration to work, they just need a few parameters and they are used only in the data access project. All my website users are using the same instance of the method (the static one), but everyone uses the static method with different parameters, so they get different responses from it (they share the pipe, but they drink different water). It's only necessary extra care inside the method to clean everything (dispose every scoped instance), because if you don't they will stay in memory. And finally, my bussiness is about data manipulation, a non static data class means a lot more memory usage than a static one (the cpu usage is almost the same in both patterns).
public abstract class Data
{
[...]
static Data()
{
#if DEBUG
_Connection = ConfigurationManager.AppSettings["debug"];
#endif
#if RELEASE
_Connection = ConfigurationManager.AppSettings["release"];
#endif
[...]
}
[...]
}
In the end of the day I use static when:
If it is simple enough (that I can control every aspect);
If it is small enough (I use extension methods to validations, and they are static) and;
If it is heavy used.
Besides that, I use layers to organize my project (poco + factory pattern). I have a utility project, then a entity model project, then a access project, then a bussiness logic project, then a website, a api, a manager, and so on. The classes in the utility project don't interact each other, but the classes inside the entity model project do (a class can have a instance of another class inside it). The entity model project don't interact with the utility project because they have the same level, they interact each other in another level, in the access project, but it's more intuitive in a data manipulation project.
Classes talk to eachother when they have a reference, in order for A to pass a message to B, A needs a reference to B (either an instance or static reference)
Classes can either talk to each other, or return information to another class that controlls the whole process (this is actually a design pattern)
For abstracting information from the main class (or any class) you have interfaces and abstract classes
The Design patterns book from the Gang of Four it's a must read in this case.
Something else to keep in mind beside is the simplicity of your design, sometimes trying to fit to a design pattern just cause may end up creating more spaguethi code. As a rule of thumb always try to sepparate the presentation funcionality from the logic, and think of classes as persons talking to eachother and performing jobs (it's kinda weird iknow but sometimes it helps me to think this way)
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
In what circumstances (usage scenarios) would you choose to write an extension rather than sub-classing an object ?
< full disclosure : I am not an MS employee; I do not know Mitsu Furota personally; I do know the author of the open-source Componax library mentioned here, but I have no business dealings with him whatsoever; I am not creating, or planning to create any commercial product using extensions : in sum : this post is from pure intellectal curiousity related to my trying to (continually) become aware of "best practices" >
I find the idea of extension methods "cool," and obviously you can do "far-out" things with them as in the many examples you can in Mitsu Furota's (MS) blog postslink text.
A personal friend wrote the open-source Componax librarylink text, and there's some remarkable facilities in there; but he is in complete command of his small company with total control over code guidelines, and every line of code "passes through his hands."
While this is speculation on my part : I think/guess other issues might come into play in a medium-to-large software team situation re use of Extensions.
Looking at MS's guidelines at link text, you find :
In general, you will probably be
calling extension methods far more
often than implementing your own. ...
In general, we recommend that you
implement extension methods sparingly
and only when you have to. Whenever
possible, client code that must extend
an existing type should do so by
creating a new type derived from the
existing type. For more information,
see Inheritance (C# Programming
Guide). ... When the compiler
encounters a method invocation, it
first looks for a match in the type's
instance methods. If no match is
found, it will search for any
extension methods that are defined for
the type, and bind to the first
extension method that it finds.
And at Ms's link text :
Extension methods present no specific
security vulnerabilities. They can
never be used to impersonate existing
methods on a type, because all name
collisions are resolved in favor of
the instance or static method defined
by the type itself. Extension methods
cannot access any private data in the
extended class.
Factors that seem obvious to me would include :
I assume you would not write an extension unless you expected it be used very generally and very frequently. On the other hand : couldn't you say the same thing about sub-classing ?
Knowing we can compile them into a seperate dll, and add the compiled dll, and reference it, and then use the extensions : is "cool," but does that "balance out" the cost inherent in the compiler first having to check to see if instance methods are defined as described above. Or the cost, in case of a "name clash," of using the Static invocation methods to make sure your extension is invoked rather than the instance definition ?
How frequent use of Extensions would affect run-time performance or memory use : I have no idea.
So, I'd appreciate your thoughts, or knowing about how/when you do, or don't do, use Extensions, compared to sub-classing.
thanks, Bill
My greatest usage for them is to extend closed-off 3rd party APIs.
Most of the time, when a software developer is offering an API on Windows these days, they are leaning more and more toward .NET for that extensibility. I like to do this because I prefer to depend on my own methods that I can modify in the future and serve as a global entry point to their API, in the case that they change it.
Previously, when having to do this, and I couldn't inherit the API object because it was sealed or something, I would rely on the Adapter pattern to make my own classes that wrapped up their objects. This is a functional, but rather inelegant solution. Extension methods give you a beautiful way to add more functionality to something that you don't control.
Many other peoples' greatest usage for them is LINQ!
LINQ would not be possible without the extension methods provided to IEnumerable.
The reason why people love them is because they make code more readable.
I have noticed another MAJOR usage of extension methods (myself included) is to make code more readable, and make it appear as if the code to do something belongs where it is supposed to. It also gets rid of the dreaded "Util" static-god-class that I have seen many times over. What looks better... Util.DecimalToFraction(decimal value); or value.ToFraction();? If you're like me, the latter.
Finally, there are those who deem the "static method" as EVIL!
Many 'good programmers' will tell you that you should try to avoid static methods, especially those who use extensive unit testing. Static methods are difficult to test in some cases, but they are not evil if used properly. While extension methods ARE static... they don't look or act like it. This allows you to get those static methods out of your classes, and onto the objects that they really should be attached to.
Regarding performance..
Extension methods are no different than calling a static method, passing the object being extended as a parameter... because that is what the compiler turns it into. The great thing about that is that your code looks clean, it does what you want, and the compiler handles the dirty work for you.
I use extension methods as a way to improve the functionality for classes without increasing the complexity of the class. You can keep your classes simple, and then add your repetitive work later on as an extension.
The Min() and Max() extension methods are great examples of this. You could just as easily declare a private method that would calculate these, but an extension method provides better readability, makes the functionality available to your entire project, and didn't require making an array any more complex of an object.
Taking the sub-classing approach vs. extension methods requires a couple of things to be true
The type must be extendable (not-sealed)
All places the type is created must support a factory pattern of sorts or the other code will just create the base type.
Adding an extension method requires really nothing other than using a C# 3.0+ compiler.
But most importantly, an inheritance hierarchy should represent an is-a relationship. I don't feel that adding 1 or 2 new methods / behaviors to a class truly expressing this type of relationship. It is instead augmenting existing behavior. A wrapper class or extension method much better fits the scenario.
In some cases you can't use a subclass: string for instance is sealed. You can however still add extension methods.