In resharper features page:
Extract Class
Enables extracting some of the fields and methods of a class into a separate, newly created class. This refactoring is useful, when a class has grown too large, too incoherent, or does too many things.
I select couple methods within class, open context menu and can't find anything related to extract class, do I miss something?
Found it:
You need to place your cursor on class name, then in Refactor menu there's Extract class submenu.
But couple tries show, that functionality still needs polishing:
would like to have ability simply select methods/fields to be moved to new class and then choose Extract Class,
it does not add using statements for newly created class,
if moving only static methods it does not mark newly class as static, that means it tries to create instance of it when it is not needed and many other small things :)
Related
I have multiple classes in 1 file. I have to put them all in 1 file because of company standards for the program I'm writing something for. Is there some way to only make 1 class in the file accessible?
Nobody needs to see the other classes.
Depends on the purpose. If the only "accessible" class would simply use the functionalities of the other classes, then that class needs to be public, and the rest could be private.
If you have properties in that classes which are types of the other, they cannot be private then.
If you are using any code reviewing tools like stylcop etc. then it will force you to have one class file with only one declared class over there. You can't get rid of this.
But since you are actively using only one class then there are couple of option you have :-
You can make you class private
Use different data structure like struct etc to remove the use of your additional classes.
I often come across the pattern that I have a main class and several smaller helper classes or structs.
I'd like to keep the names of thoses structs as clean as possible. So when I have a class that's called CarFinder that heavily makes use of some special Key object that is only (or mainly) used internally, I'd like to call that object Key instead of CarFinderKey.
Everything to remove all the extra fuzz that distracts me from when I try to understand the class while reading it.
Of course I don't want to pollute the rest of the code with a small helper class that is called Key - it most likely will clash and confuse.
In a perfect world I would have liked to have a keyword like internal to this namespace, but as that does not exist that leaves me the following options that I can think of:
Use internal and put the class in a different project.
Advantage: Perfect encapsulation.
Disadvantage: A lot of organisational overhead and unnecessary complicated dependencies.
Note: I'm not talking about really large self contained systems that undoubtedly deserve their own assembly.
Put it in a different child namespace, like CarFinding.Internal
Advantage: Easy to implement.
Disadvantage: Still can pollute when the namespace is accidently imported.
Put the helper class as a child class within CarFinder.
Advantage Doesn't pollute internally and can even be promoted as a public helper struct that is exposed to the outer world with CarFinder.Key
Disadvantage Have to put the helper class within the same file, or encapsulate it in an external file with public partial class around it. The first one makes a file unneccesary long, the second just feels really ugly.
Anyway call it CarFinderKey
Advantage Easy to implement.
Disadvantage Adds in my opinion too much fuzz to CarFinder. Still unncessary pollutes the naming, just with a name that is not likely to clash.
What is the recommended guideline?
Personally, I don't mind the extra "fuzz" caused by CarFinderKey, and here is why: Once worked on a very large project where we tried to use namespaces to disambiguate names.
So as you expand your system, you can very easily end up with 10 tabs open in your code editor, all named "Key.cs". That was seriously not fun.
It's opinion based. Anyway, I would:
try to make it a private nested class of CarFinder, which usually fails because the Key needs to be passed over to CarManager, you know what I mean. Public nested classes are discouraged.
I would put it into a sub-namespace called Core, a common name for internal stuff. For me, Core is "namespace internal" by naming convention.
The larger the project, the longer names you need. CarFinderKey is still a valid option.
I would never create additional assemblies just for this. It just doesn't feel right.
I had the same dilemma many times, and personally use (3) and a variation of (4).
(3): I have no problem with neither putting the nested class/struct within the same file (if it is small and really tied with the parent class), nor using a separate file within partial ParentClass declaration - the only drawback is that it gets one more level of indentation, but I can live with that. I also have no problem with violating FxCop rules or other recommendations - after all, they are just recommendations, not mandatory. But many people do have problems with all or some of these, so let move on.
(4): You already described the cons. What I'm going to share is how I do overcome them. Again, it's personal and one might or might not like it, but here it is.
First, let say we use a separate file for the key class and name the class CarFinderKey.
Then, inside the code file for the CarFinder class, we put the following line at the end of (or anywhere inside) the using section:
using Key = CarFinderKey;
This way, only inside the CarFinder class code file, anywhere CarFinderKey is needed, we can just refer to it simply as Key, what was the goal. At the same time we keep all the advantages and no clashes. Intellisence works w/o any problem. In VS2015, the lightbulb would even suggest to "simplify the name" for you anywhere it finds CarFinderKey inside that file.
Your decision should depend on your design. Is your Key class really a key only for CarFinders, or could it also be used to find motorcycles or houses or whatever.
One of the first rules the famous Gang of Four stipulated was "Design for change". If you really think that in the very near future your key could also be used to find houses or motorcycle, then it would not be a good idea to make your key class thus private that other could not use it.
Since you are speaking about private helper classes, I assume your key is only useful for CarFinders.
If that is the case and your design dictates that the Key is only useful for CarFinders, or maybe even: if it is designed such that it even isn't useful outside CarFinders the Key class ought to be part of the CarFinders class. Compare this to a simple integer that you would use in the CarFinders class, you would declare it private inside the CarFinders class wouldn't you?
Leaves you with the problem of one big file or a partial definition. From design point of view there is no difference. For the compiler there is also no difference. The only difference is for humans who have to read it. If you think that users of your class seldom have to read the definition of your key class, then it is better to define it in a separate file. However, if you regularly need to read the key class while reading the CarFinder class you should make access to the key class as easy as possible. If your development environment is fairly file oriented instead of class oriented, then I think that in that case the disadvantage of a large file is less than the disadvantage of having to switch between files.
I would put the class and their "helpers" in their own namespace MyNamespace.CarFinding,
so that you have :
MyNamespace.CarFinding.CarFinder
MyNamespace.CarFinding.Key
and I will just put this namespace in a sub-folder of the project.
This will not block the internal helper class to be used elsewhere in the project, but from the parent namespace you could reference your helper as CarFinding.Key
I have at least 3 .feature files in my C# Specflow tests project in which I have the step, for instance:
Given I am at the Home Page
When I first wrote the step in the file Feateure1.feature and created the step method, I placed it in a step file, let's say, Steps1.cs, which inherits from a base class that initializes a FirefoxDriver. All my StepsXXXX.cs classes inherit from this base class.
Then, I wrote Feature2.feature, which also has a step Given I am at the Home Page. And the step was automaticaly bound to the one in Steps1.cs
'Till now, no problem. That's pretty much what I wanted - to have reusable steps throughout the test project. But the problem is, whenever I'm running a scenario that has steps in diferent StepsXXXX files, I get various browser instances running.
======
I'm pretty sure this is due to the fact that My StepsXXXX (binding classes) all inherit from this base class that has a IWebDriver of its own, and when the step is called, everything else (including the before/after scenario methods) is called. But I can't figure out how to work around this.
I still want reusable steps. I tried to put these steps in the base class, but it did not work.
I thought of changing the bindings too, but specflow uses meaningfull strings to do so, and I don't want to change them to misleading strings.
Has anyone stumbled across this?
Any help is really appreciated.
You can use Scoped bindings using [Scope(Tag = "mytag", Feature = "feature title", Scenario = "scenario title")] to referred on specific scenario or feateure like this:
Feature: Feateure1
Scenario: demo
Given I am at the Home Page
When ....
[Binding, Scope(Feature = "Feateure1")]
public class Steps1{
[Given(#"Given I am at the Home Page")]
public void GivenIAmAtTheHomePage(){
{ }
}
Feature: Feateure2
Scenario: demo
Given I am at the Home Page
When ....
...
[Binding,Scope(Feature = "Feateure2")]
public class Steps2{
[Given(#"Given I am at the Home Page")]
public void GivenIAmAtTheHomePage(){
{ }
}
The problem is that SpecFlow bindings don't respect inheritance. All custom attributes are considered global, and so all SpecFlow does is search for a list of classes with a [Binding]then build up a dictionary for all the [Given]/[When]/[Then]s so that it can evaluate them for a best match. It will then create an instance of the class (if it hasn't already done so) and call the method on it.
As a result your simple cases all stay in the Steps1 class, because its the first perfect match. Your more complicated cases start instantiating more classes, hence multiple browsers, And your attempt to refactor won't work because your abstract base class doesn't have a [Binding] on it.
I'd probably start by flattening all your step class hierarchy, into one big AllSteps.cs class. This may seem counter-productive, but all you are really doing is arranging the code just how the current bindings appear to your SpecFlow features. This way you can start to refactor out the overlaps between the different GWT bindings.
At the moment your bindings are arranged around the scenarios. What you will need to do is refactor them around your functionality. Have a read of Whose Domain is it anyway? before you start and this will probably give you some good ideas. Then have a look at Sharing-Data-between-Bindings on the SpecFlow documentation to work out how to link between your new steps classes.
i think this is a lot more simple than the question and answers here make it out to be. there are really two questions at play here:
AISki gave you the right answer in the link to documentation about specflow context, but it was not really presented as the answer and there was distraction in presenting an inferior answer as the actual answer.
the answer as to the behavior you see is that you should expect exactly what is happening with the way you set things up. if you have multiple binding classes that create browser instances (and you do if they all have a common base that creates a browser instance) and they have matches in your features, you should expect multiple browser instances.
The answer for what you intend (a single browser shared among your steps) is that you should use the context feature of specflow to control the dependency on a browser instance. this amounts to dependency injection. your step definition classes should take a constructor dependency on something that creates your browser instance - specflow manages dependencies for you and you'll get a new instance for the first of your classes created and then the same one after that.
https://github.com/techtalk/SpecFlow/wiki/Sharing-Data-between-Bindings
I facing the same issue.
I wanted to have one feature file that will call steps in different cs classes. The issue came across when I want to setup and tear down for each scenario.
Using step class constructor and Dispose() not possible because the scenario uses more than one step class which I don't want to 'setup' multiple time in a scenario.
Using [BeforeScenario] and [AfterScenario] for both step classes also makes the runner run the before and after methods in both class that makes it setup run twice.
So what I was done is create another third class called something like BrowserScenarioSetup put the before and after scenario class in it to setup a browser for the scenario and assign to ScenarioContext.Current dictionary. When the test run, only one browser created for a scenario and I can use scenario steps defined in any class but just uses Scenario.Context.Current to get the browser instance.
I can make both step classes have a base step class and create a short method to get browser instance (or any shared instance created in setup) just to hide Scenario.Context.Current
Finally I can mark [BeforeScenario("Browser", "IE")] and use #Browser and #IE in a feature or scenario to only call this setup method in suitable context.
This is a follow-up to my previous question Stop my "Utility" from giving errors between different architectures, suppose I am trying to create a class library that looks something like this:
- Class Utility (Parent class)
... Utility functions and methods
(EG: Public Sub Sub1() )
- Class Utility_Web
... Functions and methods only related to Web / Web-Controls
(EG: Public Sub Web_Sub1() )
- Class Utility_WinForms
... Functions and methods only related to Winforms / WinForm-Controls
(EG: Public Sub WinForm_Sub1() )
Now, what I would like to be able to do is to just add the Utility dll as a reference to any of my projects and be able to access the functions and methods from ALL 3 of these classes by simply typing in, for example:
Utility.Sub1
Utility.WebSub1
Utility.WinFormSub1
In other words, not having to type:
Utility.Utility_Web.Websub1
And making it so that the end-programmer doesn't need to know the internal structure of this utility, they can reference all it's methods / functions with just the Utility. nomenclature.
How would I go about doing that? Is this where NameSpaces come into effect? Inheritance? Partial Classes? Modules rather than classes?
There doesn't seem to be any reason for these methods to be in separate classes if they are going to be accessed using the same class name.
If you want to split the code across many source files for organizational purposes, you can use partial classes.
This seems like an excellent instance where you'd want to use partial classes, all using the same Utility namespace. That would allow you to access the methods with Utility.WebSub1 and reduce a step.
A class named Utility is a bad class from the start. What is its utility? What does it help you do? How many other people are going to name classes Utility?
Name your classes for what they do, associate them in the namespaces where they make logical and functional sense.
Let's say that you are making a set of static methods that help out with a class that represents a Month. Why not put the methods into Month? If you're writing methods to transform data from one representation to another, name it that way (ie, MonthDataTranslation).
Don't worry about typing on the part of your clients or your client code. Intellisense and the C# using statement mitigate that a great deal and given the choice between a badly named, nebulous Utility class and a long, well-named class, I will pick the latter every single time.
I have to write large amount of code which is going to be used in three asp.net pages.
I want to know the key points so that I can decide whether I should create Static Helper class , or create base class for common codes.
I am agree that creating single helper class vs creating multiple helper classes must be a careful job depending on various things like performance etc.., but the question still remain same , you can think me as a smart coder that can create perfect number of helper classes.
I think I am going to use these code only from these three asp.net pages.
Thanks for all your answers friends, but I need more inputs, can you please send more specific points.
Thanks.
If it is code that is being shared by all three ASP.NET pages and not by other code, a baseclass is a good idea.
The code is not exposed to the 'outside world' (by making the methods protected) and you define a context in which the methods should be used. They can only be called from an ASPX page that defines trough inheritance that it is-a certain base type where the methods make sense. A Helper method could be called from everywhere in your code by just passing the right parameters, even if this is conceptual invalid.
If it's code that's going to be called from different places (for example a ValidateEmail function) then a static helper class could help.
But if you opt for the helper class, you still have to decide how many helper classes you are going to create. Dumping all your helper functions in one class is probably not a good idea from maintenance perspective.
Create a base page and inherit from that and then put your helper method and properties on the base page.