C# Nested Classes, Clean up Declaration - c#

Is there a way in C# to tidy up the following class declaration?
namespace Application.Namespace
{
public class MasterClass
{
public class FlyingSaucer
{
public class Rotator
{
public class Cube
{
Still maintaining the class structure, just cleaning up the declaration.

No - it's already pretty tidy, given that you've got 4 levels of nesting.
But you almost certainly shouldn't have 4 levels of nesting to start with. Why would you want to do that? You've got a class named subClass1 which isn't a subclass by the normal meaning (i.e. derived from another specific class; subClass1 is only derived from object.)
Nesting classes is fairly rare - I don't think I've ever seen even three levels of nesting, let alone four. Why do you think this is a good idea?

Are there any relationship between
FlyingSaucer -- >Rotator -- >Cube , i am thinking about it is a typical example of Containment.
FlyingSaucer Contains Rotator and Rotator Contains Cube.
so if that is the case , you may consider using Composition by creating properties of Rotator and Cube in FlyingSaucer.
You can inject these dependencies while creating an object FlyingSaucer. This will remove the very deep nesting in your classes and i think , you probably need to access objects of FlyingSaucer , Rotator , Cube from your master class.
so use Composition here it will really make your class hierarchy simpler and easy to extend and maintain.

it looks like you are confusing inheritance with sub classes.
sub classing is usually fairly rare.

Related

C#, is it okay to use nested classes for logical structure?

I am having a bit of a debate about the use of nested classes. The situation is that a class name makes sense to be repeated in two or more places, and while there is moderate similarity between each of the different instances, they are generally different. The nested classes are not often (if at all) needed beyond the scope of their parent class.
So then, rather than just coming up with three different class names, this seems to make more sense to me.
class A {
class B {
}
class M {
class B {
}
}
class Q {
class B {
}
}
The obvious problem with that is not functionality, but rather consistency/repetition. I was wondering if other developers have ever struggled with the same thing, and what some of the opinions were.
The .net Design Guide advises against it:
"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."
That's also what the base class library does: In the System.Web.UI namespace, you have DataGridItem, DataListItem, ListViewItem, MenuItem, RepeaterItem, etc. All of these could be called Item and nested inside DataGrid, DataList, etc. However, this would violate the two principles outlined above.
It looks okay when your classes are small. Once they get bloated, you really start thinking about moving them in separate files.
More to your point, if you want to use both A.B and M.B in the same code you have to always type A.B and M.B, which can be a pain.
If class B has any similarities between each inner class instance, would it make sense for you to abstract the similarities of B to a base class that exists alongside A, M, and Q? (I think so.) Then your inner classes, while they may have the same name, would be a little cleaner.
With that said, this type of structure can be seen for things like Metadata in an MVC application. In that instance you'd have something like:
[MetadataType(typeof(A.Metadata))]
class A
{
protected class Metadata
{
...
}
}
[MetadataType(typeof(B.Metadata))]
class B
{
protected class Metadata
{
...
}
}
In these case the inner classes each serve the same purpose but their implementations vary with each parent class. Also, with the Metadata definitions here, it makes a lot of sense to keep a class that helps describe its parent as an inner class. If there's any chance you might want to re-use the inner classes elsewhere then I would move them outside of their parents.
I think it's a little atypical to see this in practice otherwise. I'm sure there are good examples, but I bet there are more bad examples of this type of pattern.
I would say it is sometimes ok, but usually not a good design, to use private nested classes. I once refactored an existing very large class in my project to give it private nested classes. The reason why I did this was that some methods took dozens of parameters and this gave them a more logical grouping. In this sense I see nested classes as a good quick fix. It made sense because no one outside that class had any use for any of those fields.
Generally, I would shy away from using nested classes in an initial design - and think twice before considering them in a redesign. In maintenance, if you have the time, it is better to redesign the whole class and split them out into separate classes in separate files that are internal.
I think this strategy is also better for testability than using nested classes is. Due to greater dependencies with the outer class and other classes in the application, my refactored nested classes weren't much easier to unit test than the original large class that passed around many parameters. If you split nested classes so that they are on their own, you can write more discrete unit tests that actually test units rather than, effectively, combining the unit tests for the outer class and the inner class. This will give you more confidence in saying, "Yes, the inner class works at the unit test level" and "Yes, the outer class works at the unit test level" (which also tests how it fits together with the inner class, e.g. in computing formulas).
I understand your sample is sort of contrived. Still, if your class names are similar enough - or identical - you really shouldn't make them nested classes. As a general rule you should shy away from using nested classes at all.
If I'm remembering correctly, the .NET Framework Guidelines recommends against using nested classes as well. Nested Type Usage Guidelines is a little old (back to version 1.1), but the principles still apply.
Do not use nested types if the following are true:
The type must be instantiated by client code. If a type has a
public constructor, it probably should not be nested. The rationale
behind this guideline is that if a nested type can be instantiated, it
indicates that the type has a place in the library on its own. You can
create it, use it, and destroy it without using the outer type.
Therefore, it should not be nested. An inner type should not be widely
reused outside of the outer type without a relationship to the outer
type.
References to the type are commonly declared in client code.
Well you can use namespaces to do things like this too (just create a new folder in VS). Which is better for organising and will pretty much give you the same result.
But if the subclass is only relevant to the parent class then I don't see the harm in it.
Then again, if you are calling them the same thing I would guess they do a similar drop and you may want to look into abstraction, perhaps your parent classes could be done differently too. Really depends on what you need them to do though
I like doing that, for me it makes the use more clearer and especially finding names less of a problem. But usally i try to limit this on private classes or public enums.
For example
class Text {
enum Alignment
class UIElement {
enum Alignment
or
class Quadtree {
private class Node
class Octree {
private class Node
Don't create a nested class if there is any chance (or business reason) that you'll have to use it in some other place (use namespace instead and dot not hesitate to create class with long name if you need to).
For instance I use nested class for DTO between my controller and my view, or in a class to represent a cache entry.
If you want to name them the same but have different types you could use different namespaces.
Namespace1.MyClass{}
Namespace2.MyClass{}
This will end up with two different types despite the classes being named the same.
It really depends on the functionality of the nested class. That is very similar to the way the C++ STL defined iterator differently in each class. There's nothing wrong with the practice, per se, as long as the concept of each is truly different based on the encompassing class.
It can be, somewhat, a matter of style and taste, but personally I don't see an issue as long as they are truly different and dependent on the definition of the encapsulating class. It does tend to get more confusing, though, if they are publicly visible outside the class. Thus, I would not personally expose the classes publicly.
There's nothing inherently wrong about nested classes, as long as you stick to the following rules of thumb:
Never public or internal. There are special cases, such as when you're using a nested class to implement IEnumerator. But even then, the class itself should be kept private, since instances of it are being returned as IEnumerator, and it's really just being done as a way to avoid junking up the namespace with classes that aren't supposed to be instantiated.
Keep them small. A private nested class that's really just used for storing and passing around data in a more organized way is fine, and can sometimes be a very useful tool. (Not entirely unlike how anonymous classes are useful.) But if you're looking to use them to package up large chunks of functionality, it becomes a code smell that suggests you might want to consider refactoring the outer class instead.

When do we use a nested class in C# [duplicate]

This question already has answers here:
Why/when should you use nested classes in .net? Or shouldn't you?
(14 answers)
Closed 9 years ago.
Would like to know when it is right to uses a nested classes in C#?
Do we have incidents in which the use of it is unjustified and therefore not correct?
If you can give examples for both situations
Thanks
I find it's convenient to use a nested class when you need to encapsulate a format of data that is primarily going to be used within the parent class. This is usually because the purpose or format of the data is so bespoke to the parent class that it's not really suitable for wider use within your solution.
Here's a simple basic introduction to nested classes.
Nested_Classes
C# doesn't have a way to write a using directive to target a class, so that the static members of the class can be accessed without writing the class name as a qualifier (compare with Java's import static, which does allow that).
So for users of your classes, it is a little more convenient if you make any public classes as direct members of a namespace, not nested within other public classes. That way they can pull them into the global namespace with a using directive.
For private classes, go nuts, preferably put them close to where they are used to enhance the readability of your code.
I am not sure if there is room in my world for nested classes. It simply blurs the design for me. If you need to hide the information inside a class, why not just store it in member variables?
Besides, testing becomes more cumbersome without the ability to inject a stub in the place of the class.
User of Nested class is depending upon the scenario like below.
1) Organizing code into real world situations where there is a special relationship between two objects.
2) Hiding a class within another class so that you do not want the inner class to be used from outside of the class it is created within.
Suppose you have 2 classes called A and B and class B is depending upon class A without class A you cannot use class B # that scenario you can use nested classes
As per my knowledge
DataRow class is nested class for DataTable
i.e you cannot create a DataRow Class untill u declare a object of DataTable class
I find two main resons:
Personalize a class' name without ruining it.
Example: Vercas.ExplorerView, where I personalize the name of my class without ruining the meaning.
Private classes.
Example: Vercas.ExplorerView.Item is used only inside Vercas.ExplorerView.

Why can't my public class extend an internal class?

I really don't get it.
If the base class is abstract and only intended to be used to provide common functionality to public subclasses defined in the assembly, why shouldn't it be declared internal?
I don't want the abstract class to be visible to code outside the assembly. I don't want external code to know about it.
UPDATE: This question was the subject of my blog on November 13th of 2012. See it for some more thoughts on this issue. Thanks for the great question!
You're right; it doesn't have to be that way. Other OO languages allow "private inheritance", whereby the fact that D inherits from B can only be taken advantage of by code that has the ability to see B.
This was a design decision of the original C# designers. Unfortunately I am away from my desk right now - I'm taking a couple of days off for the long weekend - so I don't have the language design notes from 1999 in front of me. If I think of it when I get back I'll browse them and see if there is a justification for this decision.
My personal opinion is that inheritance should be used to represent "is a kind of" relationships; that is, inheritance should represent the semantics of the domain being modelled in the language. I try to avoid situations where inheritance is used as a code sharing mechanism. As others have mentioned, it's probably best to prefer composition to inheritance if what you want to represent is "this class shares implementation mechanisms with other classes".
By inheriting from a class, you expose the functionality of the base class through your child.
Since the child class has higher visibility than its parent, you would be exposing members that would otherwise be protected.
You can't violate the protection level of the parent class by implementing a child with higher visibility.
If the base class is really meant to be used by public child classes, then you need to make the parent public as well.
The other option is to keep your "parent" internal, make it non-abstract, and use it to compose your child classes, and use an Interface to force classes to implement the functionality:
public interface ISomething
{
void HelloWorld();
}
internal class OldParent : ISomething
{
public void HelloWorld(){ Console.WriteLine("Hello World!"); }
}
public class OldChild : ISomething
{
OldParent _oldParent = new OldParent();
public void HelloWorld() { _oldParent.HelloWorld(); }
}
I think the closest thing you can do is prevent other assemblies creating the abstract class by making its constructor internal, to quote from MSDN:
An internal constructor prevents the abstract class from being used as the base class of types that are not in the same assembly as the abstract class.
You can then try adding an EditorBrowsableAttribute to the class to try and hide it from IntelliSense (though, I've had mixed results using it to be honest) or put the base class in a nested namespace, such as MyLibrary.Internals to seperate it from the rest of your classes.
I think you're mixing concerns here, and C# is to blame, actually (and Java before it).
Inheritance should serve as a categorization mechanism, whereas it's often used for code reuse.
For code reuse it's always been known that composition beats inheritance. The problem with C# is that it gives us such an easy way to inherit:
class MyClass : MyReusedClass { }
But in order to compose, we need to do it by ourselves:
class MyClass {
MyReusedClass _reused;
// need to expose all the methods from MyReusedClass and delegate to _reused
}
What's missing is a construct like a trait (pdf), which will bring composition to the same usability level as inheritance.
There's research about traits in C# (pdf), and it would look something like this:
class MyClass {
uses { MyTrait; }
}
Although I'd like to see another model (that of Perl 6 roles).
UPDATE:
As a side note, the Oxygene language has a feature that lets you delegate all members of an interface to a member property that implements that interface:
type
MyClass = class(IReusable)
private
property Reused : IReusable := new MyReusedClass(); readonly;
implements public IReusable;
end;
Here, all interface members of IReusable will be exposed through MyClass and they'll all delegate to the Reused property. There are some problems with this approach, though.
ANOTHER UPDATE:
I've begun implementing this automatic composition concept in C#: take a look at NRoles.
I think this would violate the Liskov Substitution Principle.
In cases like this, I have used internal classes and prefer composition over inheritance. Is there anything about your design that prohibits containing all such functionality in your internal class, and then have your public classes contain an instance of this internal class?

Is it possible to have a private class?

I always wonder if it is possible to have a private class? And, what would be the point of having such class?
Thanks for helping.
Yes it is possible to have a private class, but only as an inner class of another class:
public class Outer
{
private class Inner
{}
}
This is usually useful when you want to encapsulate some logic inside of a class (the outer one), but need a more structured/OO design of code to implement it. I have used this pattern in the past when I need a container class to process some information within a method of a class, but the container class has no meaning outside of this logic. Making the container class a private inner class means that its use is localised to the outer class that utilises it.
It is worth noting that with this structure, the inner class has access to the private members of the outer class, but not the other way around.
Having private non-nested classes (Visible only to their namespace and child namespaces only) would allow to clean code boundaries while programming in the same assembly.
Having for example only an interface and a factory visible from other namespaces in the same assembly while still having all the implementation of the interface and utility classes (that no-one have business knowing out of the namespace) there.
It is still possible to do it somewhat with a big partial class replacing a namespace and nested classes inside but it's a very bad hack and unit testing become nearly impossible.
Yes you can - usually they are nested classes inside another type. This means you can aggregate logic into a nested class without exposing the class to anything else. Internal is also useful for nested classes.
Note however that there are some arguments against a design requiring nested classes - I tend to use them when they seem a good fit though.
You can have a private class, inside another class.
You may use a private class to encapsulate logic and implementation. For example you can declare an implementation of an iterator in your implementation of ICollection.

Building a new hierarchy, use an abstract class or an interface?

I'm preparing to build a 2D scene graph for my game, and i would like to know whether i should use at it's root an interface or two or a couple of abstract classes. Here's my requirements:
Base node item
needs to be able to store a matrix
also needs to be able to store a list
of child nodes
as well as a single parent node
Transform node items
needs to have a Draw method (implementation is highly probable to be the same)
requires that the base node item be
implemented/derived from
Drawable node item
needs to have a Draw method (implementation may be different)
requires that the base node item be
implemented/derived from and cannot
be implemented/derived from alongside
the transform node item
What scheme of base classes/interfaces should i use for this?
Jasonh covered the basics -- use the abstract class where you want to share code, otherwise use the interface.
I wan to add one point -- even if you go the abstract class route, I'd still recommend creating an interface as well. You never know when you'll want to have a subclass that acts like the others, but really needs to inherit another class for some reason. Abstract base classes are great to save implementation code. Interfaces are more flexible though, so unless there's a really good reason (ie. your testing reveals you can't take the performance hit of virtual method calls), use an interface as well as an abstract base class where it makes sense.
My general rule on this is: use interfaces to define the API, and use abstract base classes to allow implementations of the interface to share code.
Interfaces and abstract classes are used for two different things - interface are used for defining contract while abstract class are used to provide a base implementation and share common code. So you should definitly always use interfaces and sometimes (and I think your case is such a case) also abstract classes to avoid duplicating code.
So with interfaces only you will get the following.
class Transformation : INode, ITransformation { }
class GraphicsObject : INode, IGraphicsObject { }
I assume you can factor the common node specific code out into a base class.
abstarct class Node : INode { }
class Transformation : Node, ITransformation { }
class GraphicsObject : Node, IGraphicsObject { }
The differentiator would be if there's common code between all the classes that you can put into an abstract class and if they all need the same set of methods with this code. If this is the case, go with the abstract class. If there's no common code or you would end up making code common that shouldn't be common, then go with an interface.

Categories