Is this candidate for abstract class - c#

let's say that I want to collect in one place all common properties and behaviors for all sports. I was thinking to use SportBase as abstract class for this purpose but I'm not sure. I'm trying to understand the differences between Abstract vs Interface usage on this example.
Every sport should have following properties
DateTime Started;
DateTime Ended;
string Name;
What if I declare these properties like integers and later on I decide to use Game object as separated entity like Game StartGame. I do not see clearly which approach to use with high level of abstraction to reduce pain on later modification (this modification can have adding new properties, new behaviors, etc.)
Thanks

if you only have properties and empty methods an interface might be your better choice. if you have some actual code then abstract class is your only option. also remember that you can inherit only one abstract class but implement multiple interfaces.

You can use an interface to provide a contract to code to.
public interface ISportsEvent
{
DateTime Start { get; set; }
DateTime End { get; set; }
string Name { get; set; }
}
but that doesn't give you a reusable implementation
As a general rule you should prefer composition over inheritance.
So its often better to do something like this
public interface EventDetails
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
public string Name { get; set; }
}
public class SportingEvent
{
public EventDetails Details {get;set;}
}
now this is a bit rough but you can see what I'm getting at.

No, I wouldn't do that. You'll end up creating an abstract God class, which has way to many responsabilities.

I personally would probably make it an abstract class, since not only will your sports share some fields, but they might share some logic too.
Interfaces aren't for seperating out duplicate code, but they're purely for polymorphism.
All an interface does is guarantee that your class will act a certain way. If you plan on putting logic in your base class than you want an abstract class.

Related

ICollection in class

I come across the codes below:
public class Basket
{
public Guid BasketId { get; set; }
public DateTime Date { get; set; }
public virtual ICollection<BasketItem> BasketItems { get; set; }
public Basket()
{
BasketItems = new List<BasketItem>();
}
}
The part I do not quite understand is that why would we put
public virtual ICollection<BasketItem> BasketItems { get; set; }
instead of
public virtual List<BasketItem> BasketItems { get; set; }
One reason I can think of is that when this class is inherited, we can override BasketItems with different types?
What are other reasons of doing so?
Avoiding concrete types when possible is normally a good design practice. It actually buys you a lot of strong advantages which are well documented in the Dependency Inversion Principle of SOLID - SOLID Wikipedia. Long story short, not putting yourself into a corner is good design because it allows the user to extend the property as they see fit and it lowers maintenance because, as an author, you don't have to create a new class type for every implementation of ICollection.
Another big benefit here is unit testing. Avoiding concrete types makes it a lot easier to mock dependencies in unit tests. This leads to test being smaller and more precise. There's a good explanation here of the benefits for more info - How do interfaces making unit testing and mocking easier?
Because BasketItems doesn't need to be a list. Notice that the setter is public. It can also be overridden, as you pointed out.
It's essentially saying, as long as BasketItems is a collection of BasketItem, that's all we need to know. We don't care how the collection is implemented.
one more thing: ICollection is usually used in DataEntity for many-many/one-many relationships as well. You can refer (MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) is a list of object that needs to be iterated through and modified.

To abstract, or not to abstract

