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 7 years ago.
Improve this question
At work, our service calls follow the pattern of:
Create a proxy that allows you to hit a service on our business tier
upon hitting the service, it creates a new response instance
instantiates a new instance of one of our business code classes
Assigns the result of calling whatever function on the new instance to the response
Returns the response back through the proxy
So it always looks like this:
Dim someRequest as Request = CreateSomeSortOfRequest()
Dim results as Response = Nothing
using proxy as IResultProxy = OurLibrary.Proxy(Of IResultProxy).Create()
results = proxy.GetResults(request)
End Using
Then:
Dim results as Response = Nothing
Using whateverBusiness as new BusinessClass
results = whateverBusiness.ComputeWhatever(request)
End Using
Return results
Pretty basic stuff, right? Well the guys who have worked there for a little over 20 years now will go on and on about how none of these business classes should ever have any member variables of any kind. Ever. Wanna perform some really complicated operation? Better be prepared to pass 10 to (and I've seen it) 30 parameters.
All of this, to me, seems like bad practice. As long as you remain in that narrow scope, hand off a request to a new instance of a business class, ask it to perform whatever, it performs whatever logic necessary within itself, return the result, and carry on with your day.
I've investigated and we only ever use threading ourselves in one location in the system, and that just fires off different service calls (all of which follow the above pattern). We don't use instance pools, static variables, or anything else like that, especially since we have the above stated issue that we have a running belief that there should never be any class scoped variables.
Am I crazy for thinking that having these classes with extremely tight and locked down entry points (i.e. no outside access to internal variables) is perfectly fine, especially since there is no way to access the instances of the business class outside the scope of the service call? Or are my elders correct for stating that any private member variable in a class is non-threadsafe and should never be used?
I guess I should mention that the business classes pretty much always load some data from the database, try to piece that data together into, often, very deep hierarchal structures, then return (or the opposite; taking the object, breaking it apart, and performing, sometimes, hundreds of database calls to save).
Wanna perform some really complicated operation? Better be prepared to pass 10 to (and I've seen it) 30 parameters
Sounds like they don't want any state (public anyway) on their business classes, an understandably noble vision as it is but rarely does it prove to be useful or practical as a general rule. Instead of 30 parameters, maybe they should pass in a struct or request class.
You could point out to them that in their effort to prevent state, that 10-30 parameters comes with its own set of problems.
As stated in the documentation for the brilliant code analysis tool nDepend:
nDepend:
NbParameters: The number of parameters of a method. Ref and Out are also counted. The this reference passed to instance methods in IL is not counted as a parameter.
Recommendations: Methods where NbParameters is higher than 5 might be painful to call and might degrade performance. You should prefer using additional properties/fields to the declaring type to handle numerous states. Another alternative is to provide a class or structure dedicated to handle arguments passing (for example see the class System.Diagnostics.ProcessStartInfo and the method System.Diagnostics.Process.Start(ProcessStartInfo)) - Holy swiss cheese Batman, tell me more.
It's arguably no different to when the client passes a request object to the WCF service. You are passing request objects aren't you?
OP:
Am I crazy for thinking that having these classes with extremely tight and locked down entry points (i.e. no outside access to internal variables) is perfectly fine
OK it sounds like the system has been around for a while and has had some best practices applied by your elders during its construction. That's good. However such a system is arguably only going to continue being robust as someone follows what-ever rules that were setup...and from what you say sound quite bizarre and somewhat ill-informed.
It might also be an example of accidental architecture where the system is just because it is.
e.g. if someone goes and adds a public method and say some public properties or makes what was a private field public is likely to upset the applecart.
I once had the misfortune of working on a legacy system and though it appeared to run without incident, it was all rather fragile due to the exorbitant amount of public fields. (mind you this was c++!)
Someone could have said:
"well don't touch the public fields"
to which I could reply:
"well maybe we shouldn't make the fields public"
Hence their desire to have no instance fields. The notion that c# classes with "member variables of any kind" is naughty is not the real source of concern. Instead I suspect the problem is that of thread safety and for that they should be looking into how the caller or callers be made thread-safe not the business class in this case.
Enforcing thread safety by not having state, though effective is kind of a sledgehammer approach and tends to annoy other parts of OO sub-systems.
WCF Threading Models
It sounds to me they are performing applying old-school threading protection in WCF where WCF has it's own way of guaranteeing thread-safety in a way quite similar to how the Apartment model was successful for COM.
Instead of worrying about lock()s; and synchronisation, why not let WCF serialise calls for you:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession,
ConcurrencyMode = ConcurrencyMode.Single)]
public partial class MyService: IMyService, IDisposable
{
// ...
}
InstanceContextMode.PerSession essentially tells WCF to create a unique private instance of the service per client proxy. Got two clients calling? Well that means two instances of MyService will be created. So irrespective of what instance members this class has its guaranteed not to trod on the other instance. (note I don't refer to statatics here)
ConcurrencyMode = ConcurrencyMode.Single tells WCF that calls to this service instance must be serialised one after the other and that concurrent calls to the service are not allowed. This ties in with the InstanceContextMode setting.
Just by setting these two but very powerful settings in WCF you have told it to not only create private instances of your WCF service such that multiple clients can't trod on it, but that even if the client shared it's client proxy in a thread and attempted to call one particular service instance concurrently, WCF guarentees that calls to the service will be serialised safely.
What does this mean?
Feel free to add instance fields or properties to your service class
such members won't be trodden on by other threads
when using WCF, there is generally no need for explicit thread locking in your service class (depending on your app, this could apply to subsequent calls. see below)
It does not mean that per-session-single services only ever allow one client at a time. It means only one call per client proxy at a time. Your service will most likely have multiple instances running at a particular moment having a jolly good time in the knowledge that one can't throw stones at the other.
Roll-on effects
As long as you remain in that narrow scope, hand off a request to a new instance of a business class
Since WCF has established a nice thread-safe ecosystem for you, it has a nice follow-on effect elsewhere in the call-stack.
With the knowledge that your service entry point is serialised, you are free to instantiate the business class and set public members if you really wanted to. It's not as if another thread can access it anyway.
Or are my elders correct for stating that any private member variable in a class is non-threadsafe
That depends entirely on how the class is used elsewhere. Just as a well designed business processing layer should not care whether the call stack came from WCF; a unit test; or a console app; there may be an argument for threading neutrality in the layer.
e.g. let's say the business class has some instance property. No drama, the business class isn't spawning threads. All the business class does is fetch some DB data; has a fiddle and returns it to the caller.
The caller is your WCF service. It was the WCF service that created an instance of the business class. But what's that I hear you say - "the WCF service instance is already thread-safe!" Exactly right and thank-you for paying attention. WCF already set up a nice thread safe environment as mentioned and so any instance member in the business class shouldn't get obliterated by another thread.
Our particular WCF thread is the only thread that is even aware of this particular business class's instance.
Conclusion
Many classes in .NET have state and many of those are in private fields. That doesn't mean it's bad design. It's how you use the class that requires thought.
A WinForms Font or Bitmap object has both state; I suspect even with private members; and shouldn't arguably be fiddled with concurrently by multiple threads. That's not a demonstration of poor design by Microsoft's part rather something that should have state.
That's two classes created by people much smarter than you, me and your elders I suspect, in a codebase larger than anything we will ever work on.
I think it is fantastic that you are questioning your elders. Sometimes we don't always get it right.
Keep it up!
See Also
Lowy, Juval, "Programming WCF Services: Mastering WCF and the Azure AppFabric Service Bus", Amazon. The WCF bible - a must read for prior to any serious dabbling into WCF goodness
nDepend, a truly marvelous and powerful code analysis tool. Though one may be forgiven into thinking it's a FxCop-type-tool and though it does support such a feature, it does that and more. It analyses your entire Visual Studio solution (and stand-alone libraries if you wish) investigating coupling for one and excessive use of parameters as another. Be prepared for it pointing out some embarrassing mistakes made by the best of us.
Comes with some groovy charts too that look impressive on any dashboard screen.
Related
New to .net and was wondering if there is a performance gain to keeping an instance of, for example a DAL object in scope?
Coming from the Coldfusion world I would instanciate a component and store it in the application scope so that every time my code needed to use that component it would not have to be instanciated over and over again effecting performance.
Is there any benefit to doing this in ASP.Net apps?
Unless you are actually experiencing a performance problem, than you need not worry yourself with optimizations like this.
Solve the business problems first, and use good design. As long as you have a decent abstraction layer for your data access code, then you can always implement a caching solution later down the road if it becomes a problem.
Remember that any caching solution increases complexity dramatically.
NO. In the multi-tier world of .asp this would be considered a case of "premature optimization". Once a sites suite of stubs, scripts and programs has scaled up and been running for a few months then you can look at logs and traces to see what might be cached, spawned or rewritten to improve performance. And as the infamous Jeff Atwood says "Most code optimizations for web servers will benifit from money being spent on new and improved hardware rather than tweaking code for hours and hours"
Yes indeed you can and probably should. Oftentimes the storage for this is in the Session; you store data that you want for the user.
If it's a global thing, you may load it in the Application_Start event and place it somewhere, possibly the HttpCache.
And just a note, some people use "Premature Optimisation" to avoid optimising at all; this is nonsense. It is reasonable to cache in this case.
It is very important to do the cost benefit analysis before caching any object, one must consider all the factors like
Performance advantage
Frequency of use
Hardware
Scalability
Maintainability
Time available for delivery (one of the most important factor)
Finally, it is always useful to cache object which are very costly to create or you are using very frequently i.e. Tables's Data (From DB) or xml data
Does the class you are considering this for have state? If not, (and DAL classes often do not have state, or do not need state), then you should make it's methods static, and then you don't need to instantiate it at all. If the only state it holds is a connection string, you can also make that property field a static property field, and avoid the requirement of instantiating it that way.
Otherwise, take a look at the design pattern called Flyweight
I'm looking at some vb.net code I just inherited, and cannot fathom why the original developer would do this.
Basically, each "Domain" class is a collection of properties. And each one implements IDisposable.Dispose, and overrides Finalize(). There is no base class, so each just extents Object.
Dispose sets each private var to Nothing, or calls _private.Dispose when the property is another domain object. There's a private var that tracks the disposed state, and the final thing in Dispose is GC.suppressFinalize(Me)
Finalize just calls Me.Dispose and MyBase.Finalize.
Is there any benefit to this? Any harm? There are no un-managed resources, no db connections, nothing that would seem to need this.
That strikes me as being a VB6 pattern.
I would bet the guy was coming straight from VB6, maybe in the earlier days of .NET when these patterns were not widely understood.
There also is one case were setting an nternal reference to nothing is useful in a call to Dispose: when the member is marked as Withevents.
Without that, you risk having an uncollected object handling events when it really should not be doing that anymore.
It would seem to me that this is something that is NOT needed at all, especially without un-managed resources and data connections.
If you happen to be able to sanitize and post the code we might be able to get a bit more insight, but realistically I can't see a need for it.
Depending on the size of the objects, and how often they are created/destroyed, it could be to ensure GC can happen as early as possible.
It may be, that this pattern was used in other projects and it continues on without understanding why it was used in the first place. Monkey Gardeners
The only reason that I could see for this -- and this is dubious at best -- is if these things are being created and disposed of higher in the "food chain" and there is a potential for some of these domain classes to have either a limited or unmanaged resource at some point.
Even that is sketchy...it sounds like someone came from an unmanaged background and was looking for the .NET equivalent to managing your memory and came across the IDisposable interface.
I have recently inherited an ASP.Net app using Linq2SQL. Currently, it has its DataContext objects declared as static in every page, and I create them the first time I find they are null (singleton, sort of).
I need comments if this is good or bad. In situations when I only need to read from the DB and in situations where i need to write as well.
How about having just one DataContext instance for the entire application?
One DataContext per application would perform badly, I'm afraid. The DataContext isn't thread safe, for starters, so even using one as a static member of a page is a bad idea. As asgerhallas mentioned it is ideal to use the context for a unit of work - typically a single request. Anything else and you'll start to find all of your data is in memory and you won't be seeing updates without an explicit refresh. Here are a couple posts that talk to those two subjects: Identity Maps and Units of Work
I use to have one DataContext per request, but it depends on the scenarios you're facing.
I think the point with L2S was to use it with the unit of work pattern, where you have a context per ... well unit of work. But it doesn't work well in larger applications as it's pretty hard to reattach entities to a new context later.
Rick Strahl has a real good introduction to the topic here:
http://www.west-wind.com/weblog/posts/246222.aspx
One thing I can say I have had problems with in the past, is to have one context to both read and write scenarios. The change tracking done in the datacontext is quite an overhead when you are just reading, which is what most webapps tends to do most of the time. You can make the datacontext readonly and it will speed up things quite a bit - but then you'll need another context for writing.
Imagine in the Global.asax.cs file I had an instance class as a private field. Let's say like this:
private MyClass _myClass = new MyClass();
And I had a static method on Global called GetMyClass() that gets the current HttpApplication and returns that instance.
public static MyClass GetMyClass()
{
return ((Global)HttpContext.Current.ApplicationInstance)._myClass;
}
So I could get the instance on the current requests httpapplication by calling Global.GetMyClass().
Keep in mind that there is more than one (Global) HttpApplication. There is an HttpApplication for each request and they are pooled/shared, so in the truest sense it is not a real singleton. But it does follow the pattern to a degree.
So as the question asked, would you consider this at the very least the singleton pattern?
Would you say it should not be used? Would you discourage its use? Would you say it's a possibly bad practice like a true singleton.
Could you see any problems that may arise from this type of usage scenario?
Or would you say it's not a true singleton, so it's OK, and not bad practice. Would you recommend this as a semi-quasi singleton where an instance per request is required? If not what other pattern/suggestion would you use/give?
Have you ever used anything such as this?
I have used this on past projects, but I am unsure if it's a practice I should stay away from. I have never had any issues in the past though.
Please give me your thoughts and opinions on this.
I am not asking what a singleton is. And I consider a singleton bad practice when used improperly which is in many many many cases. That is me. However, that is not what I am trying to discuss. I am trying to discuss THIS scenario I gave.
Whether or not this fits the cookie-cutter pattern of a Singleton, it still suffers from the same problems as Singleton:
It is a static, concrete reference and cannot be substituted for separate behavior or stubbed/mocked during a test
You cannot subclass this and preserve this behavior, so it's quite easy to circumvent the singleton nature of this example
I'm not a .NET person so I'll refrain from commenting on this, except for this part:
Would you say its bad practice like a true singleton.
True singletons aren't 'bad practice'. They're HORRIBLY OVERUSED but that's not the same thing. I read something recently (can't remember where, alas) where someone pointed out the -- 'want or need' vs. 'can'.
"We only want one of these", or "we'll only need one": not a singleton.
"We CAN only have one of these": singleton
That is, if the very idea of having two of that object will break something in horrible and subtle ways, yes, use a singleton. This is true a lot more rarely than people think, hence the proliferation of singletons.
A Singleton is an object, of which, there CAN BE only one.
Objects of which there just happens to be one right now are not singleton.
Since you're talking about a web application, you need to be very careful with assuming anything with static classes or this type of pseudo-singleton because as David B said, they are only shared across that thread. Where you will get in trouble is if IIS is configured to use more than one worker process (configured with the ill-named "Web-Garden" mode, but also the # worker processes can be set in machine.config). Assuming the box has more than one processor, whoever is trying to tweak it's performance is bound to turn this on.
A better pattern for this sort of thing is to use the HttpCache object. It is already thread-safe by nature, but what still catches most people is you object also needs to be thread-safe (since you're only going to probably create the instance and then read/write to a lot of its properties over time). Here's some skeleton code to give you an idea of what I'm talking about:
public SomeClassType SomeProperty
{
get
{
if (HttpContext.Current.Cache["SomeKey"] == null)
{
HttpContext.Current.Cache.Add("SomeKey", new SomeClass(), null,
System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1),
CacheItemPriority.NotRemovable, null);
}
return (SomeClassType) HttpContext.Current.Cache["SomeKey"];
}
}
Now if you think you might need a web farm (multi-server) scale path, then the above won't work as the application cache isn't shared across machines.
Forget singleton for a moment.
You have static methods that return application state. You better watch out.
If two threads access this shared state... boom. If you live on the webserver, your code will eventually be run in a multi-threaded context.
I would say that it is definitely NOT a singleton. Design patterns are most useful as definitions of common coding practices. When you talk about singletons, you are talking about an object where there is only one instance.
As you yourself have noted, there are multiple HttpApplications, so your code does not follow the design of a Singleton and does not have the same side-effects.
For example, one might use a singleton to update currency exchange rates. If this person unknowingly used your example, they would fire up seven instances to do the job that 'only one object' was meant to do.
What are the downsides to using static methods in a web site business layer versus instantiating a class and then calling a method on the class? What are the performance hits either way?
The performance differences will be negligible.
The downside of using a static method is that it becomes less testable. When dependencies are expressed in static method calls, you can't replace those dependencies with mocks/stubs. If all dependencies are expressed as interfaces, where the implementation is passed into the component, then you can use a mock/stub version of the component for unit tests, and then the real implementation (possibly hooked up with an IoC container) for the real deployment.
Jon Skeet is right--the performance difference would be insignificant...
Having said that, if you are building an enterprise application, I would suggest using the traditional tiered approach espoused by Microsoft and a number of other software companies. Let me briefly explain:
I'm going to use ASP.NET because I'm most familiar with it, but this should easily translate into any other technology you may be using.
The presentation layer of your application would be comprised of ASP.NET aspx pages for display and ASP.NET code-behinds for "process control." This is a fancy way of talking about what happens when I click submit. Do I go to another page? Is there validation? Do I need to save information to the database? Where do I go after that?
The process control is the liaison between the presentation layer and the business layer. This layer is broken up into two pieces (and this is where your question comes in). The most flexible way of building this layer is to have a set of business logic classes (e.g., PaymentProcessing, CustomerManagement, etc.) that have methods like ProcessPayment, DeleteCustomer, CreateAccount, etc. These would be static methods.
When the above methods get called from the process control layer, they would handle all the instantiation of business objects (e.g., Customer, Invoice, Payment, etc.) and apply the appropriate business rules.
Your business objects are what would handle all the database interaction with your data layer. That is, they know how to save the data they contain...this is similar to the MVC pattern.
So--what's the benefit of this? Well, you still get testability at multiple levels. You can test your UI, you can test the business process (by calling the business logic classes with the appropriate data), and you can test the business objects (by manually instantiating them and testing their methods. You also know that if your data model or objects change, your UI won't be impacted, and only your business logic classes will have to change. Also, if the business logic changes, you can change those classes without impacting the objects.
Hope this helps a bit.
Performance wise, using static methods avoids the overhead of object creation/destruction. This is usually non significant.
They should be used only where the action the method takes is not related to state, for instance, for factory methods. It'd make no sense to create an object instance just to instantiate another object instance :-)
String.Format(), the TryParse() and Parse() methods are all good examples of when a static method makes sense. They perform always the same thing, do not need state and are fairly common so instancing makes less sense.
On the other hand, using them when it does not make sense (for example, having to pass all the state into the method, say, with 10 arguments), makes everything more complicated, less maintainable, less readable and less testable as Jon says. I think it's not relevant if this is about business layer or anywhere else in the code, only use them sparingly and when the situation justifies them.
If the method uses static data, this will actually be shared amongst all users of your web application.
Code-only, no real problems beyond the usual issues with static methods in all systems.
Testability: static dependencies are less testable
Threading: you can have concurrency problems
Design: static variables are like global variables