Should I separate properties and methods in partial classes? [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 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;

Related

naming issue with enums inside the class [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 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

Can we use Abstract class instead of interface [duplicate]

This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 7 years ago.
i have started career as support developer but i have dream to get a job for S/W dev.
i am learning OOPS with C#. often one thing bug me that is interface and abstract class usage. when to use interface and when to use abstract class. i search google on this topic but whatever the answer i browse and i saw all people try to explain what is abstract and interface but i am not after their definition rather i want see their real usage in real world program. here i like to highlight one code where interface is used but i think the full things can be design with abstract class too.
see the below code of repository design pattern where interface has been used
if i expose repository as interface
public interface IEmployeeRepository
{
Employee[] GetAll();
}
then advantage will be i could have as many implementations as i like as below
public class EmployeeRepositoryEF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying your EF DbContext
}
}
public class EmployeeRepositoryXML: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying an XML file
}
}
public class EmployeeRepositoryWCF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying some remote WCF service
}
}
see the above code which has one contract method GetAll()
and who ever will extend the interface then they can provide their own implementation. that is the advantage but my question can i write abstract class instead of interface here ?
suppose i have one abstract class
abstract class AbsEmployeeRepository
{
abstract public Employee[] GetAll();
}
now my all other repository will extend the abstract class AbsEmployeeRepository
and override the function GetAll() to give their own implementation.
now the question is if abstract class can solve my purpose then why we need interface in this scenario. where multiple inheritance is concern then interface will be preferred other wise we can complete job with abstract class.
looking for valuable comments and suggestions. thanks
You would use an abstract class, when you have
Code to be shared.
Default behaviour in methods, but want users of your class to be able to override it.
You would use an interface when
There is no shared code.
It needs to be applied to many objects, with no common base class.
To make the definitions of public methods clearer and provide documentation.
You wish the source code to be private.
Often you would use an abstract class (for shared code) together with an interface (for documentation).
Interface provides only "description" of your future classes, while abstract classes used when you need to have some "unfinished functionality". So if you want to have a class with some logic provided and some unimplemented functions - you should use abstract class, but if all the functions is not implemented - use interface instead.
You should use an abstract class IF all your implementation share a common code basis implementation. That means, the interface will guarantee, that all classes have the same members, but each one must have its own implementation for them.
If you have an abstract class as base, all inheriting classes share the same implementation unless they override it, which is in many cases not needed, often you need to implement only a hand full of members differently.
Interface - guarantee same members.
Abstract class - share common code basis.
Some nice thoughts about it got mentioned on my question for this, maybe this helps you out.
You use abstract classes when you need to provide more than just abstract members to implement but also some concrete member:
public abstract class A
{
protected abstract void DoSomeCheck();
public void DoStuff()
{
// You don't know how DoSomeCheck will be implemented but
// you know a derived class must implement it
DoSomeCheck();
}
}
Alternatively, you use interfaces to define contracts that must be fulfilled by implementers in order to ensure that they can work together with your code:
// This car accepts any engine that implements IEngine
public class Car
{
public IEngine Engine { get; set; }
}
public interface IEngine
{
void Start();
}
There're many other use cases for both abstract classes and interfaces, but covering them would require a to compose a book instead of a simple answer. I still think that above explanation should give you the required hint to learn more about the topic.
can i write abstract class instead of interface here ?
Technically, yes you can. Practically, you shouldn't.
In this particular case implementation of the repositories is likely to be different. If implementation is different, an interface will declare desired behaviour in a clear way. Use of an abstract class can be justified, if the implementation was the same for all your repositories, or some methods where the same. Therefore allowing you to move otherwise duplicated code into one shared place.
In your particular case I'd rather not use either tailored interface or abstract class. There's IEnumerable<T> that does all you want, do not re-invent the wheel:
public class EmployeeRepositoryEF: IEnumerable<Employee> {
...
}
public class EmployeeRepositoryXML: IEnumerable<Employee> {
...
}
whenever you want an array all you need do is ToArray():
EmployeeRepositoryEF myRepo = ...
Employee[] staff = myRepo.ToArray(); // <- just ask for array

