We have a massive code set, so each of the classes is of the form:
public class A :
DPM<Time, Data, TypeAKindA,
TypeAKindB, TypeAKindC,
TypeAKindC, TypeAkindD, TypeAKindE>
public class B:
DPM<Temp, Data, TypeBKindA,
TypeBKindB, TypeBKindB,
TypeBKindC, TypeBKindD, TypeBKindE>
So Time is specific struct for example which differs from Temp.
The problem, is for each of these classes I have an init, constructor, so for example in the init, I am doing this specific to the class name. I.e. A goes off and does something specific for each class.
This is a massive code-set so I cannot re-factor. I'd like to combine these, so I have one class call it C, that will basically either execute the functionality of each or somehow merge them. I cannot change class DPM, and this is a complex structure with plenty of where clauses in it.
It looks like this:
public abstract class DPM<TypeA, TypeB, TypeC, , ... > : ID
where ID is an interface.
An example of the issue is the class DPM inherited has a property called _xyz which is populated with different values in .init() depending on whether it is called from Class A or Class B. And I don't know the dependencies downstream - so where is called or used later in the code.
Any suggestions very welcome.
So you cannot refactor, but you are trying to refactor it. You will need to rename any common properties of differing types. Of course, this begs the question of whether you should do so.
I would suggest that chaining additional types onto the class definition would only make matters worse. That being the case, you could possibly refactor to common interfaces. Have you considered posting a more detailed question on StackExchange's CodeReview site?
Related
I have a Common class
say
Public class Trans
{
//Access modifiers like the following 20 are there and 20 methods
protected internal string TopVenueCd
{
get { return this.Ticket.GetValue("venueCd", "").TopOne().GetStringValue(); }
}
}
I am inheriting this class to where ever i need.
But in that in all the classes where i am inheriting i dont need all methods.
So I can create that as a static class and access it where ever it is required..
Which is wiser ?
And please give reasons for that as i am not clear in depth in oops in performance..
Thanks for all replies..
UPDATE
My Aim is to segregate one Collection related process separately in a class.
( I am using mongoDb ) One Important Collection which is heavily used and it s a big one with nested document.
Still the schema is not fixed and freezed. Still working on it to get a better solution.
So if i take the logical manipulation of that particular Collection separately in a class, if i change the schema i can change only this class.That is intention.
Since i m a beginner in C#, oops this question arise..
How to do this segregation well in best practice ?
Inheritance is so much misused as a "copy stuff into my class"-feature. It should be used for real inheritance situations (is-a-relation).
If static methods work as well, definitively use that. Use extension methods to make your static methods easy to find.
Why?
Because inheritance is the much higher coupling. You couldn't easily decouple it by using interfaces and injected services in the future.
While you can access static methods from many helper classes, you can only have one base class. If you need more stuff in the future, your base classes will become too big. Because you always inherit everything, all your classes become too big.
When you need a base class for real inheritance in the future, you can't give your class another base class anymore.
Therefore, simply do not use inheritance if in doubt. There are rare really good applications of inheritance.
There might be a problem with your design if you need to inherit a class when you don't need all the methods.
It might be that your base class is a God object, and it has too much responsibilities, or that you have lumped up a few non-essential functionalities into a common base, which is a violation of the Interface Segregation Principle.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I will write code in which I need class which holds methods only. I thought it is good idea to make class static. Some senior programmer argue that do not use static class. I do not find any good reason why not to use static class. Can someone knows in C# language there is any harm in using static class. Can static class usage required more memory than creating object of class? I will clear that my class do not have single field and hence property too.
For further information I will explain code also.
We have product in which we need to done XML handling for chart settings. We read object from XML file in class Library which holds chart related properties. Now I have two Layers first is product second class Library and XML related operations. Actually senior programmers want independent class to read and write XML. I make this class static.
In another situation I have class of chartData. In that class I want methods like whether Line of Axis,series of chart is valid or not. Also whether color of chart stores in ARGB format or plain color name. They do not want those methods in same project. Now can I make class static or create object.
If your class does not have to manage state then there is absolutely no reason to not declare it static.
In C# some classes even have to be static like the ones that have extension methods.
Now if there's a chance that it requires state in the future, it's better to not declare it as static as if you change it afterwards, the consumers will need to change their code too.
One concern is that statics can be harder (not impossible) to test in some situations
The danger of static classes is that they often become God Objects. They know too much, they do too much, and they're usually called "Utilities.cs".
Also, just because your class holds methods only doesn't mean that you can't use a regular class, but it depends on what your class does. Does it have any state? Does it persist any data that's being modified in your methods?
Having static classes is not bad, but could make you think why you have those methods there. Some things to keep in mind about that:
if the methods manage behavior for classes you have in your project, you could just add the methods to those classes directly:
//doing this:
if(product.IsValid()) { ... }
//instead of:
if(ProductHelper.IsValid(product)) { ... }
if the methods manage behavior for classes you can't modify, you could use extension methods (that by the end of the day are static! but it adds syntactic sugar)
public static bool IsValid( this Product product ) { ... }
//so you can do:
if(product.IsValid()) { ... }
if the methods are coupled to external services you may want to mock, using a non-static class with virtual methods or implementing an interface will let you replace the instance with a mock one whenever you need to use it:
//instead of:
StaticService.Save(product);
//you can do:
public IService Service {get;set;}
...
Service.Save(product);
//and in your tests:
yourObject.Service = new MockService(); //MockService inherits from your actual class or implements the same IService interface
by the other hand, having the logic in non-static classes will let you make use of polymorphism and replace the instance with another one that extends the behavior.
finally, having the logic in non-static classes will let you use IoC (inversion of control) and proxy-based AOP. If you don't know about that, you could take a look at frameworks like Spring.net, Unity, Castle, Ninject, etc. Just for giving you an example of what you could do with this: you can make all the classes implementing IService log their methods, or check some security constraints, or open a database connection and close it when the method ends; everything without adding the actual code to the class.
Hope it helps.
It depends on the situation when to use static classes or not. In the general case you create static classes when you do not need to manage state. So for example, Math.cs, or Utility.cs - where you have basic utility functions - eg string formatting, etc.
Another scenario where you want to use static is when you expect the class to not be modified alot. When the system grows and you find that you have to modify this static class alot then its best to remove the static keyword. If not then you will miss out on some benefits of OOD - eg polymorphism, interfaces - For example you could find that I need to change a specific method in a static class, but since you can't override a static method, then you might have to 'copy and paste' with minor changes.
Some senior programmer argue that do not use static class.
Tell him he is a traineee, not even a junior. Simple. The static keyword is there for a reason. if your class only has methods without keeping state - and those cases exist - then putting them into a static class is valid. Point.
Can someone knows in C# language there is any harm in using static class.
No. The only valid argument is that your design isbroken (i.e. the class should not be static and keep state). But if you really have methods that do not keep state - and those cases exist, like the "Math" class - then sorry, this is a totally valid approach. There are no negatives.
This question already has answers here:
Why/when should you use nested classes in .net? Or shouldn't you?
(14 answers)
Closed 10 years ago.
In this stackoverflow answer a commenter mentioned that "private nested classes" can be quite useful so I was reading about them in articles such as this one which tend to explain how nested classes function technically, but not why you would use them.
I suppose I would use private nested classes for little helper classes that belong to a larger class, but often I will need a helper class from another class and so I would just have to take the extra effort to (1) make the nested class non-nested or (2) make it public and then access it with the outer-class prefix on it, which both seems to be extra work without any added-value for having the nested class in the first place. Hence in general I really don't see a use case for nested classes, other than perhaps to keep classes a bit more organized into groups, but I that also goes against the one-class-per-file clarity that I have come to enjoy.
In what ways do you use nested classes to make your code more manageable, readable, efficient?
You've answered your own question. Use nested classes when you need a helper class that is meaningless outside the class; particularly when the nested class can make use of private implementation details of the outer class.
Your argument that nested classes are useless is also an argument that private methods are useless: a private method might be useful outside of the class, and therefore you'd have to make it internal. An internal method might be useful outside of the assembly, and therefore you'd make it public. Therefore all methods should be public. If you think that's a bad argument, then what is different about you making the same argument for classes instead of methods?
I make nested classes all the time because I am frequently in the position of needed to encapsulate functionality in a helper that makes no sense outside of the class, and can use private implementation details of the outer class. For example, I write compilers. I recently wrote a class SemanticAnalyzer that does semantic analysis of parse trees. One of its nested classes is LocalScopeBuilder. Under what circumstances would I need to build a local scope when I am not analyzing the semantics of a parse tree? Never. That class is entirely an implementation detail of the semantic analyzer. I plan to add more nested classes with names like NullableArithmeticAnalyzer and OverloadResolutionAnalyzer that are also not useful outside of the class, but I want to encapsulate rules of the language in those specific classes.
People also use nested classes to build things like iterators, or comparators - things that make no sense outside of the class and are exposed via a well-known interface.
A pattern I use quite frequently is to have private nested classes that extend their outer class:
abstract public class BankAccount
{
private BankAccount() { }
// Now no one else can extend BankAccount because a derived class
// must be able to call a constructor, but all the constructors are
// private!
private sealed class ChequingAccount : BankAccount { ... }
public static BankAccount MakeChequingAccount() { return new ChequingAccount(); }
private sealed class SavingsAccount : BankAccount { ... }
and so on. Nested classes work very well with the factory pattern. Here BankAccount is a factory for various types of bank account, all of which can use the private implementation details of BankAccount. But no third party can make their own type EvilBankAccount that extends BankAccount.
Returning an interface to the caller whose implementation you want to hide.
public class Outer
{
private class Inner : IEnumerable<Foo>
{
/* Presumably this class contains some functionality which Outer needs
* to access, but which shouldn't be visible to callers
*/
}
public IEnumerable<Foo> GetFoos()
{
return new Inner();
}
}
Private helper classes is a good example.
For instance, state objects for background threads. There is no compelling reason to expose those types. Defining them as private nested types seems a quite clean way to handle the case.
I use them when two bound values (like in a hash table) are not enough internally, but are enough externally. Then i create a nested class with the properties i need to store, and expose only a few of them through methods.
I think this makes sense, because if no one else is going to use it, why create an external class for it? It just doesn't make sense to.
As for one class per file, you can create partial classes with the partial keyword, which is what I usually do.
One compelling example I've run into recently is the Node class of many data structures. A Quadtree, for example, needs to know how it stores the data in its nodes, but no other part of your code should care.
I've found a few cases where they've been quite handy:
Management of complex private state, such as an InterpolationTriangle used by an Interpolator class. The user of the Interpolator doesn't need to know that it's implemented using Delauney triangulation and certainly doesn't need to know about the triangles, so the data structure is a private nested class.
As others have mentioned, you can expose data used by the class with an interface without revealing the full implementation of a class. Nested classes can also access private state of the outer class, which allows you to write tightly coupled code without exposing that tight coupling publicly (or even internally to the rest of the assembly).
I've run into a few cases where a framework expects a class to derive from some base class (such as DependencyObject in WPF), but you want your class to inherit from a different base. It's possible to inter-operate with the framework by using a private nested class that descends from the framework base class. Because the nested class can access private state (you just pass it the parent's 'this' when you create it), you can basically use this to implement a poor man's multiple inheritance via composition.
I think others have covered the use cases for public and private nested classes well.
One point I haven't seen made was an answer your concern about one-class-per-file. You can solve this by making the outer class partial, and move the inner class definition to a separate file.
OuterClass.cs:
namespace MyNameSpace
{
public partial class OuterClass
{
// main class members here
// can use inner class
}
}
OuterClass.Inner.cs:
namespace MyNameSpace
{
public partial class OuterClass
{
private class Inner
{
// inner class members here
}
}
}
You could even make use of Visual Studio's item nesting to make OuterClass.Inner.cs a 'child' of OuterClass.cs, to avoid cluttering your solution explorer.
One very common pattern where this technique is used is in scenarios where a class returns an interface or base class type from one of its properties or methods, but the concrete type is a private nested class. Consider the following example.
public class MyCollection : IEnumerable
{
public IEnumerator GetEnumerator()
{
return new MyEnumerator();
}
private class MyEnumerator
{
}
}
I usually do it when I need a combination of SRP (Single Responsibility Principal) in certain situations.
"Well, if SRP is your goal, why not split them into different classes?" You will do this 80% of the time, but what about situations where the classes you create are useless to the outside world? You don't want classes that only you will use to clutter your assembly's API.
"Well, isn't that what internal is for?" Sure. For about 80% of these cases. But what about internal classes who must access or modify the state of public classes? For example, that class which was broken up into one or more internal classes to satisfy your SRP streak? You would have to mark all the methods and properties for use by these internal classes as internal as well.
"What's wrong with that?" Nothing. For about 80% of these cases. Of course, now you're cluttering the internal interface of your classes with methods/properties that are only of use to those classes which you created earlier. And now you have to worry about other people on your team writing internal code won't mess up your state by using those methods in ways that you hadn't expected.
Internal classes get to modify the state of any instance of the type in which they are defined. So, without adding members to the definition of your type, your internal classes can work on them as needed. Which, in about 14 cases in 100, will be your best bet to keep your types clean, your code reliable/maintainable, and your responsibilities singular.
They are really nice for, as an example, an implementation of the singleton pattern.
I have a couple of places where I am using them to "add" value, as well. I have a multi-select combobox where my internal class stores the state of the checkbox and the data item as well. no need for the world to know about/use this internal class.
Private anonymous nested classes are essential for event handlers in the GUI.
If some class is not part of the API another class exports, it must be made private. Otherwise you are exposing more than you intend. The "million dollar bug" was an example of this. Most programmers are too slack about this.
Peter
The question is tagged C# so I'm not sure this is of interest, but in COM you can use inner classes to implement interfaces when a class C++ implements multiple COM interfaces... essentially you use it for composition rather than multiple-inheritance.
Additionally in MFC and perhaps other technologies you might need your control/dialog to have a drop-target class, which makes little sense other than as a nested class.
If it is necessary for an object to return some abstract information about its state, a private nested class may be suitable. For example, if an Fnord supports "save context" and "restore context" methods, it may be useful to have the "save context" function return an object of type Fnord.SavedContext. Type access rules aren't always the most helpful; for example, it seems difficult to allow Fnord to access properties and methods of a Fnord.SavedContext without making such properties and methods visible to outsiders. On the other hand, one could have Fnord.CreateSaveContext simply create a New Fnord.SaveContext with the Fnord as a parameter (since Fnord.SaveContext can access the internals of Fnord), and Fnord.LoadContextFrom() can call Fnord.SaveContext.RestoreContextTo().
Either in C# or Java or in any other language which follows oops concepts generally has 'Object' as super class for it by default. Why do we need to have Object as base class for all the classes we create?
When multiple inheritance is not possible in a language such as C# or Java how can we derive our class from another class when it is already derived from Object class. This question may look like silly but wanted to know some experts opinions on it.
Having a single-rooted type hierarchy can be handy in various ways. In particular, before generics came along, it was the only way that something like ArrayList would work. With generics, there's significantly less advantage to it - although it could still be useful in some situations, I suspect. EDIT: As an example, LINQ to XML's construction model is very "loose" in terms of being specified via object... but it works really well.
As for deriving from different classes - you derive directly from one class, but that will in turn derive indirectly from another one, and so on up to Object.
Note that the things which "all objects have in common" such as hash code, equality and monitors count as another design decision which I would question the wisdom of. Without a single rooted hierarchy these design decisions possibly wouldn't have been made the same way ;)
The fact that every class inherits object ensured by the compiler.
Meaning that is you write:
class A {}
It will compile like:
class A : Object{}
But if you state:
class B : A {}
Object will be in the hierarchy of B but not directly - so there is still no multiple inheritance.
In short
1) The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class.
2) You can have B extend C, and A extend B. A is the child class of B, and B is the child class of C. Naturally, A is also a child class of C.
Well, the multiple inheritance of Object does not apply - you can think of it as:
"If a type doesn't have a base type, then implicitly inject Object".
Thus, applying the rule ad-nauseam, all types inherit from object once and once only - since at the bottom of the hierarchy must be a type that has no base; and therefore which will implicitly inherit from Object.
As for why these languages/frameworks have this as a feature, I have a few reasons:
1) The clue's in the name 'Object Oriented'. Everything is an object, therefore everything should have 'Object' (or equivalent) at it's core otherwise the design principle would be broken from the get-go.
2) Allows the framework to provide hooks for common operations that all types should/might need to support. Such as hash-code generation, string output for debugging etc etc.
3) It means that you can avoid resorting to nasty type casts that can break stuff - like (((int *)(void*))value) - since you have a nice friendly supertype for everything
There's probably loads more than this - and in the time it's taken me to write this 6 new answers have been posted; so I'll leave it there and hope that better people than I can explain in more detail and perhaps better :)
Regarding the first part of your question, it's how classes receive common properties and methods. It's also how we can have strongly-typed parameters to functions that can accept any object.
Regarding your second question, you simply derive your class from the other class; it will then be a descendant of that class, which is in turn a descendant of Object. There's no conflict.
You have the Object base class because amongst others because the Object class has methods (like, in .NET, GetHashCode(), which contain common functionality every object should have).
Multiple inheritance is indeed not possible, but it is possible to derive class A from class B, because A may not directly derive from Object, but B does, so all classes ultimately derive from Object, if you go far enough in the class' inheritance hierarchy.
Just to compare, let's take a look at a language that doesn't enforce a single root class - Objective-C. In most Objective-C environments there will be three root classes available (Object, NSObject and NSProxy), and you can write your own root class by just not declaring a superclass. In fact Object is deprecated and only exists for legacy reasons, but it's informative to include it in this discussion. The language is duck typed, so you can declare a variable's type as "any old object" (written as id), then it doesn't even matter what root class it has.
OK, so we've got all of these base classes. In fact, even for the compiler and runtime libraries to be able to get anywhere they need some common behaviour: the root classes must all have a pointer ivar called isa that references a class definition structure. Without that pointer, the compiler doesn't know how to create an object structure, and the runtime library won't know how to find out what class an object is, what its instance variables are, what messages it responds to and so forth.
So even though Objective-C claims to have multiple root classes, in fact there's some behaviour that all objects must implement. So in all but name, there's really a common primitive superclass, albeit one with less API than java.lang.Object.
N.B. as it happens both NSObject and NSProxy do provide a rich API similar to java.lang.Object, via a protocol (like a Java interface). Most API that claims to deal with the id type (remember, that's the "any old object" type) will actually assume it responds to messages in the protocol. By the time you actually need to use an object, rather than just create it with a compiler, it turns out to be useful to fold all of this common behaviour like equality, hashing, string descriptions etc. into the root class.
Well multiple inheritance is a totally different ball game.
An example of multiple inheritance:-
class Root
{
public abstract void Test();
}
class leftChild : Root
{
public override void Test()
{
}
}
class rightChild : Root
{
public override void Test()
{
}
}
class leafChild : rightChild, leftChild
{
}
The problem here being leafChild inherits Test of rightChild and leftChild. So a case of conflicting methods. This is called a diamond problem.
But when you use the object as super class the hierarchy goes like this:-
class Object
{
public abstract void hashcode();
//other methods
}
class leftChild : Object
{
public override void hashcode()
{
}
}
class rightChild : Object
{
public override void hashcode()
{
}
}
So here we derive both classes from Object but that's the end of it.
It acts like a template for all the objects which will derive from it, so that some common functionality required by every object is provided by default. For example cloning, hashcode and object locking etc.
As as rule of thumb I generally put classes in a file of their own. Visual studio seems to encourage this but what is appropriate with regards to interfaces?
e.g.
I have Class Foo that implements interface Bar
public interface IBar
{
}
public class Foo : IBar
{
}
it seems natural to group these within the same file until another class implements the interface but to dedicate a file to 2 lines code seems excessive but correct.
What is appropriate?
I would split them into 2 files. I often found classes starting to go unmanageable when they are not in their own files.
Imagine trying to find class Foo in a file named IBar.cs or vice versa.
Since the purpose of an interface is to define a "contract" for (potentially) multiple implementing classes, I'd say putting the interface definition in its own file makes more sense. i.e. What happens if you also want to make Baz implement Foo?
Depending on the situation I either split each interface into its own file, or alternatively have an Interfaces.cs file, where I group interfaces in a given namespace together.
I'd never put an interface in the same .cs file as a class that implemented it.
I have only two situations where I find myself putting multiple top level types in a single file:
If you're defining multiple delegate types. Each is only going to be a single declaration, so it makes sense to have a Delegates.cs file.
Sometimes it makes sense to declare that a whole bunch of autogenerated partial types implement a bunch of interfaces. Again, that's one line per type:
// Actualy code is in the autogenerated file
public partial class Foo : ICommon {}
Other than that, I use one file per top-level type, which goes for interfaces, classes and enums.
You should certainly put the interface in it's own file. You may even consider putting the interface in it's own class library. If the interface will be used by two different classes in two different libraries, it makes sense to put the interface in a third library, so you don't have to include any specific implementation if you want to add the interface to a new project. In the third library you might also place classes that work with classes that implement the interface (public void Cook(IBar x), for instance).
Yes, having an interface implies that you are going to have more than one class with the same methods and properties definitions. Having it in one file for the moment is convenient as it is easy to modify without changing files. As time goes on you will and other classes use it, and if you have to make a change to it down the road you will have to hunt and peck for the right file.
I always put them into separate files. Having more than one type per file is just distracting IMO. I might make a folder "Interfaces" for them though.
Also i think you shouldn't modify them as often as your actual implementations, anyway, so having them separated at least promotes that a bit.
In terms of encapsulation, each object, whether a class or an interface, should be in its own file. Even if the interface only contains one abstract method, the fact that it's in a different file allows for better organization and better encapsulation. You can store those different interfaces in a folder, give it an appropriate namespace, and therefore a cleaner solution.