naming issue with enums inside the class [closed] - c#

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 5 years ago.
Improve this question
I'm designing a namespace called ScriptLib. Inside ScriptLib, I have a base class Script with a few derived classes, including but not limited to SPoint and SWhiteSpace and a standalone class ScanGrid.
namespace ScriptLib
{
public enum ScriptType { Point, WhiteSpace }
public enum BoundaryPointMode { FourPoints, TwoPoints }
public enum GridSizingMode { EqualInterval, EqualQuantity }
public class Script
{
public ScriptType ScriptType { get; set; }
//other properties and methods etc.
}
public class ScanGrid
{
public BoundaryPointMode BoundaryPointMode { get; set; }
public GridSizingMode GridSizingMode { get; set; }
//other properties and methods etc.
}
public sealed class SPoint : Script
{
public new ScriptType ScriptType => ScriptType.SPoint;
//other properties and methods etc.
}
public sealed class SWhiteSpace : Script
{
public new ScriptType ScriptType => ScriptType.WhiteSpace;
//other properties and methods etc.
}
//more classes derive from Script and all use ScriptType
}
Script and all its derived classes use ScriptType, and ScanGrid use the other two enums.
At the moment I place them inside the namespace but outside the classes. However, I feel I pollute the namespace this way, since the enums are not used by all classes. Please note that I only started to work on this namespace; more classes and enums will come.
However, if I place ScriptType inside the Script class and the other two in ScanGrid, it leads to the naming problem. I'd like to keep the names for properties, so I need to come up with new names for the enums. Do I name them like: ScriptTypeType, BoundaryPointModeType and GridSizingModeType? To me they do not only read badly but also seem too long, especially the ones for ScanGrid. Imaging the following code:
scanGrid.GridSizingMode = _equalInterval.Checked ?
ScanGrid.GridSizingModeType.EqualInterval:
ScanGrid.GridSizingModeType.EqualQuantity
Is it common to put the enums directly under the namespace even though they are not used by all classes in the same namespace?
Is there a good way of naming the enums and referring to them if I place them inside the classes?

First of all, here is a quote from nested types usage guidelines:
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 when variables of the nested type need to be
declared in rare scenarios such as subclassing or other advanced
customization scenarios.
So basically it's a bad idea to put enums into class just to remove them from namespace. Also it's bad idea to expose nested enums via public members - you have public properties of nested enum's type. Now back to your question:
However, I feel I pollute the namespace this way, since the enums are
not used by all classes.
When you are declaring some enum (or another type) in some namespace, it does not mean this enum should be used by all classes in that namespace. E.g. there is enum DayOfWeek in System namespace. And it's not used by all classes in System namespace. It's not even used by most of these classes.
However, if I place ScriptType inside the Script class and the other
two in ScanGrid, it leads to the naming problem.
You have this naming problem, because you are using nested types as they are not supposed to be used. But you can simplify your life a little with C# 6 using static directive. :
using static ScriptLib.Script;
This directive imports static members and nested types contained directly in a type declaration. Thus you will be able to use nested types without name qualification:
scanGrid.GridSizingMode = _equalInterval.Checked
? GridSizingModeType.EqualInterval
: GridSizingModeType.EqualQuantity

Related

"friend" classes in C# and the state pattern [duplicate]

This question already has answers here:
Closed 10 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Possible Duplicate:
Why does C# not provide the C++ style ‘friend’ keyword?
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?
There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!
Example: To be placed in AssemblyInfo.cs
[assembly: InternalsVisibleTo("OtherAssembly")]
The closest equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:
class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
or if you prefer to put the Inner class in another file:
Outer.cs
partial class Outer
{
}
Inner.cs
partial class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.
In C++, make the Factory a friend of Widget class.
In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.
This involves a fair amount of tedium - exposing all the naturally public properties again in the interface.
There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
public class Class1
{
private int CallMe()
{
return 1;
}
}
You can invoke it using this code:
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."
You can simulate a friend access if the class that is given the right to access is inside another package and if the methods you are exposing are marked as internal or internal protected. You have to modify the assembly you want to share and add the following settings to AssemblyInfo.cs :
// Expose the internal members to the types in the My.Tester assembly
[assembly: InternalsVisibleTo("My.Tester, PublicKey=" +
"012700000480000094000000060200000024000052534131000400000100010091ab9" +
"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8" +
"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e" +
"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499" +
"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88")]
The public key is optional, depending on your needs.

