decorating classes with properties to avoid duplication - c#

I am trying to work out the best way to approach the following ..
i need to pass AvailabilityOption/LimitedAvailabilityOption types to - well a service as it happens, and then get back BookingOption types.
I have routines which will generate the availability types, but am unsure if i need to go through each of my Option objects effectively duplicating versions of them inheriting from BookingOption and AvailabilityOption in turn. or can I do some sort of 'Decoration' of the simple options with the availability classes and then cast them back down to booking ones when i pass them back again.
I know there is a decoration pattern but having read a bit about this it appears that it is more about decorating at runtime.. I may well be misunderstanding.
I suspect I havent explained this very well but here is some code..
EDIT: effectively the option is a base for a number of possible options on a booking - such as an excursion or some other extra, of which there are quite afew. the availability extends that to determine what space there is on any option, but it is just extending the option itself, with the price and possibly the numbers already booked on that option.
the BookingOption is there to be returned from the routine that effectively chooses from the options based on their price and availability. I am just trying to return the bare minimum at the booking point, which is really the date when the option is required and which option it is. the availability at this point is moot..
public abstract class Option{
public int OptionID { get; set; }
public OptionType OptionType { get; set; }
public string EqtCode { get; set; }
public string CentreCode { get; set; }
public virtual string Description { get; set; }
}
public abstract BookingOption : Option{
public DateTime WeekStartDate{get;set;}
}
public abstract class AvailabilityOption : BookingOption {
public decimal Price{get;set;}
public override string Description{
get{return string.format("{0} # {1}", base.Description, Price.ToString());
set{ base.Description = value;}
}
}
public abstract class LimitedAvailabilityOption : AvailabilityOption{
public int MinNumber { get; set; }
public int MaxNumber { get; set; }
public int TotalBooked { get; set; }
public int TotalRemaining { get; set; }
public override string Description
{
get
{
return string.Format("{0} ({1} # {2})",
base.Description, TotalRemaining.ToString(), Price.ToString());
}
set { base.Description = value;}
}
}
public class Option1 : Option{
public Option1(){}
}
public class Option2 : Option{
public Option2(){}
}
public List<BookingOption> BookWithAvail(List<AvailabiliyOption> options){
//pick options based on avail and pass back the booking versions so write away...
}

It looks like answer depends on how you plan to use Availability and Limited availabilitty qualities of essences. If those availability-qualities are only applicable to LimitedAvailabilityOption and AvailabilityOption classes - than it does not seems there is a big need of implementation Availability or LimitedAvailability in separate classes, as each of those classes will be used to distinguish only one kind of other essences (LimitedAvailabilityOption and AvailabilityOption respectively). It would make sense to use decoration pattern and implement classes for Availability and Limited availability qualities only if you plan assign each of them to multiple essences that are not connected with inheritance relationship (including inheritance through intermediate classes). And if you plan to spread usage of availability-qualities across multiple classes that are not supposed to have any inheritance connection via common ancestor that has availability property - then the only choice is to extract those availability qualities into separate classes.

Related

Do empty properties take up bandwidth when sending a class over WCF?

We want to send two collections of objects out of a WCF service. The classes for the two objects share some common properties, and each have others, unique to them...
public class TypeA {
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
public string D { get; set; }
}
public class TypeB {
public string A { get; set; }
public string B { get; set; }
public string E { get; set; }
public string F { get; set; }
}
Yes I could/should use a common base class, but that isn't the question here
One the one hand, having two classes like this means that each class only has the properties it needs, which keeps it slim and focused. On the other hand, as these are basically two different views of the same underlying object, it's perfectly reasonable to combine them, and just populate the properties needed.
I can't find a way of seeing how big the WCF payload is, so don't know if using one common class is going to consume more bandwidth than using specific classes. I need this to be as efficient as possible.
Anyone know if using one common class is going to increase the WCF payload? If so, any way of find out how much?
You can put the XmlSerializerFormat attribute on your services in order to force WCF to use ASP.NET serialization engine when sending your objects. This will allow you to use other attributes and methods to take full control over which properties are serialized.
Then, you can restrict properties from being serialized using two methods:
1. Implement a ShouldSerializeXXXX() method
2. Use the DefaultValue attribute. Properties which already have the default value are not serialized.
Example:
[XmlSerializerFormat, ServiceContract]
public interface IMyService
{
[OperationContract]
MyData GetData();
}
[DataContract]
public class MyData
{
[XmlAttribute, DataMember]
public int Value1 { get; set; }
// Explicit method to control serialization of Value1 property
public bool ShouldSerializeValue1()
{
// do not serialize this value if it's 0
return Value1 != 0;
}
// Use default value of 0 to prevent serializing zeros
[XmlAttribute, DataMember, DefaultValue(0)]
public int Value2 { get; set; }
}
I would be more concerned with the data transfer type you are using if you are worried about packet size. For example, if you are using the SOAP protocol, then your packet size is going to be very large and instead of worrying about base classes to objects, you could shrink down your packet size tremendously by switching to binary, or even JSON. See here for reference: https://dzone.com/articles/wcf-rest-xml-json-or-both
Also, to inspect true packet size I would install 'fiddler' on your machine and inspect the data as it goes over the network.
I hope that sets you on the correct path...

Not sure which solution to choose (property used across two domain models, shared validation)

I've got 2 classes with many different properties and one similar property:
public class A
{
// Lots of specific properties
[Display(Name="Dun and bradstreet number")]
public string DunAndBradstreetNumber {get;set;}
}
public class B
{
// Lots of specific properties
[Display(Name="Dun and bradstreet number")]
public string DunAndBradstreetNumber {get;set;}
}
I realise I have an abundance of choice and I just want to make sure i'm choosing the most semantically correct and popular choice.
1:-----------
Should I declare another class:
public class DunAndBradstreetNumber
{
[Display(Name="Dun and bradstreet number")]
public string DunAndBradstreetNumber {get;set;}
}
and then make class A and B have pointers inside them eg.?
public class A
{
public DunAndBradstreetNumber DunAndBradstreetNumber { get; set; }
}
or
2:-----------
inherit from the DunAndBradstreetNumber?
public class A : DunAndBradstreetNumber
{
//...
}
3:-----------
declare a global function and put that in the get method of each DunAndBradstreetNumber?
public class A
{
public string DunAndBradstreetNumber {
get
{
// Run some function that I may need help on to apply property validation via attributes to
}
set;
}
}
Any more better choices?
My class A and B are domain models using entityframework if that helps at all.
The problem i'm trying to solve is to not have to declare the validation and display attributes twice in different models.
P.S - your opinion is fine... I just want to know the eventualities of the choice I have to make here (albeit its relative insignificance).

C# basic property understanding

I am learning C# and i have encounter the following piece of code
public class Album
{
public virtual int AlbumId { get; set; }
public virtual int GenreId { get; set; }
public virtual int ArtistId { get; set; }
public virtual string Title { get; set; }
public virtual decimal Price { get; set; }
public virtual string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
just wondering what's the different with the following? i mean without the get and set you can access those public property as well. what's make it important to have those get and set?
public class Album
{
public virtual int AlbumId;
public virtual int GenreId;
public virtual int ArtistId;
public virtual string Title;
public virtual decimal Price;
public virtual string AlbumArtUrl;
public virtual Genre Genre;
public virtual Artist Artist;
}
To have control over your object private fields values. for example if you don't wanna allow nulls or negative values for integers.
bool started;
public bool Started
{
get { return started; }
set
{
started = value;
if (started)
OnStarted(EventArgs.Empty);
}
}
another example
int positiveNumber;
public int PositiveNumber
{
get { return positiveNumber; }
set {
if (value < 0)
positiveNumber = 0;
else positiveNumber = value;
}
}
and also another implementation of read only properties could be as follows
int positiveNumber;
public int PositiveNumber
{
get { return positiveNumber; }
}
You can't declare a virtual field
public class Album
{
public virtual int AlbumId; // <- Syntax error
...
}
properties are, in fact, methods: get or(and) set, so
public class Album
{
public virtual int AlbumId { get; set; } // <- Both get and set methods declared as virtual ones
...
}
And you can override these get's or(and) set's in derived class if you want:
public class GreatAlbum: Album {
private Boolean m_IsGreat;
public override int AlbumId {
get {
if (m_IsGreat)
return base.AlbumId
else
return 0;
}
set {
m_IsGreat = (value != 0);
base.AlbumId = value;
}
}
...
}
With providing get(accessor) and set(mutator) methods, you can control accessing and mutating.
For example:
You have a property that you don't want to be set any value more than 15. So u make required restrictions in your set method. Unless that set method, you can't control.
But in your example, your get and set methods are default, means controlling nothing.
The main reason behind properties is to protecting and presenting private data in a controlled way.
In fact, properties show their abilties in the usage like this:
public virtual int AlbumId
{
get { // ... some magical operations ... }
set { // ... some magical operations ... }
}
And about your main question - what's the difference in this example - the main point to attention is the virtual keyword.
This keyword causes the property to be overrideable, So any other code could override the default get; method. It meens that you have the default behavior for yourself, and other codes (Extremely used in Entity Framework) implement their own logic!
Those second ones in your example aren't properties, so they don't express this magical ability...!
In the first case you are dealing with properties, in the second with fields.
Using fields has several drawbacks when compared to using properties. These drawbacks include:
You can set a breakpoint in a get or set of a property, but you can not set a breakpoint on access to the field.
Making fields public violates the information hiding principle.
The binary MSIL code for accessing fields and properties is different, so if you change a public field to a public property in the future, although the source code stays compatible, any dependant binary code breaks.
The code required to use reflection is different, hence when you move from a field to a property, your reflection code will break.
To cut a long story short: Always use public properties, NEVER use public fields.
There are a number of differences:
Properties are turned into methods by the compiler. As such, you can declare them virtual and override them in a derived class.
Using properties, you can put logic in the getter or setter (filtering, validation etc).
When you use automatically implemented properties ({ get;set;}), it may seem that you might as well just use public fields. However, using properties means you can change your getter or setter implementation at a later time, without changing the interface your class is exposing. If you had used a field and wanted to implement filtering whenever that field was read, you would have to introduce a new method, make the field private and break all existing consumers of the type.
Personally, I think the automatically implemented properties promote bad style, because they do not encourage encapsulation. Tools like ReSharper also like to generate properties with {get;set} accessors. Novice developers thus typically end up with classes with lots of {get;set;} properties exposing the type's state to the world. You should at least use {get; private set;} by default.

Have a wrapper object expose its wrapee's properties

I'm currently trying to figure out how to have a wrapper class expose the properties of whatever it is wrapping without having to manually set them one by one in the wrapper class. I've been trying to figure out if this is even a good design choice or if I'm totally misguided and going off into a very bad placeā„¢ by doing this.
I also already have my wrapper class inheriting something...
Example code below (fake objects so don't read into them please):
public class Car {
public String Name { get; set; }
public String Status { get; set; }
public String Type { get; set; }
public Car(takes params) {
// makes car!
}
}
public class CarWrapper : OtherAutomotiveRelatedThing {
public Car car;
public CarWrapper(Car c) {
car = c;
}
}
public class OtherAutomotiveRelatedThing {
public String Property1 { get; protected set; }
public String Property2 { get; protected set; }
}
I'm using inheritance on the wrapper object because I can not modify the base Car class and it needs the properties of other automotive thing. Multiple other classes inherit from OtherAutomotiveRelatedThing as well.
I return a list of the CarWrapper objects as Json (because I'm building a web app) and the wrapper object is causing problems for me. When cast/converted to Json the CarWrapper objects in the list all contain another nested object - the Car object and the framework I'm using can't get at its properties to do what it needs.
Is there a way to expose the wrapped Car object's properties at the "top level" of the CarWrapper without doing the following:
public class CarWrapper : OtherAutomotiveRelatedThing {
public Car car;
public String Name { get; private set; }
public String Status { get; private set; }
public String Type { get; private set; }
public CarWrapper(Car c) {
car = c;
this.Name = c.Name;
this.Status = c.Status;
this.Type = c.Type;
}
}
Please let me know if I'm not being clear, if you have any questions, or need/want more info.
Thanks!
For me it looks like you want prototype-style programming like in JavaScript, which is not they use in OOP.
Maybe it's good start to think of it as "If I have two different car wrappers (with differnt properties set), how should I pass any of them a method?" or "Can I have a single wrapper which wraps Car and Animal", and "How to expose public property which has the same name but different meaning for Car and Animal, like skin color?" etc
Answers may help you identify if you need say interfaces, or wrappers which expose public objects, or pure encapsulation, or changing language to say JavaScript.

Downcast on POCO classes

I have a group of POCO classes:
class ReportBase
{
public string Name { get; set; }
public int CustomerID { get; set; }
}
class PurchaseReport : ReportBase
{
public int NumberOfPurchases { get; set; }
public double TotalPurchases { get; set; }
public bool IsVip { get; set; }
}
class SaleReport : ReportBase
{
public int NumberOfSales { get; set; }
public double TotalSales { get; set; }
}
I have a web method to return ReportBase. The caller uses the return value to update UI(WPF) based on the actually type by downcasting and checking the type (one grid for sale and one for purchase). Someone suggested to use three web methods and each return the specific type.
I understand that downcast is in general against design principle by introducing if/else. Instead we should use virtual functions. But in POCO class, we don't really have virtual behaviors (only extra fields).
Are you for or against downcast in this case, why?
IMO it's all about intention. Returning just the base class doesn't say anything, especially as you return it only to save some key strokes. As a developer what do you prefer?
ReportBase GetReport() // if type==x downcast.
//or
PurchaseReport GetPurchaseReport()
SaleReport GetSalesReport()
What approach would you want to use to make the code more maintainable? Checking type and downcasting is an implementation detail after all and you probably have a method like this
public void AssignReport(ReportBase report)
{
//check, cast and dispatch to the suitable UI
}
What's wrong with this? It's lacking transparency, and this method should always know about what reports are needed by what UI elements. Any time you add/remove an element you have to modify this method too.
I think is much clear and maintainable something like this
salesGrid.DataSource=repository.GetSalesReport();
purchaseGrid.DataSource=repository.GetPurchaseReport();
than this
var report=repository.GetReport();
AssignReport(report); //all UI elements have their data assigned here or only 2 grids?
So I think that, POCO or not, I will favour the three web methods approach.

Categories