I have a class called SimpleCommand. It is a single file class that implements ICommand in a very simple way (hence the name).
I am finding that I am putting it several of my projects. (I just copy the code and add it into the project.)
These projects are all in the same solution and resulting wpf application.
My question is: Aside from increasing the size of my DLLs by a bit, what are the drawbacks to copying this code around?
(I am trying to decide if it is worth the work to put it in a nuget package.)
NOTE: I have not changed this code in years, and I don't plan to.
The issue here isn't that there are various classes with the same name in different namespaces.
The issue is that you're duplicating code, which is really bad idea.
If you want to expand your SimpleCommand to ABitMoreComplexCommand you end up copying it all over.
If you need to compare one command to another by type you couldn't do that reliably - heuristics you may implement could give you false positives
Bottom line: make another project, put all reusable code there, don't copy it around
Copying and pasting is the most innefficient way of reusing code, IMO. What happens if you ever decide to add a simple bool property to this class? you will have to do it as many times as you ever copied and pasted it.
I suggest to group these reusable parts in a single DLL and reference them from multiple projects, instead.
Related
I'm working on a Visual Studio solution that currently has two projects in it (with more to come later). One project is a mature C#/Winforms application that I built last year (think of it as the prototype). The other one is a DLL that is going to do the same thing as the prototype but through a different application. I'd like to re-use code from the prototype (let's call the method in question SyncInvoices() ) in the DLL because the prototype code works perfectly b/c I've hammered the bugs out of it. The class that contains SyncInvoices is baked into the prototype application instead of being its own DLL.
I've added the class that contains SyncInvoices() to the DLL's project (as a linked file, since it already exists elsewhere in the solution). I can instantiate that class in the DLL project and call SyncInvoices() but the compiler throws errors related to GUI elements.
The problem is that SyncInvoices() has some-thread safe calls to the Prototype application's GUI in it, basically used to pass messages/errors back to the interface.
The DLL doesn't have a GUI, so it doesn't need to run that code. It still builds the rest of the methods in that class, even though they aren't used. Is there a way I can tell the compiler to ignore those lines when building the DLL? I'd rather not maintain two sets of nearly identical code, especially when the two projects are part of the same solution.
I thought about using #define/ #if blocks to partition off the code but I'm not sure if C# works that way-- most of the time I've seen those used is to keep debug code from ending up in production. If it is possible to tell the app to include/exclude code through #if blocks, how do I set the values?
Should I just bite the bullet and make a copy of the method without the offending code in it?
Without more specifics it's hard to give the correct answer, but I'd say generally you'd handle this with events. Whatever calls into the GUI are happening in the prototype, that would typically be some form of event, which you would subscribe to in the prototype when you instantiate your new class.
Are there any particularly problematic cases you could give more specifics on?
I want to compile each individual form on my application to be used sort of as a dll on its own... I looked into this and found very confusing representations of assemblies, which may or may not be what I wanted.
Is it possible to compile the form1.cs, form1.designer.cs and form1.resx to be 1 single file which then will be able to be used as a dll. I use "dll" as an example because that is the functionality I need with each of these forms when compiled to a single file, I need to be able to call it and use it from a shell application.
I know it is possible in VS to create a separate project which will compile into a dll but with something on the verge of 80 forms to compile... it will be a messy thing to maintain. So basically, is there an easier way?
this is the closest code I could get, but it is in console, so it will be impractical if there are easier ways... also I am not sure if it will actualy compile form1.cs, form1.designer.cs and form1.resx and still work as a dll
csc /target:library /out:MathLibrary.DLL Add.cs Mult.cs
Thanks for the help
Possible? Yes. Advisable? Umm, not sure.
You must study the CSC options to use it in such a massive way.
Partial classes are simply each listed among the sources. See here
The RESX file must be compiled by ResGen.exe to a resources file see here
You will use the /References parameter to include other DLLs.
The real challenge will probably come when you try to get cross references to work, depending on the layout of your application. Is there a main hub that will control all forms? Is it a plug-in architecture?
Good luck
Basically, you are working with solution. It can contain multiple projects. For each dll, you must have one project. So create 80 projects, add to each of them single form, edit it, add some logic.
Then there will be a main project, which produce exe. You can reference all dlls in that project, but better don't. If you do, updating any of dll will required recompiling that exe too. You can load them dynamically or use sort of plugin system (to enumerate dlls, understand their purpose, etc). Then you obtain Type from assembly (loaded dll), create instance (which will call constructor, which calls InitializeComponents, which loads form resources) and display form.
Regarding abstraction, you surely need something. To example, login window. You can create a generic form with some focus, user interface and user interaction logic. But it has to communicated with main project (which encapsulate encryption, password storage model, user rights, etc). One easy way to do this is to provide 2 interfaces:
interface ILoginImplementation
{
public void SetInitialUserName(string name);
}
interface ILoginLogic
{
public bool TryAuthenticate(string name, string password);
}
Implementation is what your form must implement and Logic is what main project implements and supply when instantiating login form.
I realize this is probably not ideal, but I still think your best bet is to use Visual Studio and create a separate project for each .dll to be created.
By right clicking the Solution node and selecting Add > New Solution Folder, you can at least organize your projects into a somewhat more orderly hierarchy. That alone might go a long way to make your project more manageable.
PS: If you haven't already, you should definitely try to create an interface, or a base class (or both!) that each of your Form-classes can derive from or implement. If you're able to abstract away and generalize some of the logic, it is quite likely to save you a lot of work down the road.
I need to declare an attribute for coverage exclusion in my code, the issue is that i have a project group and i wish to create it somewhere where i can access it from all projects when i need it, right now i have it outside of the namespaces so it would be easier to use, and its declared in each project like:
public class CoverageExcludeAttribute : Attribute
{
}
is there any better way to achieve this goal in a way it could be access anywhere in my project group and declared only once, without having to add its namespace (e.g by using the global namespace) to each file i use the attribute in?
Thank you
While I actually agree with P.Brian.Mackey, I think the only way to do it is exactly as DjKraze said:
Create a new micro-project of type ClassLibrary, add a single .cs file with your Coverage(..) class and ensure that class is inside no namespaces block. Then build it and for each one of the other projects do a Add-Reference to that micro-project you just created.. That way it will surely work, and you will have a handy place to put any further 'common code' to be available everywhere.
However, each project will have to be updated with the reference. This is the minimum requirement - all in all, if you want to use anything instead of copying, it must be referred..
Sorry, almost no other options for such thing!
The other way is to .. ugh, copy. You can easily set up a simple pre-build script that will copy given .cs file to each one of your projects, but "adding" the file to the .csproj's build list is a bit harder, still possible with use of some Ruby or Python or friends...
Hm.. saying that, It may be possible to write a pre-build script to inject a reference to the micro-project automatically.. But I wont know if this is worth doing. Do you have more than 50-100 projects? Else, probably it's not worth..
This only applies to VS2010 and above
If you want some source code defined in each of your projects, but without a project reference, take a look at some of the functionality provided by NuGet, especially Source Code Transformations. These allow the addition of some source code to the project when you add the NuGet package to the project.
You can use Dependency Injection
http://en.wikipedia.org/wiki/Dependency_injection
The most popular are: Microsoft Unity, Ninject, NHibernate, StructureMap, Autofac.
Good luck!
If I'm dealing with one class and one public struct (not nested), Should I create a separate .cs just for the struct? Or leave it un-nested in its .cs file of the class? (This is assuming the struct relates to the class, but isn't so exclusive to the class that it should be nested and declared private)
Edit: I removed my initial question about two classes because I found C# classes in separate files?
Note that the only person(s) that can accurately answer this question is you, and your team. If your team is happy to find several related types inside a single file, combined due to ... whatever... then what I, or whomever other person, says, should be just ... irrelevant.
In any case, I would turn the question upside down:
Is there any reason to place two separate types (related by names, functionality, or whatever, but separate nonetheless) in the same file
and I've yet to come up with a good reason.
There are extensions/addins to Visual Studio where you can type in the name, and quickly navigate to the file, and I can think of three, but there are undoubtedly others:
DPack
ReSharper
CodeRush/Refactor! Pro
The first allows you to quickly navigate to a file by name. If you know the type, but have people putting multiple types into the same type, this will not be helpful, at all.
The second and third, lets you navigate to a type by name, but you shouldn't rely on people having those, or knowing how to use them.
To that end, I would advocate following these rules:
Project names should be identical to the root namespace of that project. I differ from this point myself where in some cases I name my projects "...Core", and I then remove "Core" from the namespace, but otherwise, leave the project name identical to the namespace
Use folders in the project to build namespace hierarchies
The name of a type should correspond 100% to the name of the file + whatever extension is right for your language. So "YourType" should be "YourType.cs", "YourType.vb" or "YourType.whatever" depending on language
That depends on who you ask.
I, personally, find it easier to read if they are all, always, broken out. However, the compiler doesn't care... so whatever you and your team agree is easier to understand.
In my opinion it's a good practice to avoid that. Some day a developer will be looking around for ClassBar in the project and won't be able to find it easily because it's nested in ClassFoo.cs
Tools like Resharper have a neat feature where you can just select a class, right click, place in new file to make this easier.
If you read any of the popular coding standards (Lance Hunt, iDesign, Framework Design Guidelines etc) most of them advocate 1 class per file.
Its annoying to scroll down and search for how many class each.cs file contains/hides.
Maintainability issue while using version control
Usability with our team.
Check here for more interesting discussion on same.
I think it was less about whether you can or whether you should. For things like this, I feel it's best to look to the convention in the rest of the codebase. Sometime conformity is better because it makes other developers jobs easier becaues everybody knows where things are.
If it's entirely new project and you are setting the standards here by yourself, do what makes sense to you. To me if the struct has no use outside the related class, I may put them in the same file. Otherwise, I seperate them out.
Is it good practise to have multiple class definitions in one file? or is it preferable to have one class per file?
I prefer one class per file. You'll never have to search for the correct filename because it is always the class name.
One class per file.
That way you can avoid having to merge edits when two people have to edit the same file because one is working on class A and the other is working on class B. While this should be automatic in any source control system, it's an extra step that can be missed which would cause problems.
Far better to have a process that didn't allow this sort of error to occur in the first place.
I do not see any issue with multiple classes in the same file, as long as the classes are related to each other.
If you have resharper, you can always use the navigation tools to find any class.
It is generally best practice to have one file per class.
Some folk, not me, like to have more than more one if they are related and very very small in size. Others might do this in a prototyping stage. I say start and stay with one per file as does Scott McConnell in his discourse on Class Quality in his seminal book Code Complete
To quote, "Put one class in one file. A file isn't just a bucket that holds some code. If your language allows it, a file should hold a collection of routines that supports one and only one purpose. A file reinforces the idea that a collection of routines are in the same class."
I think it's preferable to have one class per file and to organize them in folders having the same hierarchy as their namespaces.
Most programmers would consider one class per file to be a best practice.
Usually - no.
Following practice "one class per file" simplifies browsing of solution.
Additionally if you have a big team of developers and source control tool that uses pessimistic approach (exclusive locks) - your developers will have hard time while working on the same file.
I guess it is down to preference as you said.
I think you'll find most online examples/ most code is one class per file for easy management.
I sometimes put 2 classes in a file - only if i'm using the second class as an entity and it's only being used in the first class.
I guess you ask because you've noticed already that it's considered best practice. Given the obvious benefits (and some less obvious ones mentioned here), why would you want to do it differently? Are there any benefits at all in multiple classes per file? I can't think of any.
Usually it is the best solution to have one class per file (with the file named exactly like the contained class).
I only differ from that if
There are lots of small enumerations ->I collect these into a single file e.g. Enums.cs
There are lots (20+) of generated classes/interfaces that directly relate to each other ->Into one file E.g. Interfaces.cs
There is stuff that is no direct functional part of the application and in close semantic consistance (e.g. everything you need for interop. Thats usually a few structures, enums, constants and a single class) -> That goes into a single file named after the interop class.
Private inner classes -> Stay with their parent class instead of partial classes
I would say no, i know devexpress hates it aswell ( It has some detection bad practives).
But i do have it sometimes, when its a very small class thats basicly only used by the "main" class in the file. Personaly i think it comes down a bit to taste, there is a balance between having 10k lines long .cs files or having to many .cs in your project.
I think in terms of it being a "best practise" approach then probably yes. However, really it depends on the project. I tend to group related code into separate units for example:
MyApplication.Interfaces
MyApplication.Utils
MyApplication.Controllers
I really think a class only ever deserves it's own unit if it becomes huge. However, if it does get to this stage, you should start to consider moving some code into helper classes to separate the logic.
I would have to agree with most on this. One class per file is ideal. It makes it easier to see what's available in a project without having to rely on intellisense to discover types that are available in a given assembly.
I think the only time I ever fudge on the one class per file rule is when I'm defining a custom EventArgs class and it's related to an event that's fired from another class. Then typically I would define those in along with a delegate for the event in the same file. I don't know that it's a good practice one way or another or just out of sheer lazyness??
If you work on a very large project, too many files can slow down your build times significantly (at least with C++). I don't think that rigid adherence to a rule is necessarily the way to go.
One Class Per File is my Preferred approach, it helps me get rid of any confusion later on... I tend to use a lot of partial classes though...
As long as I dont break the 1000 line barrier, I'll stuff in as many related classes that makes sense.
Sometimes an abstraction may only be one overridden method.