Given incrementally composed classes how can I replace them with some design pattern implementation while having the method bodies defined only once? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I don't think a design pattern can be used in this sense.
The case scenario is having a base object that has these properties and corresponding getters/setters always defined: (id,name,content). In addition to that there will be objects that have optional properties and corresponding getters/setters (comments, author, deleted).
I would like those object to provide the API with the exact properties/methods that I need nothing more and nothing less.
One approach is to have everything in one class which has a bloat of state
class Article {
int id;
int name;
String content;
List<Comment> comments;
Author author;
bool deleted;
//getters and setters omitted
}
The other one is to have multiple classes but that causes bloat of class Names
class Article {
int id;
int name;
String content;
//getters and setters omitted
}
class DeletedArticle : Article {
bool deleted = true;
//getters and setters omitted
}
class ArticleWithAuthor : Article {
Author author;
//getters and setters omitted
}
class ArticleWithComments : Article {
List<Comment> comments;
//getters and setters omitted
}
class DeletedArticleWithAuthor : Article {
bool deleted = true;
Author author;
//getters and setters omitted
}
class DeletedArticleWithComments : Article {
bool deleted = true;
List<Comment> comments;
//getters and setters omitted
}
class DeletedArticleWithAuthorAndComments : Article {
bool deleted = true;
Author author;
List<Comment> comments;
//getters and setters omitted
}
//AND SO ON...
Since all the possible configurations of a Class that always has (id,name,content) and three optional variables is 2^3 I wonder if there is a way to do it with design patterns (hopefully without Reflection). Keep in mind that I know I could use a more relaxed type-wise language or just use JSON/XML but that is not the point :P. Also I am not familiar with partial classes (from C#) if that is relevant at all.
As it was pointed ExpandoObjects could be the way. Could you please provide an example code using my own classes above for ArticleWithComments and DeletedArticleWithAuthorAndComments so these are not needed to be defined ?
So for example for ArticleWithComments I would like to have something like
Article article = new CommentsOnArticle(new Article());
and for DeletedArticleWithAuthorAndComments I would like to have something like:
Article article = new AuthorOnArticle(new DeletedOnArticle(new CommentsOnArticle(new Article())));
or some other notation like:
Article article = new MergerForArticle();
article.add(CommentForArticle.class);
article.add(DeletedForArticle.class);
article.add(AuthorForArticle.class);
So in other words I want to avoid defining all the possible arrangements of classes and just have a "dynamic class declaration"
Edit: I was thinking of reflection (e.g Java Reflect) too - I don't know if that would be a good practice though..
Edit2: I was also thinking of Anonymous classes and somehow pass the implementations as lambda functions ?? (Java now supports lambda functions) but then again all of the things in the interface will have to be implemented :(
Edit3: It was pointed to use Expando Objects so I changed the question accordingly since there is no design pattern that does this job. Java alterinative could be : https://svn.codehaus.org/groovy/branches/gep-3/src/main/groovy/util/Expando.java
What you are looking for is basically c#'s dynamic types, and ExpandoObjects. You can essentially build up a type at runtime to be whatever you want.
For example:
class Program
{
static void Main(string[] args)
{
dynamic sampleObject = new ExpandoObject();
// Create a new event and initialize it with null.
sampleObject.sampleEvent = null;
// Add an event handler.
sampleObject.sampleEvent += new EventHandler(SampleHandler);
// Raise an event for testing purposes.
sampleObject.sampleEvent(sampleObject, new EventArgs());
}
// Event handler.
static void SampleHandler(object sender, EventArgs e)
{
Console.WriteLine("SampleHandler for {0} event", sender);
}
}
Of course JavaScript has similar functionality too, as you can add and remove properties from classes at runtime at will.
This kind of behavior goes all the way back to SmallTalk really. But it's really only something the language can support. Not a design pattern.
Decorator pattern is used when different implementations of some base type can be nested in one another and when a method is called, the method result is obtained by calling all nested objects' same method. For example let's say you have a coffee class and you can also add condiments to your coffee. Single Mocha can be added to coffee or Double Mocha or cream. Each condiment has different price and you don't know what condiments would be added to coffee before hand. Then you can use decorator pattern. You can decorate coffee with condiments and when you call cost method, you will get the total cost which means coffee price plus all condiments. (By the way, the example is from Head First Design Patterns book which I recommend reading if you didn't do so)
Your case is not like that. I think you can just use a dictionary. And in each class, initialize the dictionary with all properties that are appropriate for that class.

What's the use of interfaces if I have to implement all the members elsewhere anyway? [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 can declare functions and properties in an interface, but I cannot implement them. When I inherit from the interface, I now have to implement all these members in my class. If I have to do that, what's the point of declaring the interface at all?
For example, here's an example interface:
namespace InterfaceExample
{
public interface IVehicle
{
int Doors { get; set; }
int Wheels { get; set; }
Color VehicleColor { get; set; }
int TopSpeed { get; set; }
int Cylinders { get; set; }
int CurrentSpeed { get; }
string DisplayTopSpeed();
void Accelerate(int step);
}
}
I've declared all the properties and functions in this interface. Now, when I use this interface in my class like this:
namespace InterfaceExample
{
public class Motorcycle : IVehicle
{
private int _currentSpeed = 0;
public int Doors { get; set; }
public int Wheels { get; set; }
public Color VehicleColor { get; set; }
public int TopSpeed { get; set; }
public int HorsePower { get; set; }
public int Cylinders { get; set; }
public int CurrentSpeed
{
get { return _currentSpeed; }
}
public Motorcycle(int doors, int wheels, Color color, int topSpeed, int horsePower, int cylinders, int currentSpeed)
{
this.Doors = doors;
this.Wheels = wheels;
this.VehicleColor = color;
this.TopSpeed = topSpeed;
this.HorsePower = horsePower;
this.Cylinders = cylinders;
this._currentSpeed = currentSpeed;
}
public string DisplayTopSpeed()
{
return "Top speed is: " + this.TopSpeed;
}
public void Accelerate(int step)
{
this._currentSpeed += step;
}
}
I have to declare all the properties again.
So why bother at all with the interface in the first place? It seems like a waste of time, since I will be implementing all the members in my class anyhow.
As other answers emphasize interfaces tell you what to do and how to do is up to you to implement.
1. Then why I waste my time in create a Interface If I have to declare all the properties and functions of My Interface in my class.
Ok. You are creating a Motorcycle and by implementing the interface IVehicle, the MotorCycle class is forced to implement all the members of the interface IVehicle.
If you had not used an interface called IVehicle, you might actually forget to implement something that you should have been implemented.
Tomorrow, if somebody wants to build a Car then you can implement from IVehicle, people can implement all its methods and customize.
The purpose of the IVehicle interface is to make sure that whenever you build a vehicle class, it reminds and forces you to make sure that you rightly build a vehicle
2. For Properties, interface is a waste of time ?
No and definitely not.
For example, whenever you want to return the vehicle speed, instead of just rounding of the vehicle speed to integer you want in exact floating point,
10 // public float currentSpeed { get; set; }
10.5 // public float currentSpeed { get {return {//write custom logic}; set; }
Notice the customisation in Get accessor of the property.
3. When should abstract class be used ?
Abstract class should be used when all derived class would be using some repeated method. For example,
public abstract Class AbstractClass
{
public virtual int Doors { get; set; }
public virtual int Wheels { get; set; }
public virtual Color VehicleColor { get; set; }
public virtual int TopSpeed { get; set; }
public virtual int HorsePower { get; set; }
public virtual int Cylinders { get; set; }
public string WhatSideDriving
{
if (Country == "US") return "Keep Right";
if (Country == "India") return "Keep Left";
}
}
Do note that the method WhatSideDriving is already implemented and can be used by all the classes that derive from this class. However other members can be overridden and can be implemented according to the required functionality.
Then why I waste my time in create a Interface If I have to declare all the properties and functions of My Interface in my class.
Because an interface is just that; a (public) interface. It does not define an implementation, only the methods and properties used to interface to any of its implementations.
Of course, implementors of said interface must define the implementation of it. How else would you expect this to work?
That said, it's not inconceivable that properties could be implicitly (and invisibly) implemented as automatic properties, but that doesn't work for methods, and you often need more than get; set; anyway, so it would provide little benefit (i.e., a feature that isn't worth the effort).
Strictly speaking, declaring an interface is a waste of time. You could skip the interface and save some time.
However, you would be cutting the wrong corner. While it's a bit of extra time and work, in the long run interfaces are invaluable. One of the marks of a truly great software engineer is being able to design interfaces well.
To be less abstract, the interface is designed for precisely that purpose: To formalize the interface between two kinds of classes (in other words, how the two classes work together). It is a bit like a contract between classes, where each class says what they promise to provide and what they will expect. Your IVehicle example, for instance, vows that it will always have a property called doors. Then, any code which works with IVehicle can trust all implementations of IVehicle to always have a Doors. You can now safely write code which accesses IVehicle.Doors knowing that no matter what particular implementation happens to get passed to this method, your code will definitely work - even if the Vehicles package developer decides to one day add some vehicles you've never heard about or considered!
When you have only one small class implementing the interface, and you are the only developer, interfaces may be superfluous. However, what if there were multiple kinds of vehicles, each with their own logic and different members, which must nevertheless be used by some general code? For example, a vehicle tracking manager must handle classes Car, Truck, Plane and so on. Why not? They all have a speed and position, and that's all that matters.
Moreover, when you let other developers write their own vehicles, the interface is a great way of showing them how they must do this for it to work with the rest of your code.
Likewise, when you work on a large project, and split each part between different developers, well-designed interfaces can ensure that these programmers, working on different parts of the project in relative isolation, will still create a whole which works thanks to parts that fit together nicely.
Similarly, a good interface is a great way to start a complicated class even when coding on your own: It will help you keep track of what you need to implement and how, but unlike a more familiar technical specification, an interface can be understood by the compiler so that it can assist you in many ways (such as help from IntelliSense when you want to write logic using parts of your class that you will implement later).
In C# particularly, interfaces also have a practical benefit. You can't inherit from more than one class or abstract class in C# (unlike C++). This is done because multiple inheritance turns out to make life very difficult for programmers sometimes. But you can inherit from multiple interfaces, and because they are only interfaces (with no implementation) the "multiple inheritance" thing is much less of an issue.
Lastly, a real world example: Microsoft has provided for you a List.Sort method which will helpfully sort a list of any object. It is obviously easy to do this for things like numbers and strings, but it is possible to make it sort arbitrary objects you made, like vehicles. But how could Microsoft possibly know what kinds of classes you will implement, and how you intend for these to be sorted? They don't, but they provide for you an interface called IComparable. This defines the methods that sorting code needs to call to be able to compare two objects for sorting. If the object you put into your list implements this IComparable, you will have told Microsoft's List.Sort code how your objects should be sorted, and now you no longer have to write your own sort function since you can just use the well designed, tested, documented and debugged Microsoft one.
As an exercise, try writing a program which takes a list of Triangle classes (which have only a, b, c fields that store the length of each side, and a CalculateArea method) and then sorts it by area using Microsoft's List.Sort. Don't write your own sorting code, and don't use thing like LINQ OrderBy, instead do it by making Triangle implement IComparable. Then think about this: If you were the project manager in charge of development of all the .NET libraries, how would you write a sort function that anyone can use, even with their own weird classes?
You create an interface if you need to create an interface.
You can pass all types of vehicles as the interface type to methods. If you declare all three of the following and you need to calculate their fuel efficiency, you would need three separate methods that do that.
example:
public class Truck {}
public class Car {}
public class Motorcycle {}
With an interface you need one method:
public int GetFuelEfficiency(IVehicle vehicle)
The interface requires you or anyone else implementing it to declare ALL of its properties and methods. This way all classes implementing the interface will contain all the necessary properties and methods to be treated by other code in the same manner regardless of the classes specific implementations.
There are yet other reasons for declaring an interface like the lack of multiple inheritance in C#, etc.
Interfaces are definitions, and not implementations. Classes are both implementations and definitions.
The point of an interface is to separate implementation from definition, so that that the consumer does not have any knowledge of the actual object used to implement the interface.
Yes, it's more work, but good design is always more work than bad.
Interface provides a blueprint for implementation. You have the freedom to create the actual class from that blueprint. To be able to do so, you have to define all the aspects of that blueprint.
Interface is mostly used to create pluggable interfaces to applications and are also used to support multiple inheritance.
References:
Code Project
DZone
MSDN - Interfaces - C# Programming Guide
MSDN - When to use Interfaces
You may also use Abstract classes if it suits your purpose. But Abstract class != Interface.

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.

Categories

Resources