Default object implementation - c#

I want to implement default object pattern for my all classes in the inheritance tree. I am doing as shown below.
namespace test
{
public class Record
{
public int ID { get; set; }
}
public class StudentRecord : Record
{
public string StudentID { get; set; }
}
public class DriverRecord : Record
{
public string DLNumber { get; set; }
}
public class client
{
public static void Main()
{
StudentRecord st = StudentRecord.Default;
DriverRecord dr = DriverRecord.Default;
}
}
}
I want the default property or method to initialize all the class level properties to their defaults and I don’t want to repeat the implementation for each class. I just want to write on Record (base ) class . Can you provide some suggestions on this?

What you’re looking for is exactly what constructors are for. A constructor can call an inherited base constructor, so you need to do the base initialisation in only one place. Sometimes the basic functionality really does what you need :)
public class Record
{
public int ID { get; set; }
public Record()
{
// ... do general initialisation here ...
}
}
public class StudentRecord : Record
{
public string StudentID { get; set; }
public StudentRecord()
: base() // This calls the inherited Record constructor,
// so it does all the general initialisation
{
// ... do initialisations specific to StudentRecord here ...
}
}
public class client
{
public static void Main()
{
// This calls the constructor for StudentRecord, which
// in turn calls the constructor for Record.
StudentRecord st = new StudentRecord();
}
}

The Record class can only set the properties which are inherited by StudentRecord and DriverRecord. If you want to set class-specific properties to their default values you have to override the method (I would make a method) and do something like this (for StudentRecord ):
public void override Initialize()
{
base.Reset();
this.StudentId = 0;
}
HTH

You don't have any "class level properties", i.e. static properties, in your code sample. The properties you do have (the instance properties) are already initialized to their defaults -- 0 for integers, null for references, etc.
If you want to define your own defaults -- perhaps ID should default to -1 until you save, and the strings should default to "" -- then that's exactly what constructors are for:
public class Record
{
public Record() { ID = -1; }
public int ID { get; set; }
}
public class StudentRecord : Record
{
public StudentRecord() { StudentID = ""; }
public string StudentID { get; set; }
}
// etc.
If you want something different from either of those, you'll have to explain what you're looking for.

I think Null Object Pattern is what you need.

Related

What pattern can be used to create an object of one class, but fill its properties in different ways?

I have a class like this
public class OwnerWithholding
{
private decimal ManagementFeePct;
private decimal TotalManagementFee;
private decimal OperationalFeesPct;
private decimal TotalOperationalFees;
}
And I have calculation method that create object of this class, fill it with some arithmetic operations, and return this object.
public OwnerWithholding CalculationMethod1(Reservation r, SqlConnection conn)
{
OwnerWithholding result = new OwnerWithholding();
// result.ManagementFeePct = some data from Fees table in DB + value
//from another db - constant value..
// Also with other properties - with some operations on data
//result.TotalManagementFee = ..
// result.OperationalFeesPct = ..
// result. TotalOperationalFees = ..
return result;
}
And now it works fine.
But this calculation method is just one option for populating data.
There is another calculation method, implemented in a completely different way, but filling exactly the same properties of the object. And I may have more of them.
I need a pattern that would allow me to create objects of the same class, just indicating the calculation method that is needed.
I like the strategy pattern , where the algorithms will be the methods that fill the objects that called them.
But it doesn’t look very good.
Maybe a factory method would be more appropriate here, but I don’t know how to implement it.
Edit: Going by the OPs comments now, it looks like just ONE method in the class needs to be set in multiple ways.
The Template pattern (or the Builder) are better fits in this case, not the Factory.
Template Pattern.
a. Abstract Base class that set default properties, but leaves out one property (Get Ingredients) to be populated by the concrete classes.
public abstract class PizzaCreator
{
public abstract string GetIngredients { get; }
public string Bake { get; set; } = "Bake at 400F for 30 minutes";
public string Deliver { get; set; } = "Deliver in custom box";
}
b. Two Pizza classes, for now just overriding the abstract property
public class CheesePizza : PizzaCreator
{
public override string GetIngredients
{
get { return GetMyIngredients(); }
}
string GetMyIngredients()
{
return "Lots of Cheese!";
}
}
public class PepperoniPizza : PizzaCreator
{
public override string GetIngredients
{
get { return GetMyIngredients(); }
}
string GetMyIngredients()
{
return "Lots of Meats!";
}
}
Here I'm creating instances of the Pizza
var pepPizza = new PepperoniPizza();
var chessePizza = new CheesePizza();
You could even have these creations routed through a Factory class/method.
Original answer:
Here is the Abstract Factory Pattern.
This code goes into the Factory class library.
a.ICar interface
public interface ICar
{
string Name { get; set; }
int Doors { get; set; }
string EngineCapacity { get; set; }
}
b.Abstract Car Factory
public abstract class AbstractCarFactory
{
public abstract ICar CreateCar(CarType type);
}
c.Two Concrete Cars -
internal class NissanPickUpTruck : ICar
{
public string Name { get; set; }
public int Doors { get; set ; }
public string EngineCapacity { get ; set ; }
}
internal class NissanSportsCar: ICar
{
public string Name { get; set; }
public int Doors { get; set; }
public string EngineCapacity { get; set; }
}
d.Concrete Factory
public class NissanFactory : AbstractCarFactory
{
public override ICar CreateCar(CarType type)
{
switch (type)
{
case CarType.PickupTruck:
return new NissanPickUpTruck{Name = "Titan", Doors = 6, EngineCapacity = "V12"};
case CarType.SportsCar:
return new NissanSportsCar{Name = "350Z", Doors = 2, EngineCapacity = "V6"};
default:
throw new Exception();
}
}
}
Finally the calls from an external project
var nissanFactory = new NissanFactory();
var sportsCar = nissanFactory.CreateCar(CarType.SportsCar);
var pickUpTruck = nissanFactory.CreateCar(CarType.PickupTruck);
But like the other comment, the Builder is something worth checking out as well.

