I'm aware of inheritance with classes (obviously) but I want to know if the behaviour can be replicated within functions?
I have a situation where all methods need to implement some logic before being called, and rather than duplicate the code across all functions, I want to know if there's some way to inherit a base function or something similar that executes before the rest of the function processes?
Is this possible with C#?
For example, I have the following methods:
public void MyFunction1 {
if(debug)
return;
MyProductionApi.DoSomething();
}
public void MyFunction2 {
if(debug)
return;
MyProductionApi.DoSomethingElse();
}
As you see from above, my scenario basically involves checking whether I'm in development so I can avoid expensive 3rd party API calls. I just want to skip over them if I'm testing, but want to avoid writing a check for each method as there are a large number of functions.
Ideally I could create some base functionality that executes the check that I can inherit from, but I don't know if this is possible?
I want to know if there's some way to inherit a base function or
something similar that executes before the rest of the function
processes?
You don't need necessarily inheritance to solve the problem of repeating the code. You could also pass the function as parameter to an other function, doing some basic jobs before calling it. You can do it like
public void MyFunction(Action a)
{
if(debug)
return;
a();
}
and call it like
MyFunction(MyProductionApi.DoSomething);
This solves your scenario of
I just want to skip over them if I'm testing
in a very simple way without complicated structures or inheritance.
Related
I know that multiple inheritance in C# is only allowed by using Interfaces and that there are very valid reasons why multiple inheritance can quickly become a real headache. (Working in .NET Framework if that makes any difference to the answers)
However.
In working on various projects accross many classes I find myself returning to the same patterns to handle behaviour.
For example I have an Interface IXMLSavable which requires the functions GetXML() and SetFromXML(XElement e) to be implemented. The way I implement this in every class is, that I write different functions for different versions of the XML (If I changed something in the GetXML() I want to maintain backwards compatibility...). And according to a version-attribute on the root Element I switch case to the right ReadVersionX(XElement e) function so all my data stays consitent.
Another example would be centered around eventing. If for example I want to implement a "stop firing events for the time being"-Lock I would go about thusly:
private bool suppressEvents;
public bool SuppressEvents
{
get { return suppressEvents; }
set
{
bool prevValue=SuppressEvents;
suppressEvents=value;
if(prevValue!=SuppressEvents && !SuppressEvents) TheChangeEvent?.Invoke();
}
}
So I can run multiple operations on the object in question without it giving of a right old firework display of events. Again: This code will be almost unchanged for a lot of classes.
For the XML one I could refactor this to a class that has a Dictionary<int,delegate> ReadFunctions which I could then set in every implementation (I concede that there needs to be a bit of customisation in the "implementing" class) and reduce the amount of bolierplate for every class (the explicit switching on the version attribute) to just filling this dictionary.
The eventing one could go into a class on its own quite readily, I would probably only need to hook up the right event to the invokation, but that could easily be remedied by an abstract function I will have to implement (again: customisation still necessary but much less boilerplate).
Each "now-class-was-interface" on its own would make a splendid base class for any object. I could use functionality down an inheritance tree and customise it by overwriting functionality with new if I would need it.
The problem starts when I want to combine the two now-classes together. Due to the limitation in C# (which, again, is there for a reason) I cannot inherit from both above described classes at the same time. This would only be possible if I have one of these classes inherit from the other. Which would be possible, but would lead to a whole lot of a different headache when I want one functionality but not the other. Or the other functionality and not the one. The way around that would be to create a plethora of permutation classes (so one class for each combination of the functionaities). And while that would solve the problem it would probably be a nightmare to maintain.
So the real question is: Is there a way to correctly plug in different already implemented functionality into a class in an inheritance like manner that allows the addition of multiple distinct functionality packages as opposed to interfaces that cannot by the very nature of themselves provide any concrete implementation.
In many cases you can avoid inheritance with the use of interfaces/default interface methods/extension methods, decorators, or some other pattern.
In your case with xml you could simply change your interface to have one ReadMethod per version, and use a extension method to select the correct one
public interface IXMLReadable{
void ReadVersion1(XElement e);
void ReadVersion2(XElement e);
}
public static class IXMLReadableExtensions {
public static void Read(this IXMLReadable self, XElement e){
// Read version from xml, call ReadVersion1 or ReadVersion2
}
}
default interface methods would do more or less the same thing, with the added advantage of allowing the class to override the Read-method if it wants some other behavior.
However, my preferred solution would be to instead convert your object to a Data Transfer Object (DTO), add any required serialization attributes to this object, and use a library to serialize this. Added fields etc can usually be accommodated by just marking it as optional. Larger changes can usually be done by creating a new DTO class.
One way to solve your event problem could be to move this logic to a separate class
public class SuppressibleEvent
{
private bool suppressEvents;
private bool pendingEvent;
public void Raise()
{
if (!suppressEvents)
{
TheChangeEvent?.Invoke(this, EventArgs.Empty);
}
else
{
pendingEvent = true;
}
}
public event EventHandler TheChangeEvent;
public bool SuppressEvents
{
get => suppressEvents;
set
{
suppressEvents = value;
if (!suppressEvents && pendingEvent)
{
TheChangeEvent?.Invoke(this, EventArgs.Empty);
pendingEvent = false;
}
}
}
}
Optionally you may add a interface, so that only the owner can raise the event, but others can listen and register. You could also add methods/events to your class that just forwards to the actual implementation.
The overall point is that there is usually a better pattern to use than implementation inheritance. Some might require a bit more code, but usually gain a bit of flexibility as a result.
I am in the process of creating an api for database operations where I have to wrap every function call in the api with a try catch. I am basically trying to get the same functionality as decorators in python.
I read a bunch of articles and this one seemed like the best example to follow: http://ayende.com/blog/3474/logging-the-aop-way. A problem I have with it is that after resolving the container with the interface of functions that need to be wrapped, you have to make a call on the resolved container to call one of those functions.
I would like the user of my controller to be able to just make a call to my class which implements the above interface and know nothing about what I have done internally as far as the try catch business.
Is this possible?
I apologize if the solution is simple, I haven't had much experience with C#.
Thanks.
If you can spend a few bucks on PostSharp, here is one way to accomplish this:
[Serializable]
public class PrintAndIgnoreExceptionAttribute : OnExceptionAspect
{
public override void OnException(MethodExecutionArgs args)
{
Console.WriteLine(args.Exception.Message);
args.FlowBehavior = FlowBehavior.Return;
}
}
Then you use [PrintAndIgnoreException] to decorate your methods which need to be covered. PostSharp is also the best performing of all AOP frameworks, because the extra code is weaved in post-compilation, so there is no run-time penalty. I don't work for them, I just use it in pretty much everything I do these days.
I have a method in a class for which they are a few different outcomes (based upon event responses etc). But this is a single atomic function which is to used by other applications.
I have broken down the main blocks of the functionality that comprise this function into different functions and successfully taken a Test Driven Development approach to the functionality of each of these elements. These elements however aren't exposed for other applications would use.
And so my question is how can/should i easily approach a TDD style solution to verifying that the single method that should be called does function correctly without a lot of duplication in testing or lots of setup required for each test?
I have considered / looked at moving the blocks of functionality into a different class and use Mocking to simulate the responses of the functions used but it doesn't feel right and the individual methods need to write to variables within the main class (it felt really heath robinson).
The code roughly looks like this (i have removed a lot of parameters to make things clearer along with a fair bit of irrelevant code).
public void MethodToTest(string parameter)
{
IResponse x = null;
if (function1(parameter))
{
if (!function2(parameter,out x))
{
function3(parameter, out x);
}
}
// ...
// more bits of code here
// ...
if (x != null)
{
x.Success();
}
}
I think you would make your life easier by avoiding the out keyword, and re-writing the code so that the functions either check some condition on the response, OR modify the response, but not both. Something like:
public void MethodToTest(string parameter)
{
IResponse x = null;
if (function1(parameter))
{
if (!function2Check(parameter, x))
{
x = function2Transform(parameter, x);
x = function3(parameter, x);
}
}
// ...
// more bits of code here
// ...
if (x != null)
{
x.Success();
}
}
That way you can start pulling apart and recombining the pieces of your large method more easily, and in the end you should have something like:
public void MethodToTest(string parameter)
{
IResponse x = ResponseBuilder.BuildResponse(parameter);
if (x != null)
{
x.Success();
}
}
... where BuildResponse is where all your current tests will be, and the test for MethodToTest should now be fairly easy to mock the ResponseBuilder.
Your best option would indeed be mocking function1,2,3 etc. If you cannot move your functions to a separate class you could look into using nested classes to move the functions to, they are able to access the data in the outer class. After that you should be able to use mocks instead of the nested classes for testing purposes.
Update: From looking at your example code I think you could get some inspiration by looking into the visitor pattern and ways of testing that, it might be appropriate.
In this case I think you would just mock the method calls as you mentioned.
Typically you would write your test first, and then write the method in a way so that all of the tests pass. I've noticed that when you do it this way, the code that's written is very clean and to the point. Also, each class is very good about only having a single responsibility that can easily be tested.
I don't know what's wrong, but something doesn't smell right, and I think there maybe a more elegant way to do what you're doing.
IMHO, you have a couple options here:
Break the inner functions out into a different class so you can mock them and verify that they are called. (which you already mentioned)
It sounds like the other methods you created are private methods, and that this is the only public interface into those methods. If so, you should be running those test cases through this function, and verifying the results (you said that those private methods modify variables of the class) instead of testing private methods. If that is too painful, then I would consider reworking your design.
It looks to me like this class is trying to do more than one thing. For example, the first function doesn't return a response but the other two do. In your description you said the function is complex and takes a lot of parameters. Those are both signs that you need to refactor your design.
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 6 years ago.
Improve this question
I have a Class that retrieves some data and images does some stuff to them and them uploads them to a third party app using web services.
The object needs to perform some specific steps in order.
My question is should I be explicitly exposing each method publicly like so.
myObject obj = new myObject();
obj.RetrieveImages();
obj.RetrieveAssociatedData();
obj.LogIntoThirdPartyWebService();
obj.UploadStuffToWebService();
or should all of these methods be private and encapsulated in a single public method like so.
public class myObject()
{
private void RetrieveImages(){};
private void RetrieveAssociatedData(){};
private void LogIntoThirdPartyWebService(){};
private void UploadStuffToWebService(){};
public void DoStuff()
{
this.RetrieveImages();
this.RetrieveAssociatedData();
this.LogIntoThirdPartyWebService();
this.UploadStuffToWebService();
}
}
which is called like so.
myObject obj = new myObject();
obj.DoStuff();
It depends on who knows that the methods should be called that way.
Consumer knows: For example, if the object is a Stream, usually the consumer of the Stream decides when to Open, Read, and Close the stream. Obviously, these methods need to be public or else the object can't be used properly. (*)
Object knows: If the object knows the order of the methods (e.g. it's a TaxForm and has to make calculations in a specific order), then those methods should be private and exposed through a single higher-level step (e.g. ComputeFederalTax will invoke CalculateDeductions, AdjustGrossIncome, and DeductStateIncome).
If the number of steps is more than a handful, you will want to consider a Strategy instead of having the steps coupled directly into the object. Then you can change things around without mucking too much with the object or its interface.
In your specific case, it does not appear that a consumer of your object cares about anything other than a processing operation taking place. Since it doesn't need to know about the order in which those steps happen, there should be just a single public method called Process (or something to that effect).
(*) However, usually the object knows at least the order in which the methods can be called to prevent an invalid state, even if it doesn't know when to actually do the steps. That is, the object should know enough to prevent itself from getting into a nonsensical state; throwing some sort of exception if you try to call Close before Open is a good example of this.
If method B() truly cannot be called unless A() is called first, then proper design dictates that A should return some object that B requires as a parameter.
Whether this is always practical is another matter, but that's how it should be done.
Yes private, otherwise you are leaving the door open for users to do things wrong, which will only be a cause for pain for everyone.
Do you ever need to call any of these methods on its own? ie does any of them do anything which is useful and might be needed stand alone? if so then you might want to keep those public, but even if you keep them all public, you should have the method which calls them in the correct order (preferably with a useful name) to make things easier for your users.
It all depends on whether the operation is essentially atomic. In this case it looks like a single operation to us outsiders, but is it really? If LogIntoThirdPartyWebService fails, does the UI need to present a dialog box to ask the user if they want to retry? In the case where you have a single operation, retrying the LogIntoThirdPartyWebService operation also requires redoing potentially expensive operations like RetrieveImages, while making them separate enables more granular logic.
What I would do in this case is something like this:
Images images = RetrieveImages();
ImagesAndData data = RetrieveAssociatedData(images);
WebService webservice = LogIntoThirdPartyWebService();
UploadStuffToWebService(data, webservice);
or maybe more ideally something like this:
UploadStuffToWebService(RetrieveImages().RetrieveAssociatedData(),
LogIntoThirdPartyWebService());
Now you have granularity while enforcing the proper order of operations.
It sounds to me like from the consumer of your object's point of view, the object does one thing: it moves images from one place to another. As the consumer of the object, all of the individual steps you need to take to accomplish that are irrelevant to me; after all that's why I have you to do it for me.
So you should have a single DoStuff() method that takes all the necessary params, and make all the implementation details private.
Private -- and take the parameters in the constructor and execute the order there.
Do not assume the caller will, or knows how to, call them in order.
So, rather than the example you have listed, I would do it this way:
MyObject myObject = new MyObject(); // make a constructor to take any parameters that are required to "setup" the object per your requirements.
myObject.UploadToWebService();
It really depends on whether you estimate that anyone would want to invoke only one of these methods and whether they make sense individually or can be implemented independently. If not, then it is better to avoid exposing anything but the high level op.
Expose as little as possible, as much as necessary. If a call to FuncA() is always followed by a call to FuncB(), make one public and have it call the other, or else have public FuncC() call them in sequence.
Yes, it should definitely be private, especially as all the methods seem to be parameterless and you're just concerned with the order.
The only time I would consider calling each method explicitly is if they each took several, non-overlapping parameters, and you wouldn't want to pass such a long string of parameters to one method and would want to modularize. And then you should make sure to document it clearly. But remember that comments are not executable... You'll still have to trust your user a bit more than you really should.
One of the biggest factors of information hiding and OOP... only give the user what is absolutely necessary. Allow as little room for mess-up as possible.
The question of public or private depends entirely on the contract you wish to expose for your object. Do you want users of your object to call the methods individually, or do you want them to call a single "DoStuff" method and be done with it?
It all depends on the intended usage of the class.
In the example you've given, I'd say DoStuff should be public and the rest private.
Which do you think would be easier for the consumers of your class?
Absolutely write one public method that performs the correct steps in the correct order. Otherwise, the caller is not going to do it right; they're going to forget a step or skip something.
Neither. I think you have at least 3 objects otherwise you are breaking the Single-Responsibility Principal. You need an object that "Gets and holds images", one that "manipulates images", and one that "manages external vendor communication".
One reason they would be public is if you intend the user to be able to insert logic between steps. In this case, you should impose that the functions are called in the correct order internally by keeping a really tiny state machine. If the state machine transitions in the wrong order, you have options besides just doing something wrong, such as throwing an exception.
However, an alternative design that allows them all to be remain private if the case of needing to act beween steps does exist. Instead of making the methods public, provide a public callback interface that lets the users attach handlers that you call at each step of the process. In your now private doItAll() method, you can do something as granular as:
if(preRetrieveHandlerExists){
preRetrieveHandler()
}
obj.RetrieveImages();
if(postRetrieveHandlerExists){
postRetrieveHandler()
}
//so on and so forth
My software engineering rule of thumb is to always give the user/consumer/caller as little chance to screw things up as possible. Therefore, keep the methods private to ensure working order.
Fowler uses the term "Feature Envy" to describe a situation where one object calls a handful of methods (especially repeatedly) on another.
I don't know where he got it from. You don't see it much in the literature, and a lot of people over the years have had no idea what I was talking about (I dunno why, I thought the name was perfectly obvious once I heard it. Which is why I repeat it)
I want to design a class, which contains a procedure to achieve a goal.
And it must follow some order to make sure the last method, let's say "ExecuteIt", to behave correctly.
in such a case, what design patter will you use ?
which can make sure that the user must call the public method according some ordering.
If you really don't know what I am saying, then can you share me some concept of choosing a design patter, or what will you consider while design a class?
I believe you are looking for the Template Method pattern.
Template Method is what you want. It is one of the oldest, simply a formalization of a way of composing your classes.
http://en.wikipedia.org/wiki/Template_method_pattern
or as in this code sample:
abstract class AbstractParent // this is the template class
{
// this is the template method that enforces an order of method execution
final void executeIt()
{
doBefore(); // << to be implemented by subclasses
doInTheMiddle() // also to be implemented by subclasses
doLast(); // << the one you want to make sure gets executed last
}
abstract void doBefore();
abstract void doInTheMiddle();
final void doLast(){ .... }
}
class SubA extends AbstractParent
{
void doBefore(){ ... does something ...}
void doInTheMiddle(){ ... does something ...}
}
class SubB extends SubA
{
void doBefore(){ ... does something different ...}
}
But it seems you are fishing for an opportunity to use a pattern as opposed to use a pattern to solve a specific type of problem. That will only lead you to bad software development habits.
Don't think about patterns. Think about how you would go around solving that specific problem without having patterns.
Imagine there were no codified patterns (which is how it was before). How would you accomplish what you want to do here (which is what people did to solve this type of problems.) When you can do that, then you will be in a much better position to understand patterns.
Don't use them as cookie cutters. That is the last thing you want to do.
Its basically not a pattern, but: If you want to make sure, the code/methods are executes in a specific order, make the class having only one public method, which then calls the non-public methods in the right sequence.
The simple and pragmatic approach to enforcing a particular sequence of steps in any API is to define a collection of classes (instead of just one class) in such way that every next valid step takes as a parameter an object derived from the previous step, i.e.:
Fuel coal = CoalMine.getCoal();
Cooker stove = new Cooker (gas);
Filling apple = new AppleFilling();
Pie applePie = new Pie(apple);
applePie.bake(stove);
That is to say that to bake a pie you need to supply a Cooker object that in turn requires some sort of a suitable fuel to be instantiated first. Similarly, before you can get an instanse of a Pie you'd need to get some Filling ready.
In this instance the semantics of the API use are explicitly enforced by its syntax. Keep it simple.
I think you have not to really execute nothing, just prepare the statements, resources and whatever you want.
This way whatever would be the order the user invokes the methods the actual execution would be assured to be ordered; simply because you have the total control over the real execution, just before execute it.
IMHO Template Method as very little to do with your goal.
EDIT:
to be more clear. Make your class to have one public method Execute, and a number of other public methods to tell your class what to do (when to do it is a responsibility of you and not of the user); then make a number of private methods doing the real job, they will be invoked in the right order by your Execute, once the user has finished settings things.
Give the user the ability of setting, keep execution for your self. He tells what, you decide how.
Template Method is rational, if you have a class hierarchy and base class defines protected operation steps in its public template method. Could you elaborate your question?
As general concept you should choose a pattern as a standard solution to a standard problem so, I agree with Oded, the "Template Method" seems to fit your needs (but what you explained is too few maybe).
DonĀ“t use pattern as "fetish", what you have to keep in mind is:
How can I figure my problem in a standard way?
There is a pattern for this?
Is this the simplest way?