Class declared inside of another class in C# - c#

I am working on some legacy code and have come across something that I'm not sure of. We have a class y that is declared inside of another class x. Class y is only ever used inside of class x but my question is why wouldn't you create a separate class file and put class y in there instead of declaring it inside of class x? Isn't this violating OOP's or is it just a matter of style since it is only ever used inside of this class. I'm refactoring some of this code and my first reaction would be to separate class y out into it's own file.
namespace Library
{
public class x
{
// methods, properties, local members of class x
class y
{
// methods, properties, local members of class y
}
}
}

You create an inner class because it is only ever used within the scope of class x and it logically fits in the factoring/architecture of class x.
Class y might also be privy to implementation details of class x that are not meant to be known to the public.

This has permissions implications. A top-level "class y" would be "internal" - however, here "y" is private to "x". This approach is helpful for implementation details (for example cache rows etc). Likewise, y has access to all private state of x.
There are also implications with generics; x<T>.y is generic "of T", inherited from the outer class. You can see this here, where Bar has full use of T - and note that any static fields of Bar are scoped per-T.
class Foo<T> {
void Test(T value) {
Bar bar = new Bar();
bar.Value = value;
}
class Bar {
public T Value { get; set; }
}
}
Often people incorrectly think they need to define Bar as Bar<T> - this is now (effectively) doubly generic - i.e. Foo<TOld, T> - where TOld is the (now unavailable) T from Foo<T>. So don't do that! Or if you want it to be doubly-generic, pick different names. Fortunately, the compiler warns you about this...

This code is fine for the exact reason that you have given - "class y is only ever used inside of class x". Those are nested types and one of the guidelines for using them is that nested types should be tightly coupled to their declaring type and must not be useful as a general purpose type. That way the nested class is inacessible to other classes, but still allows you to follow object oriented principles.

I just went through code that I am updating (and I originally wrote) and removed all nested classes. Unfortunately, I originally used the nested class outside of the class it was defined in. Moving nested classes out made a huge difference to me because I originally had bad design.
If Y is only used in X and will never be used outside of X, I'd say keep it there

I think it's ok, as long as the contained class is only used as utility. I use this sort of construct for example to define complex return types for private methods.