Structure for Classes containing Lists of Instantiated classes to be stored in Dictionary

For my example classes to be stored are lets say:
class Race
{
public string Name { get; set; }
public DateTime Date { get; set; }
public List<Competitor> Competitors = new List<Competitor>();
}
class Competitor
{
public string Name { get; set; }
public List<Stats> SomeData = new List<Stats>():
}
class Stats
{
//Other Properties Etc
}
They are to be stored in :
class Events : Dictionary<string, List<Race>>
{
public Events()
: base()
{
}
}
And I fill the Dictionary with another class :
class GenerateEventsData
{
public Events newEvents = new Events();
public GenerateEventsData()
{
fillEvents();
}
private void fillEvents()
{
//Method to fill events.
}
}
I feel as though I'm getting to a stage where lists of classes are being stacked up and my structure is not correct.
I plan to eventually serialize the data to disk and re-use at a later date but that's beyond the bounds of this question. However if the classes aren't well structured i think i may have issues.
Thanks in advance.
you could use a generic container:
public class ListDictionary<T> : Dictionary<string,List<T>>
{
public ListDictionary():base(){}
public void AddItem(string key, T value)
{
if(ContainsKey(key))
this[key].Add(value);
else
Add(key,new List<T>{value});
}
//similar for remove and get
}
Also have a look at the repository pattern.

DRY principle when working with multiple method signatures

