I am trying to create a common library structure. I am doing this by creating separate projects for every common lib I want.
I have the following 2 namespaces: MyCompany.ERP and MyCompany.Barcode
I need both of them to have a class named Utilities and be static. If I do that I will then need to specify the full namespace name before my static class in order to access it.
Is there any other preferred way to do it?
Or I should go for different names in classes like BarcodeUtils and ERPUtils?
If i do that i will then need to specify the full namespace name before my static class in order to access it?
No, there is no need for that, though the details depend on the class that will use these types and the using declarations it has.
If you only use one of the namespaces in the class, there is no ambiguity and you can go ahead and use the type.
If you use both of the namespaces, you will either have to fully qualify the usages, or use namespace/type aliases to disambiguate the types.
using ERPUtils = MyCompany.ERP.Utilities;
using BCUtils = MyCompany.Barcode.Utilities;
public void MyMethod()
{
var a = ERPUtils.Method();
var b = BCUtils.Method();
}
There isn't any other way. You can make an aliases in using directives:
using MC=MyCompany.ERP;
using MB=MyCompany.Barcode;
...
public void Test()
{
var a = MC.Utilities.Method();
var b = MB.Utilities.Method();
}
It's the simplest way to manage them.
The MS guidelines have the following to say:
Do not introduce generic type names such as Element, Node, Log, and Message. There is a very high probability it would lead to type name conflicts in common scenarios.
and
Do not give the same name to types in namespaces within a single application model.
I concur that it's probably a good idea to use BarcodeUtilities and ErpUtilities instead. (Unless the utility classes are not meant to be used by client code, in which case you could name them Utilities and make them internal.)
"Utilities" is not a very good name for a class, since it is far too generic. Therefore, I think you should rename both of them to something more informative.
You can use an alias:
using BarcodeUtils = MyCompany.Barcode.Utilities;
on the pages you have clashes. But ideally rename them if this is happening in a lot of places.
I would suggest using different class names. If you really want to call both of them Utilities then you could use the alias feature on the using directive, e.g.
using ERP = MyCompany.ERP;
using Barcode = MyCompany.Barcode;
...
ERP.Utilities.SomeMethod();
Barcode.Utilities.SomeMethod();
You will have to use the full path when both are named the same. Otherwise you will get an ambiguous reference error.
You can use an alias however that will save you some typing:
using Project = PC.MyCompany.Project;
I would go for a different name that's somewhat more descriptive. A
It actually depends on the purpose of your classes. If you are going to distribute your Barcode.Utilities and ERP.Utilies seperately it is better stay like this. On the other hand, if you are going to use them only in same class, you may use 2. method for easiness of code.
Related
The unity documentation recommend to use namespaces to organize your code, avoid extended class name, and make more maintainable code.
ControlerCameraAction becomes Controleurs.Cameras.Action and CameraAction becomes Cameras.Action.
However in Unity editor you can't see your namespaces, only the last class name, and this can be confusing since some class have now same name.
Editor shows now Action and Action
So how to use namespaces in Unity?
Am I doing something wrong?
So how to use namespaces in Unity ?
Like you did, basically. Namespaces are used in code, not in the editor. The main problem of Unity is the way that scripts are treated. Scripts get compiled internally into debuggable IL-Code.
But in the editor itself, they are always named by their filenames, which are forced to be the same as the class name.
This is the reason you don't see your whole type-name (namespace + classname), but always the classname alone.
Am i doing something wrong ?
No, you aren't. As far as I remember, there is no way to display the classname instead of the filename in the editor, since the displayed data is determined by the meta-files that Unity generates.
So tl;dr:
You are doing it right and there is no way to display the namespaces in the Editor.
I'd suggest you should sort your scripts into folders and use the AddComponentMenu-Attribute to organize your code physically according to your namespaces. This is the same pattern that is used by Microsoft.
Easy way is to think in namespace how file folder. You assign your desired name avoiding similar name to systems and unity namespace. Each namespace inside another namespace is similar to navigate inside a folder inside another folder.
Ussually this start with your company name or your plugin name:
namespace mycompany_name
{
namespace myplugin_name
{
}
}
or
namespace myplugin_name
{
//part name i.e. Networking, Utils, Database or similar ramification
namespace myplugin_part_name
{
}
}
Later you reference to it in another script with "using":
using mycompany_name.myplugin_name
The unity documentation recommend to use namespaces to organize your
code, avoid extended class name, and make more maintainable code.
Yes !
ControlerCameraAction becomes Controleurs.Cameras.Action and
CameraAction becomes Cameras.Action.
Yes, and no.
The idea behind namespaces is organization not just simple use this feature called namespaces. And that organization should follow a logic. If every class has a different namespace then you will have to import as many namespaces as classes that you will use in your code.
You can think in terms of 'modules' or maybe see if a layered architecture can be useful for you.
If you have ControllerCameraAction and CameraAction, you can a.- use the namespace Cameras for both (then you will have Cameras.CameraAction and Cameras.ControllerCameraAction) , b.- if you have a layered architecture (like MVP, MVVM, or some more DomainDesign Driven, etc.) you can have namespaces using the layer name and the module. (then you will have something like Presentation.Cameras.ControllerCameraAction, Domain.Cameras.CameraAction and this can help you to follow an Onion architecture).
The syntax for namespaces are like this:
namespace Domain.Cameras
{
public class CameraAction
{
}
}
And you use them with using directive
using Domain.Cameras;
namespace Presentation.Cameras
{
public class ControllerCameraAction
{
private CameraAction cameraAction;
...
}
}
More about namespaces here!
By default all classes that don't have an explicit namespace belong to global namespace, so even when you are not writing any namespace you are using one.
Unity will not make any difference between namespaces, this is more a c# characteristic. And it helps with organization, separation of concerns principle, and avoiding name conflicts too, but in the last instance, your class names should still be representative and clear enough to understand what that class does. If you see Camera.cs and Camera.cs it's really hard to see what class does what. If you open those files and see the namespace/code/folder where they are that will help, but the idea is save those extra seconds/cognitive load and just be more explicit with your names.
As a complement here you can see another interesting discussion about namespaces use.
I always right click to resolve the namespace implicitly.
But for some namespace, I cannot resolve it implicitly and have to resolve it explicitly, leading to code like program1.logging.ErrorLogger.ErrorArise. Why can't I resolve implicitly?
Check this fiddle:
https://dotnetfiddle.net/6Px9BQ
The problem is, there are two or more classes sharing the same name, so its not implicitly possible to know which you refer to, hence you need to specifiy the name explicit, by providing its full namespace name.
If you dont want to specify long qualifiers all the time, you can shorten them like this:
Apple.Berry.Cheese.Cake cake = new Apple.Berry.Cheese.Cake();
shortened:
using abc = Apple.Berry.Cheese;
abc.Cake cake = new abc.Cake();
Visual studio gives you a lot of power and can easily let you pass over some concepts. One of the tools provided is that you can right click to add a using directive at the top of the code file which signals the compiler what class names will mean at compile time.
But if two namespaces have the same class name, and both are in use in the same class, then you have to explicitly tell the compiler in each case what to use.
I'm working on a C# library (let's just call it "Foo" for the sake of this question). It has some needs very similar to standard .NET needs: for example, it provides some drawing services, and some conversion services.
For the sake of familiarity and users of the library being able to guess what things are called, I'd like to follow the .NET standard, and name these parts of the library Foo.Drawing and Foo.Convert (and so on). But I'm finding that in actual use, this causes pain. People almost always have "using System;" at the top of each file, and when using this library, they want to have "using Foo;" as well. But now they have two Drawing and two Convert modules, and hilarity ensues.
For example, now instead of just using Drawing.Color for a parameter or variable type, you have to explicitly spell out System.Drawing.Color, or the compiler complains that Foo.Drawing doesn't have a Color type. Similarly, you want to use a standard Convert.ToInt32, you have to say System.Convert.ToInt32, even though you're already using System, because otherwise it finds Foo.Convert and fails to find ToInt32.
I understand why all this is as it is, but I'm still new to the C# community, so I don't know which is the most standard solution:
Leave it this way, and expect users to use fully-qualified names where necessary?
Rename the conflicting modules to something else (maybe Foo.Graphics instead of Foo.Drawing, and Foo.Conversion instead of Foo.Convert)?
Use some prefix on the standard names (Foo.FDrawing and Foo.FConvert)?
Something else?
Any advice from you more experienced C# gurus will be appreciated!
You can use namespace aliasing :
using System;
using FConvert = Foo.Convert;
public class Bar
{
public void Test()
{
var a = Convert.ToInt32("1");
var b = FConvert.ToInt32("1");
}
}
One of the main usage of namespaces is to avoid name clashing.
It means that namespaces allow developers to create types with identical names, as long as the belong to different namespaces.
A library usually have at least a root namespace, and possibly nested namespaces that logically groups the related types.
Name your types as you wish, as long as the names are meaningful and represent what the type really are. A client of your library expects a type named Animal to represent an Animal, not something else. The same applies for naming namespaces.
However, avoid at all cost the names from System, since it will be really annoying for your library clients (as you described) to deal with conflicting names all over the place.
A common way to deal with conflicting namesapces inside a class is to use namespace aliasing:
using FooConvert = Foo.Convert;
using BarConvert = Bar.Convert;
I've built a reusable Class Library to encapsulate my Authentication logic. I want to be able to reuse the compiled *.dll across multiple projects.
What I've got works. But, something about how I'm making the reference, or how my Class Library is structured isn't quite right. And I need your help to figure out what I'm doing-wrong/not-understanding...
I've got a Class Library (Authentication.dll) which is structured like this:
namespace AUTHENTICATION
{
public static class authentication
{
public static Boolean Authenticate(long UserID, long AppID) {...}
//...More Static Methods...//
}
}
In my dependent project I've added a reference to Authentication.dll, and I've added a using directive...
using AUTHENTICATION;
With this structure I can call my Authenticate method, from my dependent project, like so...
authentication.Authenticate(1,1)
I'd like to be able to not have to include that "authentication." before all calls to methods from this Class Library. Is that possible? If so, what changes do I need to make to my Class Library, or how I'm implementing it in my dependent project?
In C# a function cannot exist without a class. So you always need to define something for it, being a class for a static method or an object for an object method.
The only option to achieve that would be to declare a base class in the Authentication assembly from which you inherit in the dependent projects.
You could expose Authenticate as a protected method (or public works too), and call it without specifying the class name.
public class MyClassInDependentProject : authentication
{
public void DoSomething(int userId, long appId)
{
var success = Authenticate(userId, appId);
…
}
}
That said, you'll quickly find this to be a bad design. It conflates a cross-cutting concern with all sorts of other classes, and those classes are now precluded from inheriting from any other class.
Composition is a core principle of object-oriented programming, and we have the idiom "Favor composition over inheritance." This simply means that we break down complexity into manageable chunks (classes, which become instantiated as objects), and then compose those objects together to handle complex processing. So, you have encapsulated some aspect of authentication in your class, and you provide that to other classes compositionally so they can use it for authentication. Thinking about it as an object with which you can do something helps, conceptually.
As an analogy, think about needing to drill a hole in the top of your desk. You bring a drill (object) into your office (class). At that point, it wouldn't make sense to simply say "On," because "On" could be handled by your fan, your lamp, your PC, etc. (other objects in your class). You need to specify, "Drill On."
If you are making a class library in C# you should learn to use the naming conventions that exists: Design Guidelines for Developing Class Libraries
Here is how you should name namespaces: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/interface
C# is also an object oriented language, hence the need of classes (using Authentication as you should name your class).
It also seems like the data source is hard coded. Your class library users (even if it's just you) might want to configure the data source.
Google about singleton and why it's considered to be an anti pattern today (in most cases).
You are obliged to use Class in order to invoke your method, just
When is static class just NameClass.Method
When is not static, you must create instance, ClassName ob = new ClassName(); ob.Method();
The format of a call like this is class.method, and you really can't escape using the "class" moniker even with the "using" designation. Something has to "host" the function.
I don't think what you are asking for is possible without using the base class method Jay mentioned. If all you want is to simplify the syntax whenever you call Authenticate() however, this silly solution (adding an extra method in each class that needs to do authentication) may be just what you want:
private static void DoAuth(long UserID, long AppID){
authentication.Authenticate(UserID, AppID)
}
If the ID's are always the same within some context, you could also overload it:
private static void DoAuth(){
DoAuth(1,1)
}
Yes, this does mean you have to add more code wherever you want to do the authentication (that's why it's silly! ;) ). It does also however, also reduce this:
authentication.Authenticate(1,1);
...into this:
DoAuth();
I leave the cost / benefit analysis of this up to you..
I know I am some 3 years late but here goes nothing.
To keep your code cleaner and more readable you should create a new namespace for all the re-usable code that you want to have. Then in that namespace have the Authentication Class and Authenticate Function.
To use this you can easily set a using on your namespace and use the function as you are doing like
Authentication.Authenticate()
But to use
Authenticate()
by itself you can always do
using MyNamespace.Authentication;
and in your code use Authenticate Function directly.
This situation probably is not entirely uncommon to some of you: you have some functionality to put in a class but the perfect name (*) for that class is taken by one of the classes in the System namespace or other namespace/class that's not yours but you're using/importing.
(*) By perfect I mean small, concise and clear names.
For instance I have an Utils class that has a Diagnostics (mostly debug utils) class and a Drawing class. I could:
have a DrawingUtils class and a DiagnosticsUtils class, but that just smells like bad structure.
pick a thesaurus and be done with an worse, longer or awkward name that's casually still not taken.
Write class names in my native language instead of English.
Ask the smart guys at StackOverflow.
I think options 1-3 aren't promising :(
EDIT:
Since my chosen answer doesn't address the problem definitively (neither I do), what I'd recommend for people facing the same situation is to ask yourselves: Will you frequently use the conflicting BCL class/namespace? If no, then let your name conflict (as I did with Diagnostics). If yes, add a word that limits the possibilities of your class/namespace.
In practice, this means:
"Drawing": Something that draws.
"MyCustomControlDrawing": Something that draws only on MyCustomControl. e.g.: "WidgetDrawing".
EDIT2:
Another solution to take a look next time: Extension Methods (courtesy of Lawnmower).
I don't see any issue with keeping the names Drawing, Diagnostics etc. That's one of the purposes of namespaces, to resolve naming conflicts.
The beauty of namespaces is that they allow you to create classes with identical names. You can assign an alias to a namespace when you import it into your file with a using statement.
using MyAlias = My.Custom.Namespace;
this will keep your classes separate from Microsoft's.
you can then reference your classes as
MyAlias.Diagnostics
or you could alternatively assign an alias to Microsoft's namespace, but I wouldn't recommend this because it would confuse other developers.
To me, it really isn't worth the hassle of purposefully writing conflicting class names. You'll confuse other developers who aren't familiar with your codebase, because they will be expecting to use BCL classes but end up with yours instead (or vice versa). Then, you just waste their time when they have to write specific using aliases.
Honestly, coming up meaningful identifier names is a useful skill, but it isn't worth delaying your development. If you can't come up with something good quickly, settle for something mediocre and move on. There is little value in toiling over the names. I dare say there are more productive things you could be doing.
EDIT: I also don't believe that "small" is a component of a "perfect" identifier. Concise and clear, for sure, but if it takes a longer name to convey the purpose of a particular construct, so be it. We have intellisense, after all.
Use namespaces to disambiguate your classes from the classes in other namespaces. Either use fully qualified names or a using statement that tells the compile what you need:
using Type = MyReallyCoolCustomReflector.Type;
Now if you want to still use the Type class from the System namespace:
System.Type sysType = anObject.GetType();
Generally I try to avoid name duplicates but this doesn't always work out that way. I also like simple, readable and maintainable code. So as often it is a trade-off decision.
Well, if you want to avoid a namespace collision there are a couple of things you can do:
Don't collide, instead choose a unique name.
Example:
If you are creating a Math class you can name yours CamiloMartin.MathHelper
Use the long namespace to distinguish between collissions.
Example:
public class MyClass
{
public int SomeCalculation(int a, int b)
{
return MyNamespace.Math.SomeFunc(a, b);
}
}
Using an alias to differentiate.
Example:
using System.Math;
using SuperMath = MyNamespace.Math;
namespace MyNamespace
{
public class MyClass
{
public int SomeCalc(int a, int b)
{
int result = Math.abs(a);
result = SuperMath::SomeFunc(a, b);
return result;
}
}
}
Just for the record: .NET framework doesn't have neither Utils nor Diagnostics class. (But does have System.Diagnostics namespace.)
Personally I don't like general-purpose classes like Utils because their methods are not very discoverable (and usually either too general or too specific), therefore I would justify their use only as for internal classes.
As for the rest -- I agree with others on that namespaces are convenient. (Although I would thought twice to name the class if there is already a class in System with the same name, not because of name conflicts, but rather because the reason why I can't use 'original' class could mean that the class I'm about to create is semantically different.)
Often its possible to choose a more specific name. Take Utils for example. Absolutely everything can be called a utilitiy. For the reader of your code this classname is worthless.
Often utility classes are a collection of methods that didn't really fit anywhere else. Try to place them where they belong, or group them by some criteria, then use the group as a classname. Such grouping is in my experience always possible.
In general:
That's what we are doing (hey, we can refactor it later)
Used it once or twice but only on important classes. Especially useful if you don't know the 'perfect' name yet.
don't even think about this...
Using namespace aliases is no fun. So I avoid it if I can.