Let me give you an example of the use of nested classes that might clarify when this kind of architecture is appropriate. I recently needed to generate an HTML table by pulling selected columns from a data table and "pivoting" them so that rows become columns and vice versa. In my case, there were two essential operations: pivoting the data and generating some rather complex output (I was not just showing the data: each data column/table row was subject to operations for extracting title, generating image tags, setting up links, etc. thus using a SQL Pivot wasn't really right either).
After an initial attempt to create one class to do the whole thing, I recognized that much of the data/methods fell into three distinct partitions: header processing, row processing, and pivoting. Thus, I decided that a better approach would be to encapsulate the logic for "header" and "row" into separate, nested classes. This allowed me to separate the data held by each row and program the pivot operations very cleanly (calling a separate row object for each column in your data table). At the end of the pivot operations, I generated output by calling the header object and then each row object in turn to generate its output back to the main class.
Separate classes weren't appropriate because A) the nested classes did need some data from the master class and B) the processing was very specific and not useful elsewhere. Just programming one big class was simply messier due to confusion surrounding terms such as "column" and "row" which differed depending on whether you were talking about data or HTML output. Also, this was unusual work in that I was generating HTML in my business class so I wanted to pull apart the pure business logic from the UI generation. In the end, nested classes provided the perfect balance, then, of encapsulation and data sharing.

You could still refactor your class y into another file, but use a parial class. The benefit of this is that you still have one class per file and don't have the refactoring hassles of moving the declaration outside of class x.
e.g. you could have a code file: x.y.cs which would look something like
partial class X
{
class Y
{
//implementation goes here
}
}

Related

Am I following the SRP with this structure?

I am trying to write a plugin for Autocad, and there, they have these Extension Dictionaries where you can save data into an Autocad object so that when you close a drawing file, the saved data persists.
Now I need 4 functions to manipulate the extension dictionary:
exist - for checking if an extension dictionary exists
create - for creating an extension dictionary
set - for setting data inside the extension dictionary
get - for getting data from the
extension dictionary
currently, what I have is I have an ExtensionDictionaryManager.cs that is partial broken down into 4 .cs files like this:
partial class ExtensionDictionaryManager
{
public bool Exist() {...}
}
partial class ExtensionDictionaryManager
{
public bool Create() {...}
}
partial class ExtensionDictionaryManager
{
public bool Set() {...}
}
partial class ExtensionDictionaryManager
{
public bool Get() {...}
}
Does this follow the Single Responsibility Principle? Or should I break it down even more into ExtensionDictionaryCreator, ExtensionDictionaryChecker, ExtensionDictionarySetter and ExtensionDictionaryGetter?
My concern is if I did break it into absolute single responsibilities, not grouping related functionalities together, and doing it consistently throughout my program, I would end up with so many objects.
Which would be the right way to do this?
The SRP is difficult to handle. See for example a Message class. Should this class contain a Send() method? Can a method send itself? Or should there be another class MessageSender?
Some people use the SRP only to make classes smaller and smaller, which might ultimately lead to classes containing only one method. But methods that belong togehter should stay together. A good help is how to decide what should be in the same class is: If I have to change a feature, often I have to change several methods. These methods should be in the same class. If I change always the same two classes at the same time, these classes maybe should be united. If I change only one part of a class, or the other, but never both parts at the same time, the class should be split. See also https://hackernoon.com/you-dont-understand-the-single-responsibility-principle-abfdd005b137
Coming back to the example with the message: If the mechanism of sending the message is completely unrelated to the data that the message contains, two classes Message and MessageSender might be better. If the format of the message is strongly linked to how to send the message, it might be better to have a single class. But this is always some subjective consideration.
And for your code: I would leave it in one class. See for example List<T>: This is one class for manipulating the list, and not a ListAdder<T>, ListInserter<T>, ListRemover<T>, ... If your autocad changes, you will have to change the the algorithm of checking whether something exists, of creating, and so on, all at the same time. That's why they belong into one class.

Accessing class properties inside the class via the this.PropertyGet

I'm building a C# class for matrices. I actually found something on SO to get started with so I don't have to start from scratch. The guy's class has a private property for the rows and columns of the matrix and a get() and set() property. Sometimes the guy refers to the properties themselves by name mRowCount and mColumnCount or by the this.RowCount and this.ColumnCount inside the class for calculation purposes as seen below (I only added relevant code):
public class Matrix
{
private decimal[,] mInnerMatrix;
private int mRowCount, mColumnCount = 0;
public int RowCount
{
get { return mRowCount; }
}
public int ColumnCount
{
get { return mColumnCount; }
}
}
Sometimes in the code the guy uses the properties by name mRowCount and mColumnCount and other times using this.RowCount and this.ColumnCount instead of the former way. What is the difference? Is one way better and if so with respects to what? Particularly in boolean methods where the methods checks to see if the object/matrix is a diagonal, symmetric or square matrix the developer uses the this.RowCount and this.ColumnCount in the loops that run through the mInnerMatrix[] array that holds the matrix's data. Other times he uses the properties themselves. Can anyone explain why someone might do this or is it a mistake? What should I use and should I use it throughout the entire program?
Technically, the get and set methods can be not that straightforward. For instance if you don't store rows and cols count but instead store rows and total elements, you would have to divide total by rows to get cols:
public Cols {get {return _mTotal/_mRows;}}
This is not the best sample, but you can get the idea. In your simple case there will be no difference whether to use a field or a property (if you actually have set methods but omitted them, otherwise the properties are readonly!). But note that one day you might want to implement some logic in get. Then the code that's using properties would work fine but the code that's using fields would fail.
Outside a class you always have to use properties, if any. In fact, you would declare fields private so that only within the class you can access them. Technically you can use both fields and properties outside class, but that would lead to a chaos.
On the other hand I would disagree that mixing properties and fields access within a class is always discouraged. Sometimes you would really need this access, the easiest sample is when your property is readonly (has only get).
If you defined properties - use them wherever possible, inside or outside class, as they may contain additional logic, not only direct member access.
One valid reason not to use properties (use direct access instead) - in constructor,
every other access should be made using properties.
It's rather bad practice to mix direct access and properties within a class

In C# or OOP, should 2 classes reference each other that are related?

I am working on a class library using C#. I have designed 3 main classes to help model our data. They are designed such that class A contains a list of class B instances, and class B contains a reference to a class C instance, ie:
public class Policy
{
public List < PolicyTerm > myTerms;
person Customer;
string PolicyNumber;
}
public class PolicyTerm
{
public Billing myBill;
Datetime effectivedate;
List < Activities > termActivities;
public doAction()
{
use value from Policy, like PolicyNumber;
}
}
public class Billing
{
float remainingBalance;
Datetime nextDueDate;
public void doSomething()
{
reference value from PolicyTerm, such as effective date;
use value from Policy, such as PolicyNumber;
}
}
The problem I have is when I try to use a method within PolicyTerm or Billing that needs data from the containing class. In the example above, this would be the method "doSomething" trying to use a value from PolicyTerm, like the effective date for the term in requesting or saving data to our database.
I am wondering if I have the correct design for my classes because of this scenario. Should I just add a reference to the "parent" class within the child classes, in order to make the parent's data available? Or do I need to rethink the overall structure and design of the code?
I feel like the class design works well for modeling the data and our business rules, but it does create a few limitations like the above situation. I liked the separation of the PolicyTerm and Billing for the ability to allow that code to be modified and tested independently. Also, I feel like it keeps each section smaller and simpler.
Any advice that can be provided would be much appreciated.
Update: Code block was updated to provide more details on the code in question.
If doSomething() always needs the reference to the C object's parent, you should indeed put this reference into C where you can ensure that it refers to the correct B instance. OTOH if that reference is not always the parent, but still it is always going to refer to the same B instance, it still suggests turning it into a member of C. OTOH if doSomething() can be called with varying references, that reference should be kept as a method parameter.
It is not bad per se to put a reference from child to parent, or to have a mutual dependency between two classes - it depends on the context. The consequence of this is that the two classes can not be used separately, so in fact they form a component. This may or may not be acceptable for you.
Components in general can consist of multiple classes - a collection with its items and iterator(s) is in fact a typical example. However, it is advisable to express the logical dependency between these classes on the physical level as well, e.g. by making one class an inner class of the other, or making both classes inner classes in a third class.
This really depends on the situation. In general, unless there is a clear, obvious relationship between classes "B" and "C", it's a red flag that C.doSomething() would require access to B, since C is contained within B...
However, a method in B requiring access to C makes sense, since C is a member within B.
That being said, there are times that this is appropriate. Without knowing your actual classes, and what they represent, its difficult to say more...
Two classes shouldn't, but two interfaces is OK.
Of course, the smaller the interfaces the better. You'll find that if the interfaces are small enough (which they should be - see Interface Segregation Principal), you won't actually need 2 of the same.
Creating a reference to your required class doesn't seem a bad idea at all. If it's required, you could make Class C's constructor take the reference to Class B and store it in a member variable.
I'm working on a project at the moment with a couple of classes behave like this.
Another option which might be a bit more "sane" is to have an event on class C, that's something like "SuchAndSuchDataRequired." Class B could then listen to that event when it gets the instance of C. Class C fires the event from within doSomething() when it needs the data from B, B then returns the data in it's event handler and bingo - class C has the data and doesn't even know it came from class B.
The general rule of thumb is keep the data as close as possible to the functions/methods/classes that will be using it. This will keep things decoupled and you won't have to have both classes referencing each other, which actually makes you have to create an extra object that might not be necessary.
And like ChaosPandion said: please post some more specific code so we can better help you.
Edit:
If you B references C and C references B, then you might want to consider putting the two together as one object. This works best if the two classes are not completely different. If there is no real distinguishable difference, then just put it together in one class ... that could simplify the whole thing.
In my opinion your modelling seems a bit skewed i.e. why is there a property of type person within policy and why have a List of a concrete implementation in Policy i.e. PolicyTerm. This couples the classes together and doesn't feel right - i.e. Policy HAS A customer? Should be Customer HAS A Policy
Can I suggest the following (quickly modelled and not tested but you should be able to see what I'm getting at)
public class Customer()
{
prop name,etc,etc;
public List<IPolicyTerm> Policies{get;set;}//I use public getters and setters throughout but you need to choose what level of encapsulation you want
private Account customerAccount{get;set}
public Customer()
{
//ctor
customerAccount = doDbCall;
Policies = doDbCall;
}
public decimal GetCurrentPolicyCost()
{
decimal cost = 0;
foreach(var policy in Policies)
{
if(policy.DueDate < DateTime.Now){
cost += policy.GetCost(); //for example but you can call whatever is defined at the interface level
}
}
return cost;
}
public bool HasEnoughFunds()
{
return customerAccount.Balance >= GetCurrentPolicyCost();
}
//keeping Account hidden in Person as Person has a reference to Account.
//By doing so there is type coupling between the two classes
//BUT you can still modify Policies away from Person
private class Account
{
//should only contain properties and I assume only one 'Account' per person
}
}
public interface IPolicyTerm
{
object Id{get;set}
DateTime DueDate {get;set;}
decimal GetCost();
}
///now we can have polymorphic Policies i.e. the cost of one can be calculated differently based on policy
public class LifeCoverPolicy : IPolicyTerm
{
public object Id;
public DateTime DueDate{get;set;}
public decimal GetCost()
{
return 10;
}
}

Passing arguments between classes - use public properties or pass a properties class as argument?

So let's assume I have a class named ABC that will have a list of Point objects.
I need to make some drawing logic with them. Each one of those Point objects will have a Draw() method that will be called by the ABC class.
The Draw() method code will need info from ABC class.
I can only see two ways to make them have this info:
Having Abc class make public some properties that would allow draw() to make its decisions.
Having Abc class pass to draw() a class full of properties.
The properties in both cases would be the same, my question is what is preferred in this case. Maybe the second approach is more flexible? Maybe not? I don't see here a clear winner, but that sure has more to do with my inexperience than any other thing.
If there are other good approaches, feel free to share them.
Here are both cases:
class Abc1 {
public property a;
public property b;
public property c;
...
public property z;
public void method1();
...
public void methodn();
}
and here is approach 2:
class Abc2 {
//here we make take down all properties
public void method1();
...
public void methodn();
}
class Abc2MethodArgs {
//and we put them here. this class will be passed as argument to
//Point's draw() method!
public property a;
public property b;
public property c;
...
public property z;
}
Also, if there are any "formal" names for these two approaches, I'd like to know them so I can better choose the tags/thread name, so it's more useful for searching purposes. That or feel free to edit them.
The best approach depends on the nature of the information ABC needs to provide to the Point instances, the nature of the relationship between these classes, and the "expected" future for them. In other words there are a lot of qualitative factors.
If you do go with passing the Point an ABC instance, don't - rather, work out an appropriate abstraction for whatever it is Point needs from ABC, and encapsulate that in an interface. In static terms this is similar to simply creating a new class to encapsulate the information, but dynamically quite different.
The reason you shouldn't simply pass an instance of ABC is that it creates a circular dependency. Without going into too much detail, this should generally be regarded as a Very Bad Thing and avoided unless absolutely necessary.
And, at a more abstract level, it will make more sense and enable logical changes later if you identify the reason for this apparent circular dependency and factor that out - ie, create an interface to represent this 'data source for Points' role which ABC must fulfil. This role is distinct from the 'container for Points' role and that should be reflected in your design.
You could also pass the parameters to the draw() method - again this may be good or bad depending on a heap of factors. It's certainly not a Very Bad Thing, as long as you've thought about the implications.
It will be more work to create and maintain a separate class to pass state between ABC and point, but it's worth doing if you want to decouple point from ABC.
The main question is, how much does decoupling them matter to you, if it matters at all? If it makes sense in your domain for point instances to know about abc instances, it probably isn't worth creating the parameter class and you should just go with option 1.
Go with approach #2, but without the object. Just pass the parameters to Draw directly.
Since the Point class and ABC appear to have to mediate between themselves as to what to draw, why not call the draw() method on the Point, passing the actual ABC object as an argument. The ABC object can provide accessor methods (don't expose those properties!) and the point class (or subclass implementations) can decide what to call back on ABC for.
You may want to consider reversing the dependencies. Instead of Points accessing properties from ABC, have ABC set properties on the points when (or just before) calling "draw()" on each of them. Something similar to the Flyweight pattern used when rendering cells in Swing's JTables (see javadoc). You may also consider decoupling Point (data model) from PointDrawer (reusable rendering code). That way your Points will not depend on all those properties, only your PointDrawers will.
And yes, it is OO programming even if you explicitly pass in all parameters to each Point at drawing time - that way, Points have no dependency at all on either ABC or on ABC's would-be "parameter-passing class".

When to Subclass instead of differentiating the behaviour

I'm having difficulties deciding when I should be subclassing instead of just adding an instance variable that represents different modes of the class and then let the methods of the class act according to the selected mode.
For example, say I've a base car class. In my program I'll deal with three different types of cars. Race cars, busses and family models. Each will have their own implementation of gears, how they turn and seat setup. Should I subclass my car into the three different models or should I create a type variable and make the gears, turning and seating generic so they would act different depending on which car type was selected?
In my current situation I'm working on a game, and I've come to realise that it's starting to get a bit messy, so I ask advice on possibly refactoring of my current code. Basically there are different maps, and each map can be one of three modes. Depending on which mode the map is defined as there will be different behaviour and the map will be built in a different way. In one mode I might have to give out rentals to players and spawn creatures on a timeout basis, wherein another the player is responsable for spawning the creatures and yet in another there might be some automated spawned creatures alongside with player spawned ones and players constructing buildings. So I'm wondering whether it would be best to have a base map class, and then subclass it into each of the different modes, or whether to continue down my current path of adding differentiated behaviour depending on what the map type variable is set to.
All credits to AtmaWeapon of http://www.xtremevbtalk.com answering in this thread (Archive Link)
Core to both situations is what I feel is the fundamental rule of object-oriented design: the Single Responsibility Principle. Two ways to express it are:
"A class should have one, and only one, reason to change."
"A class should have one, and only one, responsibility."
SRP is an ideal that can't always be met, and following this principle is hard. I tend to shoot for "A class should have as few responsibilities as possible." Our brains are very good at convincing us that a very complicated single class is less complicated than several very simple classes. I have started doing my best to write smaller classes lately, and I've experienced a significant decrease in the number of errors in my code. Give it a shot for a few projects before dismissing it.
I first propose that instead of starting the design by creating a map base class and three child classes, start with a design that separates the unique behaviors of each map into a secondary class that represents generic "map behavior". This post is concerned with proving this approach is superior. It is hard for me to be specific without a fairly intimate knowledge of your code, but I'll use a very simple notion of a map:
Public Class Map
Public ReadOnly Property MapType As MapType
Public Sub Load(mapType)
Public Sub Start()
End Class
MapType indicates which of the three map types the map represents. When you want to change the map type, you call Load() with the map type you want to use; this does whatever it needs to do to clear the current map state, reset the background, etc. After a map is loaded, Start() is called. If the map has any behaviors like "spawn monster x every y seconds", Start() is responsible for configuring those behaviors.
This is what you have now, and you are wise to think it's a bad idea. Since I mentioned SRP, let's count the responsibilities of Map.
It has to manage state information for all three map types. (3+ responsibilities*)
Load() has to understand how to clear the state for all three map types and how to set up the initial state for all three map types (6 responsibilities)
Start() has to know what to do for each map type. (3 responsibilities)
*Technically each variable is a responsibility but I have simplified it.
For the final total, what happens if you add a fourth map type? You have to add more state variables (1+ responsibilities), update Load() to be able to clear and initialize state (2 responsibilities), and update Start() to handle the new behavior (1 responsibility). So:
Number of Map responsibilities: 12+
Number of changes required for new map: 4+
There's other problems too. Odds are, several of the map types will have similar state information, so you'll share variables among the states. This makes it more likely that Load() will forget to set or clear a variable, since you might not remember that one map uses _foo for one purpose and another uses it for a different purpose entirely.
It's not easy to test this, either. Suppose you want to write a test for the scenario "When I create a 'spawn monsters' map, the map should spawn one new monster every five seconds." It's easy to discuss how you might test this: create the map, set its type, start it, wait a little bit longer than five seconds, and check the enemy count. However, our interface currently has no "enemy count" property. We could add it, but what if this is the only map that has an enemy count? If we add the property, we'll have a property that's invalid in 2/3 of the cases. It's also not very clear that we are testing the "spawn monsters" map without reading the test's code, since all tests will be testing the Map class.
You could certainly make Map an abstract base class, Start() MustOverride, and derive one new type for each type of map. Now, the responsibility of Load() is somewhere else, because an object can't replace itself with a different instance. You may as well make a factory class for this:
Class MapCreator
Public Function GetMap(mapType) As Map
End Class
Now our Map hierarchy might look something like this (only one derived map was defined for simplicity):
Public MustInherit Class Map
Public MustOverride Sub Start()
End Class
Public Class RentalMap
Inherits Map
Public Overrides Sub Start()
End Class
Load() isn't needed anymore for reasons already discussed. MapType is superfluous on a map because you can check the type of the object to see what it is (unless you have several types of RentalMap, then it becomes useful again.) Start() is overridden in each derived class, so you've moved the responsibilities of state management to individual classes. Let's do another SRP check:
Map base class
0 responsibilities
Map derived class
Must manage state (1)
Must perform some type-specific work (1)
Total: 2 responsibilities
Adding a new map
(Same as above) 2 responsibilities
Total number of per-class responsibilities: 2
Cost of adding a new map class: 2
This is much better. What about our test scenario? We're in better shape but still not quite right. We can get away with putting a "number of enemies" property on our derived class because each class is separate and we can cast to specific map types if we need specific information. Still, what if you have RentalMapSlow and RentalMapFast? You have to duplicate your tests for each of these classes, since each has different logic. So if you've got 4 tests and 12 different maps, you'll be writing and slightly tweaking 48 tests. How do we fix this?
What did we do when we made the derived classes? We identified the part of the class that was changing each time and pushed it down into sub-classes. What if, instead of subclasses, we created a separate MapBehavior class that we can swap in and out at will? Let's see what this might look like with one derived behavior:
Public Class Map
Public ReadOnly Property Behavior As MapBehavior
Public Sub SetBehavior(behavior)
Public Sub Start()
End Class
Public MustInherit Class MapBehavior
Public MustOverride Sub Start()
End Class
Public Class PlayerSpawnBehavior
Public Property EnemiesPerSpawn As Integer
Public Property MaximumNumberOfEnemies As Integer
Public ReadOnly Property NumberOfEnemies As Integer
Public Sub SpawnEnemy()
Public Sub Start()
End Class
Now using a map involves giving it a specific MapBehavior and calling Start(), which delegates to the behavior's Start(). All state information is in the behavior object, so the map doesn't really have to know anything about it. Still, what if you want a specific map type, it seems inconvenient to have to create a behavior then create a map, right? So you derive some classes:
Public Class PlayerSpawnMap
Public Sub New()
MyBase.New(New PlayerSpawnBehavior())
End Sub
End Class
That's it, one line of code for a new class. Want a hard player spawn map?
Public Class HardPlayerSpawnMap
Public Sub New()
' Base constructor must be first line so call a function that creates the behavior
MyBase.New(CreateBehavior())
End Sub
Private Function CreateBehavior() As MapBehavior
Dim myBehavior As New PlayerSpawnBehavior()
myBehavior.EnemiesPerSpawn = 10
myBehavior.MaximumNumberOfEnemies = 300
End Function
End Class
So, how is this different from having properties on derived classes? From a behavioral standpoint there's not much different. From a testing viewpoint, this is a major breakthrough. PlayerSpawnBehavior has its own set of tests. But since HardPlayerSpawnMap and PlayerSpawnMap both use PlayerSpawnBehavior, then if I've tested PlayerSpawnBehavior I don't have to write any behavior-related tests for a map that uses the behavior! Let's compare test scenarios.
In the "one class with a type parameter" case, if there are 3 difficulty levels for 3 behaviors, and each behavior has 10 tests, you'll be writing 90 tests (not including tests to see if going from each behavior to another works.) In the "derived classes" scenario, you'll have 9 classes that need 10 tests each: 90 tests. In the "behavior class" scenario, you'll write 10 tests for each behavior: 30 tests.
Here's the responsibility tally:
Map has 1 responsibility: keep track of a behavior.
Behavior has 2 responsibilities: maintain state and perform actions.
Total number of per-class responsibilities: 3
Cost of adding a new map class: 0 (reuse a behavior) or 2 (new behavior)
So, my opinion is that the "behavior class" scenario is no more difficult to write than the "derived classes" scenario, but it can significantly reduce the burden of testing. I've read about techniques like this and dismissed them as "too much trouble" for years and only recently realized their value. This is why I wrote nearly 10,000 characters to explain it and justify it.
You should subclass wherever your child type is some sort of specialization of the parent type. In other words, you should avoid inheritance if you just need functionality. As the Liskov Substitution Principle states: "if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program"
In your case i would go with a hybrid approach (this might be called composition, i don't know), where your map mode variable is actually a separate object that stores all related data/behavior to the map's mode. This way you can have as many modes as you like without actually doing too much to the Map class.
gutofb7 nailed it on the head as to when you want to subclass something. Giving a more concrete example: In your Car class, would it matter anywhere in your program what type of car you were dealing with it? now if you subclassed Map, how much code would you have to write that deals with specific subclasses?
In the particular problem you talked about with the maps and spawning, I think this is a case where you want to favour composition over inheritance. When you think about it, they aren't exactly three different types of map. Instead, they are the same map with three different strategies for spawning. So if possible, you should make the spawning function a separate class and have an instance of a spawning class as a member of your map. If all the other differences in "modes" for your maps are similar in nature, you might not have to subclass the map at all, although subclassing the different components (i.e. have a spawn_strategy base class and subclass the three types of spawning from that), or at least giving them a common interface, will probably be necessary.
Given your comment that each type of map is meant to be conceptually different, then I would suggest subclassing, as that seems to fulfill Liskov's substitution principle. However, that is not to say you should give up on composition entirely. For those properties which every type of map has, but may have different behaviour/implementation, you should consider making your base class have them as components. That way you can still mix and match functionality if you need to, while using inheritance to maintain a separation of concerns.
I don't program in C#, but in Ruby on Rails, Xcode, and Mootools (javascript OOP framework) the same question could be asked.
I don't like having a method that will never be used when a certain, permanent, property is the wrong one. Like if it's a VW Bug, certain gears will never be turned. That's silly.
If I find some methods like that I try to abstract everything out that can be shared among all my different "cars" into a parent class, with methods and properties to be used by every kind of car, and then define the sub classes with their specific methods.

Categories