With the DRY principle in mind, how would you tackle almost identical methods (with different signatures) that work with an IEnumerable. I.e. one signature works with a specific type parameter. My question extends to the calling of private methods, and their multiple signatures.
I don't want to have two methods with identical logic - If something changes then I have to change both sets of logic. The calling of the private methods for example, how can I make the private method accept either type of IEnumerable
public class Person
{
public string Name {get; set;}
public string Age {get; set;}
}
public class SupremeBeing : Person
{
public string Power {get; set;}
}
public class Payroll
{
public void DoSomething(IEnumerable<Person> peopleIn)
{
// Do this with peopleIn
// Do that with peopleIn
// Call private method passing in peopleIn (which also has 2 signatures)
}
public void DoSomething(IEnumerable<SupremeBeing> peopleIn)
{
// Do this with peopleIn
// Do that with peopleIn
// Call private method passing in peopleIn (which also has 2 signatures)
}
}
It looks to me like what you want is more abstraction on the Payroll Class
public abstract class PayrollBase<T> where T : Person
{
public void DoSomething(IEnumerable<T> peopleIn)
{
// Do this with peopleIn
// Do that with peopleIn
this.InternalLogic(peopleIn);
}
protected virtual InternalLogic(IEnumerable<T> peopleIn)
{
// do something super special
}
}
You would then implement this for your specific types
public PersonPayroll : PayrollBase<Person>
{
protected override InternalLogic(IEnumerable<Person> peopleIn)
{ ... }
}
public SupremeBeingPayroll : PayrollBase<SupremeBeing>
{
protected override InternalLogic(IEnumerable<SupremeBeing> peopleIn)
{ ... }
}
You would then use some form of factory class to instantiate the right "Payroll" for the list of people you're dealing with.
The object oriented approach would be to make the classes handle their differences themselves. You can for example use virtual methods to have one implementation for each class.
When you can treat every object as a Person object regardless of the actual type, then you only need one set of methods to handle the payroll, and you wouldn't need to call it with separate lists for each class, you can put them all in the same list and call the method.
Example:
public class Person {
public string Name {get; set;}
public string Age {get; set;}
virtual public int Salary { get { return 1000 + Age * 10; } }
override public string ToString() {
return Name + "(" + Age + ")";
}
}
public class SupremeBeing : Person {
public string Power {get; set;}
override public int Salary { get { return 5000 + Age * 7; } }
override public string ToString() {
return Power + " " + Name;
}
}
public class Payroll {
public void DoSomething(IEnumerable<Person> peopleIn) {
foreach (Person p in peopleIn) {
Console.log("{0} earns {1}", p, p.Salary);
}
}
}
One option is to call the first method from the second:
public void DoSomething(IEnumerable<SupremeBeing> peopleIn)
{
this.DoSomething(peopleIn.Cast<Person>());
// do SupremeBeing specific stuff
}
Another option is to have a private method which does all the Person stuff.
public void DoSomething(IEnumerable<SupremeBeing> peopleIn)
{
this.DoSomethingWithPersons(peopleIn);
}
public void DoSomething(IEnumerable<Person> peopleIn)
{
this.DoSomethingWithPersons(peopleIn);
}
private void DoSomethingWithPersons(IEnumerable<Person> peopleIn)
{
// do stuff
}
Subtle differences between the two options without more information it's hard to know which would be better.
I don't understand your problem. You could create a generic method which does your generic stuff and then create a method which could be overridden for your special stuff.
Like:
class Something
{
protected virtual void DoSomethingSpecial<TYPE>(TYPE item)
{
}
public void DoSomethingy<TYPE>(IEnumerable<TYPE> items)
{
foreach(TYPE item in items)
{
// do whatever you have to do for every type
// do whatever you have to do in special
this.DoSomethingSpecial(item)
}
}
}
Code not tested just typed.
And then create one class for every special case. In these classes you just override DoSomethingSpecial for every type and you're done.
You could just have the Payroll class sort out the different types of Persons after it has run all the common operations and forward people to the appropriate extended methods.
interface IPerson {
string Name { get; set; }
string Age { get; set; }
}
public class Person : IPerson {
public string Name { get; set; }
public string Age { get; set; }
}
public class SupremeBeing : Person
{
public string Power { get; set; }
}
public class Payroll
{
public void DoSomething(IEnumerable<IPerson> peopleIn)
{
//..everyone does this and that
IEnumerable<Person> NormalPeople = peopleIn.OfType<Person>();
if (NormalPeople.Count() > 0) DoSomethingNormalSpecific(NormalPeople);
IEnumerable<SupremeBeing> SupremeBeings = peopleIn.OfType<SupremeBeing>();
if (SupremeBeings.Count() > 0) DoSomethingSupremeSpecific(SupremeBeings);
}
public void DoSomethingNormalSpecific(IEnumerable<Person> normalPeopleIn)
{
// just normal people
}
public void DoSomethingSupremeSpecific(IEnumerable<SupremeBeing> supremeBeingsIn)
{
// just Supreme Beings
}
}

Facade a class without writing lots of boilerplate code?

Let's say I have a class from a 3rd-party, which is a data-model. It has perhaps 100 properties (some with public setters and getters, others with public getters but private setters). Let's call this class ContosoEmployeeModel
I want to facade this class with an interface (INavigationItem, which has Name and DBID properties) to allow it to be used in my application (it's a PowerShell provider, but that's not important right now). However, it also needs to be usable as a ContosoEmployeeModel.
My initial implementation looked like this:
public class ContosoEmployeeModel
{
// Note this class is not under my control. I'm supplied
// an instance of it that I have to work with.
public DateTime EmployeeDateOfBirth { get; set; }
// and 99 other properties.
}
public class FacadedEmployeeModel : ContosoEmployeeModel, INavigationItem
{
private ContosoEmployeeModel model;
public FacadedEmployeeModel(ContosoEmployeeModel model)
{
this.model = model;
}
// INavigationItem properties
string INavigationItem.Name { get; set;}
int INavigationItem.DBID { get; set;}
// ContosoEmployeeModel properties
public DateTime EmployeeDateOfBirth
{
get { return this.model.EmployeeDateOfBirth; }
set { this.model.EmployeeDateOfBirth = value; }
}
// And now write 99 more properties that look like this :-(
}
However, it's clear that this will involve writing a huge amount of boilerplate code to expose all the properties , and I'd rather avoid this if I can. I can T4 code-generate this code in a partial class, and will do if there aren't any better ideas, but I though I'd ask here to see if anyone had any better ideas using some super wizzy bit of C# magic
Please note - the API I use to obtain the ContosoEmployeeModel can only return a ContosoEmployeeModel - I can't extend it to return a FacededEmployeeModel, so wrapping the model is the only solution I can think of - I'm happy to be corrected though :)
The other approach may be suitable for you is to use AutoMapper to map base class to your facade here is sample code:
class Program
{
static void Main(string[] args)
{
var model = new Model { Count = 123, Date = DateTime.Now, Name = "Some name" };
Mapper.CreateMap<Model, FacadeForModel>();
var mappedObject = AutoMapper.Mapper.Map<FacadeForModel>(model);
Console.WriteLine(mappedObject);
Console.ReadLine();
}
class Model
{
public string Name { get; set; }
public DateTime Date { get; set; }
public int Count { get; set; }
}
interface INavigationItem
{
int Id { get; set; }
string OtherProp { get; set; }
}
class FacadeForModel : Model, INavigationItem
{
public int Id { get; set; }
public string OtherProp { get; set; }
}
}
Resharper allows the creation of "delegating members", which copies the interface of a contained object onto the containing object and tunnels the method calls/property access through to the contained object.
http://www.jetbrains.com/resharper/webhelp/Code_Generation__Delegating_Members.html
Once you've done that, you can then extract an interface on your proxy class.