Should I separate properties and methods in partial classes? [closed]

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
I'm writing the foundational classes for an application, and want to construct them properly for long term maintainability. To that end, I'm researching which design patterns to implement, use of interfaces, abstract classes, and separating persistence from activity. My head is swimming with patterns, paradigms, and principles.
I have a class Product for which I have created an interface IProduct. I believe I need to make Product and abstract class, because any instance of it is required to be one of half a dozen values for the property Category. So, my first question: is the following the appropriate way to do that?
abstract class Product : IProduct
{
// Fields
// Properties
// Methods
}
interface IProduct
{
// Properties
}
public class Model : IProduct
{
public Model()
{
Category = "Model";
}
// Model-specific fields
// Model-specific properties
// Model-specific methods
}
Articles I read, including questions previously answered here, indicate that I should design with separation of properties and methods (persistence and activity). To that end, should the above code really look like this?
abstract class Product : IProduct
{
// Fields
// Properties
// Methods
}
interface IProduct
{
// Properties
}
public partial class Model : IProduct
{
public Model()
{
Category = "Model";
}
// Model-specific fields
// Model-specific properties
}
public partial class Model : IProduct
{
// Model-specific methods
}
Of course, that presumes I got the first part right, but perhaps the answers will enlighten me on how I should be doing things.
Lastly, if separation of properties and methods is a good thing, and Product has some methods that are applicable across all concrete versions of it, should I move them to a separate abstract class like this?
abstract class Product : IProduct
{
// Fields
// Properties
}
abstract class Product : IProduct
{
// Methods
}
The only use I see in keeping partial classes is when two separate systems update the two files. This is true for example when using Visual Studio designers (the Windows Forms designer for instance), that update their own class file. Another thing could be true for another auto-generated class you have. One is maintained by the system, one by you.
I never ever felt the urge to have two separate partial class files I maintain myself. I usually use #region directives to split the methods and the properties.
Personally I prefer combining semantic-based and visibility-based approach to sorting members within a class. Actually I don't know who ever 'invented' the rule to sort out members based on the type of language entity (i.e. fields in a group, properties in a group etc.) That makes hardly any sense in respect to readability.
It is a good idea to use #region directives to separate them. Also, I tend to use horizontal lines (------…---) to make the code more readable.
Example:
public class SomeClass : ParentClass, ISomeInterface
{
#region ------ Large feature 1 ----------------------------
… // any non-private members related to 'Large feature 1' go here
#endregion
#region ------ Large feature 2 ----------------------------
… // any non-private members related to 'Large feature 2' go here
#endregion
#region ------ Implementation of ISomeInterface -----------
… // ISomeInterface implementation goes here, comments are *not* repeated
#endregion
#region ------ ParentClass overrides ----------------------
… // parent class members' overrides go here, comments are *not* repeated
#endregion
#region ------ Internals ----------------------------------
… // any private members, i.e. the actual implementation
#endregion
}
There is no reason to over-use partial declarations unless you really need to have them in separate files. A good reason is when a portion of the class is auto-generated. However, using partial declarations for the sole sake of separating members is far less readable and maintainable than consistent use of regions.
Also, I'm not a fan of separating property declarations and corresponding backing field declarations (in case you can't use auto-properties). The following is far more maintainable and readable:
public int SomeProperty
{
get { … return someProperty; }
set { someProperty = value; … }
}
private int someProperty;

Namespace vs nesting class [duplicate]

This question already has answers here:
Class.Class vs Namespace.Class for top level general use class libraries?
(7 answers)
Closed 8 years ago.
I am considering these two scenarios:
class StructuralCase
{
class Structure
{
...
}
class Material
{
...
}
class Forces
{
...
}
}
and
namespace StructuralCase
{
class Structure
{
...
}
class Material
{
...
}
class Forces
{
...
}
}
The thing is that inside "StructuralCase" I won't be declaring any instance variables, e.g., it will function as a "parent" for the rest of classes.
This lead me to consider converting StructuralClass to a namespace. What do you think about that? Is there any hard rule?
What you have are two different things.
First scenario class example:
You have an internal class with 3 nested private classes
In your second scenario namespace example:
You have 3 internal independent classes with no nesting.
If the classes should only be used within StructuralCase use the first example, otherwise if the classes are independent and have no relationship then the namespace is the way forward.
Generally, you want to use a namespace, if only because it enables using statements - otherwise you have to refer to the class by all nested classes (except inside the parent class itself, of course). Thus in case 1, outside reference would have to say
StructuralCase.Structure s = ...
instead of
using StructuralCase;
// ...
Structure s = ...
Functionally the only real reason to make a nested class is
So that the nested type has access to nonpublic members of the parent type. If this is a concern over API surface, see instead internal
So that the subclass isn't accessible outside the parent class, such as a specific struct used for results of a specific query
So that the child class can share some Generic Parameters from the parent class, such as factory classes which need the same generic parameters
I would just use Namespace, because you don't all the overhead of a class.
A class has more structure, variables, and methods, and offers layers of inheritance, but if you don't need them, don't use Class.

