advice with webforms and global functions - asp.net

i am new to webforms and come from a php background.
when creating complex web apps in php i usually have a lot of global functions in an includes file. these functions are then made available to other php pages.
how do you implement this in asp.net webforms?

This is undesirable in Object-Oriented Programming in general. Your global functions probably implement a large number of unrelated features. Instead, relate those features using classes. Put all the functions that implement a particular feature into a single class. You can then make the functions static if you like, so they can be referenced as ClassName.Function.

Like John said, put your functions into objects. In general it's best to avoid public static functions when possible for a variety of reasons, especially if you wish to use dependency injection or mocking for tests.
Global data is almost always a warning sign that you could have a problem with your design - so if you're unable to put your methods into objects you might want to look at why.

Related

If globals are bad, why does every web framework use them?

Every web development framework I've come across, including the best designed ones (Web2Py, Kohana) make use of some form of global variables to represent objects that are global within the application domain- for example, objects representing 'request' and 'response'.
On the other hand, the idea that global variables are bad is one of the fundamental axioms of programming. Indeed the now common disparagements of the singleton pattern usually point to the fact that it's nothing more than globals in disguise, as if that were explanation enough.
I'm trying to understand once and for all how globals can be so condemnable and at the same time be a seemingly indispensable part of all our web frameworks?
What is a global? Taking your text I assume you mean a variable that's declared at global scope. Such variable could be overridden by any assignment and break existing functionality.
However, in OO languages, everything is inside a class and assignment can be wrapped in gettors and settors for properties, or completely hidden behind methods. This gives a safe way of dealing with globals. Note that in proper OO languages (Java, C#, VB.NET etc) it is not possible to have global variables (sometimes a language construct suggests otherwise, but static fields in C# or modules in VB, mixins in Ruby are all wrapped in classes and thus not truly global).
A singleton, you mention it, is a special kind of global. As a designer you can control how many instances run of it. A car only needs one engine, a country only one government (or war breaks loose) and a program needs only one main thread. Globals are a necessity to programming, the real discussion should not be, do we need them, but how to solidly create and use them.
You say that request and response objects are globals in web development. They are not. They are (usually, depending on your toolset) convenience variables set in scope before your code is run. Since a web application can have multiple request objects at any given time, I think these are a poor example of a global variable. They are not (but they are usually local and a singleton to your current thread).
One important feature that you cannot cover in traditional procedural languages (like Basic, Pascal, C) is access control and thus concurrency and thread safety for global variables. In .NET for instance, any static method or property in the BCL (one could say that any static variable is global by definition) is thread-safe by design. Guidelines for user-defined static methods or properties suggest you do the same.
EDIT: the danger is with languages that allow global variables but at the same time propagate themselves as truly OO. While these are wonderful languages, it is indeed dangerous to step out of the protection of OO and create globals in for instance Perl, Python, Ruby, PHP.
I don't know exactly in what context those globals are used in web frameworks, but anything global starts to create problems as soon as you need to have solid access control. If you start to use such a global in concurrently executing program, it's quite hard to say who and when accessed and changed it. It creates so-called shared state. This makes debugging even more difficult.
Anyway, I am not really in favour of such statements. This only leads to oversimplifications. You have to weight you requirements and then decide if this or that pattern brings more positive or negative effects...

Asp.Net "plugin" architecture improvements

At the moment we have an architecture where a dll is dropped into the bin folder which contains a certain class, the main application then looks for that class, using reflection, and runs a specific method which performs a function which isn't important here
Clearly reflection creates other issues, and has quite a large overhead...what other things could we do/use instead of reflection?
Have you considered MEF?
MEF as already stated is a good option - it's whole ethos is pluggable architecture.
The overhead of reflection is really only a problem if you do it multiple times.. if you cache the types you find then you won't have to go looking for them again.

Is reflection actually useful apart from reverse engineering?

Languages such as Java and PHP support reflection, which allows objects to provide metadata about themselves. Are there any legitimate use cases where you would need to be able to do something like ask an object what methods it has outside of the realm of reverse engineering? Are any of those use cases actually implemented today?
Reflection is used extensively in Java by frameworks which are leveraged at runtime to operate with other code dynamically. Without reflection, all links between code must be done at compile time (statically).
So, for example, any useful plug-in framework (OSGi, JSPF, JPF), leverages Reflection. Any injection framework (Spring, Guice, etc) leverages Reflection.
Any time you want to write a piece of code that will interact with another piece of code without having that piece of code available when compiling, Reflection is the way forward in Java.
However, this is best left to frameworks and should be encapsulated.
There certainly are good use cases. For example, obtaining developer-provided metadata. Java APIs are increasingly using annotations to provide info about methods/fields/classes and their use. Like input validation, binding to data representations... You could use these at compile-time to generate metadata descriptors and use those, but to do it at runtime would require reflection. Even if you used the metadata descriptors, they'd end up containing things like class, method and field names that'd need to be accessed via reflection.
Another use case: dynamic languages. Take Ruby... It allows you to check up-front whether an object would respond to a method name before trying to call that method. Something like that requires reflection.
Or how about when a class or method name must be provided from outside compiled code, like when selecting an implementation of some API. That's just gonna be a bit of text. Looking up what it resolves to comes down to reflection.
Frameworks like Spring or Hibernate make extensive use of reflection to inspect a class and see the annotations.
Frameworks for debugging, serialization, logging, testing...

OO and Writing Drupal Modules

Preface: Yes, I've read:
http://drupal.org/node/547518
I am writing 'foo' module for Drupal6, where I am organizing the code in an OO fashion.
There's a class called Foo that has a bunch of setters and accessors, and it is working quite well at abstracting some pretty nasty code and SQL.
The question is is it common practice to expose a class for other modules, or is it better to wrap things in the more typical foo_myfnname()?
For example, if I am writing the module's docs, should I tell people to do this:
$foo = new Foo();
$something = $foo->get_something();
or tell them to call:
foo_get_something();
which under the hood does:
function foo_get_something() {
$foo = new Foo();
return $foo->get_something();
}
Difficult to say, and I don't think there is something like a 'common practice' for this. Taking the ubiquitous views module as an example hints on wrapping common API calls in 'standard' functions, and leaving the usage of the object(s) for advanced stuff only.
Personally I'd base the decision on the intended API audience. If you're addressing the 'broad' Drupal user base, forcing them to use Classes is probably (unfortunately/annoyingly) still a bit stretching, as many part time PHP users will have no proper concept of OOP (heck, even 'professional' PHP devs often don't have it).
If on the other side your intended audience consists of developers only, providing a proper OO layer 'as is' should be ok, and probably less confusing than the mixture that results otherwise (using views as an example again, I often started using one of the convenience wrapper functions, and found myself rewriting quite some code later on just because I needed this tiny little change that required direct object usage - better to be consistent and use objects from the beginning).

What are the downsides to static methods?

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

Resources