.NET - how to make a class such that only one other specific class can instantiate it?

I'd like to have the following setup:
class Descriptor
{
public string Name { get; private set; }
public IList<Parameter> Parameters { get; private set; } // Set to ReadOnlyCollection
private Descrtiptor() { }
public Descriptor GetByName(string Name) { // Magic here, caching, loading, parsing, etc. }
}
class Parameter
{
public string Name { get; private set; }
public string Valuie { get; private set; }
}
The whole structure will be read-only once loaded from an XML file. I'd like to make it so, that only the Descriptor class can instantiate a Parameter.
One way to do this would be to make an IParameter interface and then make Parameter class private in the Descriptor class, but in real-world usage the Parameter will have several properties, and I'd like to avoid redefining them twice.
Is this somehow possible?
Make it a private nested class that implements a particular interface. Then, only the outer class can instantiate it, but anyone can consume it (through the interface). Example:
interface IParameter
{
string Name { get; }
string Value { get; }
}
class Descriptor
{
public string Name { get; private set; }
public IList<IParameter> Parameters { get; private set; }
private Descriptor() { }
public Descriptor GetByName(string Name) { ... }
class Parameter : IParameter
{
public string Name { get; private set; }
public string Value { get; private set; }
}
}
If you really must avoid the interface, you can create a public abstract class that has all of the properties but declares a protected constructor. You can then create a private nested class that inherits from the public abstract that can only be created by the outer class and return instances of it as the base type. Example:
public abstract AbstractParameter
{
public string Name { get; protected set; }
public string Value { get; protected set; }
}
class Descriptor
{
public string Name { get; private set; }
public IList<AbstractParameter> Parameters { get; private set; }
private Descriptor() { }
public Descriptor GetByName(string Name) { ... }
private class NestedParameter : AbstractParameter
{
public NestedParameter() { /* whatever goes here */ }
}
}
LBushkin has the right idea. If you want to avoid having to retype all the properties just right-click the name of the class and choose "Refactor" > "Extract Interface", that should give you an interface that contains all those properties. (This works in VS 2008, I don't know about earlier versions.)
C# generally takes the approach that instead of avoiding redundant code, VS will just help you write it faster.
You could use a constructor marked Internal.
That way it's public to classes in the assembly, and private to classes outside of it.
Mark the class to be "protected" from instantiation (Parameter) with the StrongNameIdentityPermission attribute and the SecurityAction.LinkDemand option:
[StrongNameIdentityPermission(SecurityAction.LinkDemand, PublicKey="...")]
class Parameter
{
...
}
You will need to provide the appropriate public key. Because you are demanding a link-time (JIT-time, in fact) check on the Parameterclass, this means that it can only be used from an assembly that is signed with a strong name that uses the private key matching the public key that you supply in the attribute constructor above. Of course, you will need to put the Descriptor class in a separate assembly and give it a strong name accordingly.
I have used this technique in a couple of applications and it worked very well.
Hope this helps.
If you want only the Descriptor class to instantiate a Parameter, then you can make the Descriptor class a nested class of Parameter. (NOT the other way around) This is counterintuitive as the container or parent class is the nested class.
public class Parameter
{
private Parameter() { }
public string Name { get; private set; }
public string Value { get; private set; }
public static Parameter.Descriptor GetDescriptorByName(string Name)
{
return Parameter.Descriptor.GetByName(Name);
}
public class Descriptor
{ // Only class with access to private Parameter constructor
private Descriptor() { // Initialize Parameters }
public IList<Parameter> Parameters { get; private set; } // Set to ReadOnlyCollection
public string Name { get; private set; }
public static Descriptor GetByName(string Name) { // Magic here, caching, loading, parsing, etc. }
}
}
There is another way: check the call stack for the calling type.

Categories

Resources