thanks in advance for reading this. I don’t fully understand how/when to use abstracts so I am trying to think about it each project I work on to see if it will all click some day Smile | :)
Also, the mix of accessibility levels (private, protected, internal) with keywords static, abstract, and override tend to leave me a little confused. How do I define this method/property/class....
It's not all a big mystery to me but some projects have me coding in circles when dealing with these topics.
With that said,
I have an application that reads an XML document and outputs text and image files. I’m also storing all of the information in a database. I have it working nicely.
The XML has a standard implementation with required fields and is used by multiple organizations to submit data to my app. All organizations should use (at least) the required nodes/elements that are outlined in the XML implementation guide.
So, I want to have a default data object type to be able to derive a specific organization’s data type for required elements. (If this object is going to be used, these are the fields that must be implemented).
If the org. just uses the default requirements, I can use the default object. If they use additional (optional) fields, I’ll have to create a new type inheriting the default type.
My first thought was to use and abstract class that had protected properties for my bare minimum requirements:
public abstract partial class AbstractDataObject
{
protected string DataObjectName;
protected DateTime? DataObjectDate;
etc...
}
Then, if the organization just uses the required elements of the node and no optional elements, I can use a “default” object.
internal partial class DefaultDataObject : AbstractDataObject
{
public new string DataObjectName { get; set; }
public new DateTime? DataObjectDate { get; set; }
etc...
}
But, if an organization uses optional fields of the required node, I can use a derived organization data object.
internal sealed partial class OranizationDataObject : AbstractDataObject
{
public new string DataObjectName { get; set; }
public new DateTime? DataObjectDate { get; set; }
etc...
//Optional fields used by this organization
public string DataObjectCode { get; set; }
etc...
}
Do I need the abstract class? It seems to me I can just have a DefaultDataObject (something like):
internal partial class DefaultDataObject
{
public virtual string DataObjectName { get; set; }
public virtual DateTime? DataObjectDate { get; set; }
etc...
}
And then:
internal sealed partial class OranizationDataObject : DefaultDataObject
{
public override string DataObjectName { get; set; }
public override DateTime? DataObjectDate { get; set; }
etc...
//Optional fields used by this organization
public string DataObjectCode { get; set; }
etc...
}
I’m just really trying to understand how to define these objects so I can reuse them per organization. Both ways seem to work, but I am hoping to understand how to define them properly.
Getting the XML into above objects:
public DefaultDataObject ExtractXmlData(XContainer root)
{
var myObject = (from t in root.
Elements("ElementA").Elements("ElementB")
select new DefaultDataObject()
{
DataObjectName = (String)t.Element("ChildElement1"),
DataObjectDate =
Program.TryParseDateTime((String)
t.Elements("ChildElement2")
.ElementAtOrDefault(0)
),
etc....
OR
public OranizationDataObject ExtractXmlData(XContainer root)
{
var myObject = (from t in root.
Elements("ElementA").Elements("ElementB")
select new OranizationDataObject()
{
DataObjectName = (String)t.Element("ChildElement1"),
DataObjectDate = Program.TryParseDateTime(
(String)t.Elements("ChildElement2")
.ElementAtOrDefault(0)),
DataObjectCode = (String)t.Element("ChildElement3"),
etc....
Again, thanks for reading. Don't forget to tip your wait staff....
Joe
First of all, your base class doesn't need to be abstract if it's a plain DTO class. If you don't have any functionality that needs to be implemented differently by derived classes, you can simply make it a plain base class which will hold common properties.
Next, there is no point in declaring properties in the base class (abstract in your case), if you are going to hide them (using the new keyword). You first code snippet of DefaultDataObject unnecessarily creates a bunch of new properties with the same name. Remove them completely - they are already defined in the base class.
[Edit] I didn't notice this initially, and #svick warned me, that your base class actually contained fields instead of properties, which makes me wonder why you needed to add the new keyword at all. I went over your code quickly and saw them as properties. In any case, you should never expose public fields - at least change them to auto-implemented properties by adding the { get; set; } block.
In other words, this would simply work:
// this doesn't need to be abstract.
// just put all the common stuff inside.
public class BaseDO
{
// as svick pointed out, these should also be properties.
// you should *never* expose public fields in your classes.
public string Name { get; set; }
public DateTime? Date { get; set; }
}
// don't use the new keyword to hide stuff.
// in most cases, you won't need that's behavior
public class DerivedDO : BaseDO
{
// no need to repeat those properties from above,
// only add **different ones**
public string Code { get; set; }
}
As a side note, but nevertheless important IMHO, you should simplify naming (and make it more clearer what your code does). There is no need to repeat "DataObject" in every property name, for example. But since your code is probably only a simplified version, it doesn't matter.
Lastly, have you heard of XmlSerializer? You don't need to traverse the XML elements manually. It is enough to call XmlSerializer to both serialize and deserialize your data.
Everything I need to know I learned from Sesame Street
Scrub your class design hard to make sure you've identified everything that is the same and different. Play computer, so to speak, with your classes and see how they do the same, different, or the same thing but in different ways.
What is the same, different, same but differently will likely change as you play computer.
Think in general terms of the two pillars of OO Classes. Polymorphism and Inheritance
As you do the above that is. Not so much in terms of C# implementation per se.
How things clump into same vs. different will help drive implementation
And it's all relative.
More of same default behavior? Perhaps a concrete base class instead of abstract.
More of same thing, but differently? Perhaps an abstract class instead of concrete base class.
A default way of doing x? Perhaps a virtual method.
Everyone does the same thing, but no two the same way? A delegate perhaps.
Implementation Suggestions
Make methods and fields protected as a default. Private does not get inherited. Designs change, stay flexible. If something just has to be private, fine.
virtual means you can change implementation in a sub class. It does not mean you must.
Folks seem to under-utilize delegates. They're super for polymorphic methods.
There is nothing wrong with public fields. What's the practical difference between a public field and a public auto-implemented property? Nothing. They both directly return (or set) the underlying value. So what's the point of even bothering with properties? If you want to publicly expose an underlying value differently than it's "natural" state. For example, returning a number in a specific format. And of course you can have different properties for the same field.
A Property can have a get without a set. Or vice versa. Also get and set can have different access levels. Often you'll see this as a public get and a protected (or private) set.
It depends on what the derived types will want to do. If they are going to use the default implementation and only expand on it somehow, then having the default class as the non-abstract base class is fine.
On the other hand, if they are most likely going to re-implement the functionality, you should have an abstract base class (or an interface) and a separate default class.
If you for some reason don't know which one is it, you can let the inheritors choose by having an abstract base class and leaving the default class unsealed.
Also, looking at your code, it seems you misunderstand what the various keywords do. Most of the time, you do not want to use new like this. What it does is to define another member with the same name, unrelated to the original one. Also, there's no reason to override something if you don't want to change it. So, if you expect that the derived classes won't have to reimplement the properties, you don't have to make them virtual at all.
An abstract class can already implement things that can be inherited
public abstract class DataObjectBase
{
public string DataObjectName { get; set; }
public DateTime? DataObjectDate { get; set; }
}
A concrete class can add new properties and methods
public class DerivedDataObject : DataObjectBase
{
public int NewProperty { get; set; }
}
The properties DataObjectName and DataObjectDate are already available in the new class, because they are automatically inherited from the base class.
If the abstract class defined an abstract member, however, you would have to implement it in the derived class.
Say the base class defines
public abstract void SomeMethod(string name);
The the derived class has to do this
public override void SomeMethod(string name)
{
...
}
If your base class does not have abstract members, it does not need to be abstract and can play the role of your default data object directly.
The keyword 'partial` is not needed here. It is only useful if you want to split one class into several pieces over several files.
The keyword new is wrong here. It is used to shadow an inherited member. This means that the inherited member will be hidden "behind" the new declaration. What you need, is to override. This does not hide a member, but provide an alternative implementation of the same member in the derived class.

Where should properties reside when modeling OOP? Small example included

I'm looking to learn how to use interfaces and base classes effectively. I'm not exactly sure where to put common properties? Do only behaviors belong in an interface? If properties such as: Color and MinSpeed shouldn't go in the interface, where should they live? In an abstract class?
public interface IVehicle
{
void Speed();
void Clean();
void Stop();
}
public class Bmw : IVehicle
{
// Because these pertain to every vehicle no matter of maker,
// should these propertes go in the interface? Or in an abstract class?
public string Color { get; set; }
public int MinSpeed { get; set; }
#region IVehicle Members
public void Speed()
{
}
public void Clean()
{
}
public void Stop()
{
}
#endregion
}
Interfaces can be thought of as a contract that must be satisfied by any implementing class. Use it if you want to guarentee that all classes do the same thing—satisfy the same API—but you don't care how they do it. If properties are a part of that API, then by all means include them in your interface.
From your example above, if you want all cars to be guaranteed to have a color and minSpeed, then those properties belong in the interface. If those properties are specific to BMWs alone, then they belong in the BMW class. If those properties belong to some classes but not others, you could create a new interface extending the original one:
public interface IVehicleWithColorAndMinSpeed : IVehicle
{
string Color { get; set; }
int MinSpeed { get; set; }
}
(just don't get carried away with this)
Abstract classes are similar, but allow you to provide a default implementation for your sub classes.
Abstract classes tend to be easier to version, since you can add something new to your API, and provide a default implementation that your existing subclasses will automatically pick up; adding something to an interface immediately breaks all existing classes which implement that interface.
The 'right' answer is entirely dependent on your domain model. What is the problem you're trying to solve? There is no 'right' answer other than the one which solves the particular problem at hand with the greatest:
understandability
maintainability
brevity
isolation
performance
You can probably consider most of those properties to be in order of importance, but they mean different things to different people and there's probably a lot of debate implied there too.
Can you tell us any more about the particular application you imagine these classes to serve?

Should entities implement interfaces?

I personally don't have my entities implement interfaces. For a Task class I wouldn't have ITask that just had the same properties defined on it.
I've seen it done a few times though, so I'm wondering where that advice comes from, and what benefits you get from it.
If you're using an ORM then the argument that says "I can change my data access" is irrelevent, so what other reason is there for doing this?
UPDATE:
A good point was made in the comments about INotifyPropertyChanged. That wasn't my point though - I'm talking about having something like this:
public interface ITask
{
int Id { get; set; }
string Description { get; set; }
}
public class Task : ITask
{
public int Id { get; set; }
public string Description { get; set; }
}
I went down this road once (interfaces for value objects). It was a royal pain in the backside, I recommended against it. The common arguments for it are:
Mocking:
They are value objects. Nought to mock. Plus mocking ends up being a large pain than either writing a builder (in Java) or using the named arguments stuff in C#.
Readonly views:
I must admit I still prefer to make something immutable by default, only making it mutable if absolutely required.
Hidden functionality:
Generally scope has covered this one for me.
The major benefit of this is that it is a way of exposing your entity as a "read-only" version (as long as your interface does not expose setters of course).
We're doing quite a bit of unit testing and so often want to mock out things we're not testing. Although I don't like it, we've ended up using interfaces all over the place because it makes it a lot easier to mock things.
In theory most of the mocking frameworks can mock normal classes too, but in practice this has caused us issues because we sometimes do clever things with reflection and the type of the mocked class isn't the same as the original. So doing:
var myTask = MyIoCProvider.Get<Task>();
var taskType = typeof(myTask);
Was unpredictable. Whereas:
var myTask = MyIoCProvider.Get<ITask>();
var taskType = typeof(myTask);
Gives you as taskType that IS definitely derived from ITask.
So interfaces just give us a way of making our system more mockable.
If you were thinking in terms of using DomainEvents than data structures such as the task really do need to implement an interface
public interface IDomainEvent
{
Guid EventId { get; }
Guid TriggeredByEvent { get; }
DateTime Created { get; }
}
public class OrderCancelledEvent : IDomainEvent
{
Guid EventId { get; set; }
Guid TriggeredByEvent { get; set; }
DateTime Created { get; set; }
// And now for the specific bit
int OrderId { get; set; }
}
Or similarly if you have a common data access layer that may need to take in a standard base class of IEntity but I wouldn't have an interface for each type if it is just a data structure as you describe in your post.
When you are handling Domain Objects that actually expose behaviour you may then want to have an interface for unit testing.
I think some programmers just use interfaces, because they heard interfaces are good so they ended using them everywhere without thinking about actual pros and cons.
Me personally, I never use interfaces for entities that only represent a piece of data like db row for example.

Best way to separate read and write concerns using interfaces?

Lately I've been realizing the benefit of (some would argue overuse of) immutable objects to cut down dramatically on read-write dependency issues in my object model and their resulting conditions and side-effects, to ultimately make the code simpler to manage (kind of functional-programming-esque).
This practice has led me to create read-only objects that are provided values at creation/construction time and then to make available only public getters for external callers to access the properties with. Protected, internal and private setters allow internal control to be maintained over writing to the object model.
When creating interfaces while making an API over my object model, I've started considering the same issues about immutability. For example, by providing only public getters on my interfaces, and leaving it up to implementors to decide upon setters and how to handle that aspect.
An example of a "read-only" interface for implementation that I'm talking about is this Valuable Item (just for demonstration):
public interface IValuableItem {
decimal Amount {get;}
string Currency {get;}
}
However I got to wondering how I should provide a companion interface that allows for writing (and if I should), and not combine those operations within the same interface as to not "taint" its immutability.
The following ideas have come to mind, just off the top of my head. Without providing what I think are pros and cons to each, what do you think the best approach is? Is there a coding methodology common in the industry for managing this concept?
// companion writer
public interface IValuableModifier {
decimal Amount {set;}
string Currency {set;}
}
or
// explicit methods to enforce importance of or deviance in the programming
public interface IValuableModifier {
void SetAmount(decimal val);
void SetCurrency(string cur);
}
or
// companion writer that inherits the original interface
public interface IValuableModifier : IValuableItem { //...
or
// Let a concrete class choose one and/or the other.
class Concrete : IValuableModifer, IValuableItem { //...
or
etc...
What else can help me imbue writing on my otherwise immutable programming model and keep it moderately flexible or at least to separate the concerns for better control over it?
I think I might use a variant of your ideas, something like this:
public interface IValuableItem
{
decimal Amount { get; }
string Currency { get; }
}
public interface IMutableValuable : IValuableItem
{
new decimal Amount { set; get; }
new string Currency { set; get; }
}
class Item : IMutableValuable
{
public decimal Amount { get; set; }
public string Currency { get; set; }
}
This way your mutable interface has full getters and setters (I don't think it makes sense to have an interface that has setters but no getters), but any object that implements it will also have an immutable version of the interface that you can use for any pure-functional code.
You should have separate interfaces for ReadableFoo, ImmutableFoo, and MutableFoo. The latter two should inherit from the first. ReadableFoo should contain an "AsImmutable" method which will return a Foo that is guaranteed to be immutable (a immutable instance should return itself; a mutable instances should return a new immutable instance which contains its data), and probably an "AsNewMutable" member (which will create a new mutable instance containing the same data, whether the original was mutable or not).
No class should implement both ImmutableFoo and MutableFoo.
If your objects are to be immutable (and you design your application around the concept of immutable data) then objects really MUST remain immutable.
The canonical method for modifying data in immutable scenarios is to create new objects, so I would suggest something like this:
public interface IValuableItem<T>
{
decimal Amount { get; }
string Currency { get; }
T CreateCopy(decimal amount, string currency);
}
public class SomeImmutableObject : IValuableItem<SomeImmutableObject>
{
public decimal Amount { get; private set; }
public string Currency { get; private set; }
public SomeImmutableObject(decimal amount, string currency)
{
Amount = amount;
Currency = currency;
}
public SomeImmutableObject CreateCopy(decimal amount, string currency)
{
return new SomeImmutableObject(amount, currency);
}
}
SomeImmutableObject obj = new SomeImmutableObject(123.33m, "GBP");
SomeImmutableObject newObj = obj.CreateCopy(120m, obj.Currency);
Consider using a builder pattern: Builder objects construct immutable instances of the core object. .NET Strings are like this - the string object is immutable, and there is a StringBuilder class for efficient construction of string objects. (string + string + string is much less efficient than using a StringBuilder to do the same)
Note also that builder objects exist solely for building the target object - builders are not instances of the target object / do not implement the target interface themselves.
It's worth the effort to make your system run on immutable objects, as immutability washes away a lot of headaches in threading / concurrency / parallel execution scenarios, as well as data caching / data versioning scenarios.
I believe combining your 3rd and 4th choice is a better way to implement mutable & immutable types.
Public interface ImmutableItem {
decimal Amount {get;}
string Currency {get;}
}
Public interface MutableItem: ImmutableItem {
decimal Amount {set;}
string Currency {set;}
}
class Concrete : ImmutableItem {
//Only getters
}
class Concrete : MutableItem {
//Both getters & setters
}
This is clean and it let the concrete classes to decide which kind of mutability is wanted to expose to outer world.

Categories

Resources