Creating a Namespace -> Class -> Nested Class? or

I was reading about creating classes and nested classes to determine what is the best approach for my needs, but I couldn't find something similar to what I need ( or couldn't understand it ;) ).
I will give you guys a (almost) real-life example:
Let's say I own a factory which manufactures different kinds of vehicles. So, my namespace would be Factory I figure.
Now, lets say the factory manufactures cars, boats and airplanes. So I will add three classes to my Factory namespace with those names.
Here is where my problem is with understanding the other methods:
I have some common things between the three types of vehicles. For example, they all have an engine (might be different HP or shapes which I understand are properties of the engine, but still they all have an engine). Also, cars and airplanes have doors (sometimes boats do too). On the other hand, they also have some unique things (airplanes have propellers for example that might come in different sizes or shapes).
Can someone please describe what I said in code so I could understand the differences between them?
Your question is a bit vague. Rather than try to answer it, I'll answer two related questions.
What is the purpose of a namespace?
The primary purpose of a namespace is to organize type declarations into a hierarchy so that they can be found by users easily.
The secondary purpose of a namespace is to provide a mechanism for disambiguating name collisions. That is, if XYZ Corp has a type Vehicle and ABC Inc has a type Vehicle, and PQR Ltd wants to use code from XYZ and ABC at the same time, the PQR programmers need a way to tell the compiler which type "Vehicle" actually refers to.
You suggest naming your namespace "Factory". That's probably a bad idea. A factory is probably a class, not a namespace. A factory is a kind of thing, not a way of organizing things. I would be inclined to name my namespace "Dementic.Manufacturing" and have it contain a Factory class. Now things are organized in two ways: first, by the company, Dementic Incorporated, that is producing the code, and by what the code is related to, namely, manufacturing. And it is unlikely that any competitor of yours will also make a namespace called Dementic.Manufacturing.
When should I make a nested type as opposed to a top-level type?
Make a nested type when the nested type is an implementation detail of the outer type. It is generally considered a poor practice to make a public nested type, though it is occasionally done.
A common example is an enumerator class; it is usually a private implementation detail of a enumerable collection.
You could stick all these in your Factory namespace.
A vehicle class would contain shared components, and classes for your specific vehicle types would inherit from the vehicle class... is that what you're asking?
public class Engine
{
public int HorsePower {get;set;}
}
public class Vehicle
{
public Vehicle() { }
public Engine Engine;
public int Doors;
}
public class Airplane : Vehicle
{
public Airplane () { }
public string PropellerModel;
}
public class Boat : Vehicle
{
public Boat () { }
public string RudderModel;
}
If you want to be as generic as possible, you can approach it something like this:
namespace Factory
{
public interface IDoor { }
public interface IEngine { }
public interface IPropeller { }
public abstract class Vehicle
{
public ICollection<IDoor> Doors { get; protected set; }
public ICollection<IEngine> Engines { get; protected set; }
}
public class Airplane : Vehicle
{
public ICollection<IPropeller> Propellers { get; protected set; }
}
}
Then have the specific concrete types provide the relevant collections to the supertype properties.
This is a bit of a hack, but modeling any real-world objects as classes in a programming language is going to break down sooner or later.
Note that I've made the engine property a collection too. This is to support, for example, the Prius class, which would have two engines.
An alternate approach would be to define the vehicles in terms of interfaces, somewhat like this:
namespace Factory
{
public interface IDoor { }
public interface IEngine { }
public interface IPropeller { }
public interface IDoorProvider
{
ICollection<IDoor> Doors { get; }
}
public interface IEngineProvider
{
ICollection<IEngine> Engines { get; }
}
public interface IPropellerProvider
{
ICollection<IPropeller> Propellers { get; }
}
public abstract class Vehicle { }
public class Car : Vehicle, IDoorProvider, IEngineProvider
{
public ICollection<IDoor> Doors { get; protected set; }
public ICollection<IEngine> Engines { get; protected set; }
}
// And so on...
}
This approach has the advantage that you don't have to define much on Vehicle itself, but this also means that you can't easily share the definitions of these members across all of the classes. However, this prevents you from defining members on the base type that are not relevant to the concrete types.
You have the wrong concept of what namespaces are. Namespaces have nothing to do with this.
I think you're also confusing inheritance and factories. Again, those are very separate ideas.
First think about creating your class heirarchy with the common base class that provides the basic structure of your objects and then the specialized subclasses that provide the specific details. And be careful not to use inheritance unless it truly works. Don't force your model into an inheritance heirarchy if it doesn't make sense.
Then you can worry about creating one or more factories to create instances of these objects.
As for namespaces, a namespace is just a way to group related pieces of code together in a logical, meaningful way. You might have a factory namespace, but you could just as well have a "factories" namespace or a "vehicles" namespace or something completely different which is relevant to your domain.
Since the person asking the question might actually get some value out of it, here my take:
If your software deals in some ways with objects of the real world, don't try to model the set of classes that represent the core of your application according to the real world. Rather, let the requirements of the software guide as to how your objects will look like.
For example, is this an order management system?
In that case it may be more relevant that certain orderable items have other orderable items directly associated with it. For a boat you can order certain parts, engines, etc. That is, it may more important to express the relationships between orderable items instead of having them available as concrete types.
For example, is it a tool to draw new boats, planes, propellers, etc.? Then a more relevant base class maybe that of a shape. Is it more about calculating the power of an engine or the efficiency of a propeller? Then you may need some concept of mathematical bodies and additional physical relationships and characteristics need to be defined between the different objects.
Lastly, as a rule of thumb you can think of inheritance as a somewhat overrated concept in that it is the first thing that starters think of when touching OO. The predominant concept of reuse in nature is composition - ultimately all natural things are composed of small items with very clear interfaces. Ideally, you will try and compose your OO application in a similar fashion.
I would rather go for VehicleFactory namespace, Factory as a class (there are many design patterns addresing the problem of creating objects and usually this needs to be a class, or at least (usually in non-objective programming) function. Namespace won't provide you this.

Why Interface support multiple inheritance and class doesnt in c# [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why C# doen't support multiple inheritance
Should C# include multiple inheritance?
i like to what is reason for interface support multiple inheritance and class doesnt support
I would rather 'negate' your statement.. "interface support multiple inheritance".
Interface is NOT actually inheritance, it is JUST a "contract" of service/behavior that a class abides with.
By implementing an interface a class does NOT inherit anything per se.
And since a class/entity can bind with multiple contracts (behaviours), we can implement multiple interfaces in a class.
Because these are conceptually two totally different things.
If you inherit from a class, you inherit the code of the base class.
If you implement (not inherit!) an interface, you force your implementing class to have some predefined method/event/property signatures.
While multiple inheritance for classes is a notorious source of errors and confusion, having many interfaces in a class' inheritance list is about combining various behavioural aspects, and as such it is an important instrument for component-based programming.
Or, in other words: It is an implementation of the Favour Composition over Inheritance design principle.
Thomas
I'd be very interested in a more authoritative answer, but here's my take.
In languages that support multiple inheritance, the key ambiguity that is (arguably) unsatisfactorily resolved is what happens when you subclass from two types that both define a method with the same signature. For example:
public class BaseClass1
{
public string SomeMethod()
{
return "Implementation1";
}
}
public class BaseClass2
{
public string SomeMethod()
{
return "Implementation2";
}
}
public class MySuclass : BaseClass1, BaseClass2
{
}
Now what does the following return?
MySubclass mySubclass = new MySubclass();
string s = mySubclass.SomeMethod();
In C#, explicit interface implementation allows you to easily resolve this by definining both. After converting BaseClass1 and BaseClass2 to interfaces, we can have
public class MySuclass : IBaseClass1, IBaseClass2
{
string IBaseClass1.SomeMethod()
{
return "Implementation1";
}
string IBaseClass2.SomeMethod()
{
return "Implementation2";
}
}
The key of course being that there is no ambiguity with this syntax as it's not possible to access SomeMethod without first casting the target to either IBaseClass1 or IBaseClass2.

Categories

Resources