I have a class which takes multiple collections, and then needs to perform calculations on these collections in a particular order. E.G.
public class ClassCalc
{
public ClassCalc(double varEm,
List<List<double>> col1,
List<List<double>> col2)
{
//set fields etc.
}
public void CalcCols(){
//here, I will 'zip' col1/col2 to create List<double> for each
}
public void CalcStep2(){
//this is dependent on the results from CalcCols()
}
public void CalcNonDependent(){
//this can be called at any stage
}
}
The constructor forces the client to supply the relevant data, so there's an obvious ways to do this, by calling the methods in the constructor, this way, I know that everything will be populated. But, this doesn't seem like a clean solution, especially when I want to unit test parts of the code.
If I want to unit test CalcNonDependent(), I need to fully initialize the object, when I might not even require the result of the other two calculations.
So, my question, is there a pattern that can be used for this particular scenario; I have looked at Chain of Responsibility & Command Pattern, but wondered if anyone has any suggestions
Have you looked at Template? Not sure if it applies to your situation 100% but you would have a base class which defines 3 abstract methods and then calls them in the correct order.
class SomeBaseClass
{
public abstract void CalcCols();
public abstract void CalcStep2();
public abstract void CalcNonDependent();
public void DoAllCalculations()
{
CalcCols();
CalcStep2();
CalcNonDependent();
}
}
Then you inherit from this class and provide concrete implementations of your calculation methods.
I recommend concentrating on code coverage rather than method coverage. This way you can make the methods private and expose a single method that calls all 3 methods providing 100% coverage for the class. If you are concerned with dividing the tests for performance reasons then you can further subdivide the tests into groups which perform nightly long running tests vs daily/with every checkin tests.
The command pattern isn't going to solve much in the way of making the class more test-able. I would use such a pattern if you needed runtime workflow adaptation (E.G. M1(), M2(), then M2(), M1(), then M2(), M3() etc).
For example,
public class ClassCalc
{
public ClassCalc(double varEm,
List<List<double>> col1,
List<List<double>> col2)
{
//set fields etc.
}
public void DoWork()
{
//Run methods in order.
}
private void CalcCols(){
//here, I will 'zip' col1/col2 to create List<double> for each
}
private void CalcStep2(){
//this is dependent on the results from CalcCols()
}
private void CalcNonDependent(){
//this can be called at any stage
}
}
You seem to be making a complicated problem out of nothing. Just change the class to:
public class ClassCalc
{
public ClassCalc(double varEm,
List<List<double>> col1,
List<List<double>> col2)
{
//set fields etc.
}
public void CalcCols()
{
//here, I will 'zip' col1/col2 to create List<double> for each
CalcStep2();
}
public void CalcNonDependent()
{
//this can be called at any stage
}
private void CalcStep2()
{
}
}
If for CalcStep2 it is necessary that CalcCols has been executed, why not keep a flag to keep track of it, and include in CalcStep2 something like
if (!CalcColsHasBeenDone)
CalcCols();
Of course, don't forget to set CalcColsHasBeenDone to true at the end of CalcCols :)
You might want to extract an interface for your public operation, and expose only a single public method through it.
Using this in conjunction with e.g. P.Brian.Mackey's answer will make the other methods invisible from a clients perspective, while they can still be public in the implementing class, thus allowing for unit testing if needed.
Related
I have an interface:
interface ISqlite
{
void insert();
void update();
void delete();
void select();
}
And custom service class:
class SqliteService
{
public SQLiteDatabase driver;
public SqliteService() {
SqliteConnection(new SQLiteDatabase());
}
public void SqliteConnection(SQLiteDatabase driver)
{
this.driver = driver;
}
public void select(ISqlite select) {
select.select();
}
public void insert(ISqlite insert) {
insert.insert();
}
public void delete(ISqlite delete)
{
delete.delete();
}
}
And last class Pacients that realizes ISqlite interface:
class Pacients: ISqlite
{
public List<ClientJson> pacients;
public Pacients() {
this.pacients = new List<ClientJson>();
}
public void add(ClientJson data) {
this.pacients.Add(data);
}
public void insert()
{
throw new NotImplementedException();
}
/* Others methos from interface */
}
I try to use my code like as:
/* Create instance of service class */
SqliteService serviceSqlite = new SqliteService();
/* Create instance of class */
Pacients pacient = new Pacients();
pacient.add(client);
serviceSqlite.insert(pacient);
As you can see above I send object pacient that realizes interface ISqlite to service. It means that will be called method insert from object pacient.
Problem is that I dont understand how to add data in this method using external class: SQLiteDatabase()? How to get access to this.driver in service class from object pacient?
Edit 1
I think I must move instance of connection new SQLiteDatabase() to db inside Pacients class is not it?
Generally speaking, I would favor a solution where the data objects themselves don't know anything about how they're stored, i.e. they have no knowledge of the class that communicates with the database. Many ORMs do just that.
Of course it might not be easy depending on the specifics of your situation... Try to examine what your methods on each object actually need; generally speaking they need the values of properties, and what column each property corresponds to, right? So any external class can do this if it knows these bits of information. You can specify the name of the column with a custom attribute on each property (and if the attribute isn't there, the column must have the same name as the property).
And again, this is the most basic thing that ORMs (Object Relational Mappers) do, and in addition they also manage more complicated things like relationships between objects/tables. I'm sure there are many ORMs that work with SqlLite. If you're OK with taking the time to learn the specifics of an ORM, that's what I would recommend using - although they're not silver bullets and will never satisfy all possible requirements, they are in my opinion perfect for automating the most common day to day things.
More to the point of the question, you can of course make it work like that if you pass the SQLiteDatabase object to the methods, or keep it in a private field and require it in the constructor or otherwise make sure that it's available when you need it; there's no other simple solution I can think of. And like you pointed out, it implies a certain degree of coupling.
You can change the signature of interface's methods to pass an SQLiteDatabase object.
interface ISqlite
{
void insert(SQLiteDatabase driver);
void update(SQLiteDatabase driver);
void delete(SQLiteDatabase driver);
void select(SQLiteDatabase driver);
}
Example call from the service:
public void insert(ISqlite insert)
{
insert.insert(driver);
}
I think you can figure out the rest by yourself.
Like many other posts I've found on SO, I'm trying to get my head around delegates. Hopefully this example is not classed a duplicate because I am asking a specific question about a particular example.
public delegate void HelloFunctionDelegate(string message);
public class Delegate
{
static void Main()
{
HelloFunctionDelegate del = new HelloFunctionDelegate(GoodNight); // delegate will point to the GoodNight method
del("Hello"); // invoke the delegate
}
public static void GoodMorning(string strMessage)
{
Console.WriteLine(strMessage + " and good morning!");
Console.ReadKey();
}
public static void GoodNight(string strMessage)
{
Console.WriteLine(strMessage + " and good night!");
Console.ReadKey();
}
}
So in my example I understand that my delegate is a reference to any function that matches its signature and if I pass in GoodMorning I will see:
Hello and good morning!
and if I pass in GoodNight I will see: Hello and good night!
So its kind of like going through a middle man...
I don't understand is what's the point, why wouldn't I just directly call my GoodMorning / GoodNight methods as and when I need to use them?
Maybe there are better examples for when a delegate is useful, but in this example, why don't I just bypass the middle man?
Since you are asking concretely about this example and not in general: There is no point to doing that in this particular piece of code. It teaches you the mechanics of delegates but it does not teach you the point of using them.
In short, the point is that some piece of code can take a reference to a method without knowing what method it will actually receive. It can later call that delegate at will. That enables more abstractions than otherwise possible.
Consider you have the following delegate:
public delegate void CarEvent(Car car);
And then you have an implementation like the following:
public class Car : DataRecord
{
// An event to execute when the record is deleted
public CarEvent OnDelete { get; set; }
public void Delete()
{
this.DeleteRecord(); // Deletes this record from ex. the database
if (OnDelete)
{
OnDelete(this); // Executes the event
}
}
}
By using a delegate you can subscribe different methods to the OnDelete allowing you to do different things when the record is deleted.
Ex. you can make it so when the record is deleted it's deleted from a "ListView" that holds it.
public class CarList : ListView
{
public CarList()
: base()
{
foreach (var car in CarRecords.LoadCars())
{
var listViewItem = new ListViewItem(car);
car.OnDelete = this.DeleteCarFromList;
this.Items.Add(listViewItem);
}
}
private void DeleteCarFromList(Car deletedCar)
{
this.Items.Remove(deletedCar);
}
}
Of course the above is a rough example and there is a lot more things and different kind of situations where you can use delegates and most notably if you want to use them for events you should consider implementing them using the event keyword. - https://msdn.microsoft.com/en-us/library/awbftdfh.aspx
All in all you want to use delegates when the behavior may differ depending on the overall implementation of something. Like you might want to do one thing in one situation and something else in another situation, but they should both over-all do the same thing.
If you do not need different behaviors based on implementation then there's no need to use delegates. You'd always want to call a method directly if possible.
I hope this explained it okay.
In the below class I have a public method called ProcessMessage. This method is responsible for processing the incoming messages. Processing a message involves different stage. I want to decorate this class in such a way that I can publish performance counter values from each stage of the message processing.
I know I can override the ProcessMessage method and rewrite the logic once again with publishing performance counter values. But is there any better way / pattern which I can apply, so that I don’t have to duplicate the logic once again in the decorated class.
public class MessageProcessor
{
public void ProcessMessage()
{
ConvertReceivedMessage();
SendToThirdParty();
ReceiveResponse();
ConvertResponseMessage();
SendResponseToClient();
}
private void ConvertReceivedMessage()
{
//here I want to publish the performance counter value from the decorated class
}
private void SendToThirdParty()
{
//here I want to publish the performance counter value from the decorated class
}
private void ReceiveResponse()
{
//here I want to publish the performance counter value from the decorated class
}
private void ConvertResponseMessage()
{
//here I want to publish the performance counter value from the decorated class
}
private void SendResponseToClient()
{
//here I want to publish the performance counter value from the decorated class
}
}
Thanks.
Use a list of IProcessor objects instead of a bunch of methods. Going this way you are able to add/skip/change call order. In your IProcessor declare Process(PerformanceContext context) method and implement PerformanceContext class to exchange some values like StartTime, NumberOfCalls etc.
Good luck!
I'm trying to design a class hierarchy in C# to properly model my application model.
The problem is I'm not sure which is the right way to do it.
Let's say I have an Order class which is supposed to be the base (abstract) class for all order types and the reference type I'm working with when using orders. The order class has only a single 'important' method: let's call it order.PlaceOrder(), but there are multiple (orthogonal) requirements that an order might have to do (or not do): log the placing of the order, place the order asynchronously (PlaceOrder method returns immediately) and others.
Now, I want to make actual concrete classes which can support any number of these requirements. For example:
class GoogleOrder : LoggedOrder, AsyncOrder, etc
class AppleOrder: AsyncOrder
class MicrosoftOrder : Order
The question is: if I want to create such a class by deriving from all the "strategies", then they all (but one) have to be interfaces, whereas I wish to inherit actual implementation and avoid copy/pasting of code, and I'm not sure how to do it.
I come from a C++ background, where I could just derive from multiple base classes (or possibly use a policy based design, like Andrei Alexandrescu describes in his book), but in C# I'm not sure how to do it, even though this seems like a very general question, one which I should know by now.
Any help is greatly appreciated!
It seems like your design calls for "Decorator pattern", Decorator pattern gives flexibility to add responsibilities/roles dynamically and with different combinations however you like instead of using inheritance.
here are example on how to implement decorator:
http://alagesann.com/2013/08/16/decorator-pattern-made-easy/
http://en.wikipedia.org/wiki/Decorator_pattern
hope that helps.
here is the sample code for your scenario. see if it helps.
public abstract class Order
{
public abstract void PlaceOrder(); // log the placeing of the ordr, place the order asynchronously
}
public class MicrosoftOrder : Order // default order
{
public void PlaceOrder()
{
// default implementation for placing order.
}
}
public class AppleOrder : Order // for asycn functionalities.
{
private Order order;
public AppleOrder(Order order)
{
this.order = order;
}
public void PlaceOrder()
{
// Implement async functionalities.
// you can also call default order as
// order.PlaceOrder();
}
}
public class GoogleOrder : Order // logged order
{
private Order order;
public GoogleOrder(Order order)
{
this.order = order;
}
public void PlaceOrder()
{
// Implement logged order
// you can also call default order as
// order.PlaceOrder();
}
}
class Program
{
static void Main(string[] args)
{
Order order = new MicrosoftOrder();
order.PlaceOrder(); // Default Order;
Order orderWithAsync = new AppleOrder(order);
orderWithAsync.PlaceOrder(); // Place order with asycn
Order orderWithAsyncAndlogging = new GoogleOrder(orderWithAsync);
orderWithAsyncAndlogging.PlaceOrder(); // order with asynch and logging.
}
}
I'm learning C# and am trying to get my head around when to use classes and when not to.
If I was writing an app for a bank, I know I would use classes for customers which would include their name, account number, balance, etc. Would I use a static class for the methods that would deposit into their account, withdraw, change their address, etc since I only need to write them once?
Also, what would I use to keep track of every customer object? Having 2,000 Customers:
exampleName = new Customer();
in my code doesn't seem right. I'm not at the point of learning database's yet and am just learning classes.
Having a database would be ideal, but in the mean time you could use an IEnumerable to hold your Customer objects, like this:
List<Customer> myCustomers = new List<Customer>();
myCustomers.Add(new Customer {Name = "Bob", Address = "123 Anywhere St." });
Then you can just pass the list around where needed.
Typically you will then have a property on the Customer class that holds the accounts:
public class Customer
{
public Customer()
{
_accounts = new List<Account>();
}
public List<Account> Accounts
{
get { return _accounts; }
set { _accounts = value; }
}
private List<Account> _accounts;
}
And so on. Note that I'm keeping this simple and doing things the more long winded and descriptive way as you are a beginner.
Using lists of items in this way is a good way to start because you will natuarlly use these when you get to using a database; you will retrieve result sets from the database and then translate those result sets into lists of business objects.
As for using static methods to do business logic like adjusting balances, changing addresses, etc., for you at this stage it doesn't matter. If you are using tools like Resharper it will nag you with suggestions like that, but in your case you can safely ignore that particular one. What you should look for is keeping everything as self contained as possible, avoid leakage of data and leakage of responsibilities between objects - this is just good coding discipline and a good way to prevent bugs that are caused by loose coding.
Once you've got your functionality laid down and working, you may have a desire to move some functionality into static 'helper' style classes. This is absolutely fine, but do be careful - helper classes are fantastic and everything but can quickly turn into an anti-pattern if you don't maintain that coding discipline.
You don't need to use a static class, or static methods, in order to only write the methods once. It may or may not make sense to do so, but this is a perfectly valid way to write the methods without repeating yourself:
public class Customer
{
//properties, constructors, etc.
public virtual void Deposit(decimal amount) { }
public virtual void Withdraw(decimal amount) { }
//etc
}
This also allows you to make use of polymorphism, e.g.
public class BusinessCustomer : Customer
{
public override void Deposit(decimal amount) { //some other implementation }
}
Static classes are used when you aren't going to instantiate objects. You get one "instance" of that class - you can't do things like:
MyStaticClass m = new MyStaticClass();
m.SomeFunc();
when you've got a static class. Instead you'd use it by using the class name itself. Something like:
MyStaticClass.SomeFunc();
As to what would you use to keep track of every Customer object? You could use some sort of collection to hold these. Granted, in a real system there'd be some sort of persistence piece, likely a database, to hold the data. But you could just make something like:
IEnumerable<Customer> Customers = new List<Customer>();
And then add your customers to that list
Customers.Add(new Customer() { ... });
Back to the question about static methods...
So, the deal here is that you're not going to be referencing instance members in a static method, so you wouldn't use static methods to update a particular Customer's address. Assuming your Customer class looked like:
public class Customer
{
public string Address { get; set; }
}
You couldn't use a static method like
public static void SetAddress()
because each Customer (presumably) has a different address. You couldn't access the customer's address there because it isn't static. Get that? Instead, you'd use a static method if you were wanting to do something that didn't need to deal with instance data. I use static methods for things like utility functions.
public static double ComputeSomething(double someVal) { ... }
Here, the ComputeSomething function can be called by anybody like:
var result = MyStaticClass.ComputeSomething(3.15);
The takeaway here is that static classes aren't used to instantiate objects, rather they are used really as a convenient container to hold functions. Static functions are ones that can be on a non-static class but can't access any of the instance data.
One place where a static function would be used would be for the Singleton pattern. You make the constructor non-public so folks can't call it, and instead provide a static method on the class to return the one and only instance of the class. Something like:
public class MySingleton
{
private static MySingleton instance;
private MySingleton() {}
public static MySingleton Instance
{
get
{
if (instance == null)
{
instance = new MySingleton();
}
return instance;
}
}
}
what for withdrawls, deposits, etc
Those would be called Transactions.
This is meant to be in addition to the other answers. This is example of polymorphism with interfaces.
public interface IDeposit {
void Deposit(decimal amount);
}
public interface IWithdraw {
void Withdraw(decimal amount);
}
public class Customer : IDeposit, IWithdraw {
public void Deposit(decimal amount) { throw new NotImplementedException(); }
public void Withdraw(decimal amount) { throw new NotImplementedException(); }
}
public class DepositOnlyATM : IDeposit {
public void Deposit(decimal amount) { throw new NotImplementedException(); }
}
Keeps concepts separate, and allows for implementing multiple interfaces, or just one. With class inheritance approaches you only get one, and you get all of it. Inevitably you end up with spaghetti in my experience because sub-classes want some of the behavior, but not all of it.
I would recommend instead of getting into the implementation details right away that you first write down some simple user stories for your bank example. For instance
As a customer I would like to open a new account so that I can make deposits and withdrawls
Just in that requirement, we can envision a couple of classes (customer and account). From there just functionally decompose what the customer should do and what the account should do.
I've found that the book "The Object Oriented Thought Process" is a good read and will help answer some of the questions as to "when do I do this vs. that".
Good luck and have fun!