I am trying to define when to name a class as a Context and I am having a very difficult time. Could someone please define "Context" for me and explain when to name a class "Context"?
Dictionary.com (Random House Dictionary, © Random House, Inc. 2011) defines context as:
the parts of a written or spoken statement that precede or follow a specific word or passage, usually influencing its meaning or effect: You have misinterpreted my remark because you took it out of context.
the set of circumstances or facts that surround a particular event, situation, etc.
The second definition is the applicable definition in this case. Taking the HTTPContext class for example, we know that the class contains information about the web site at the current moment (including the request, the response, the session, the user, etc.)
Therefore, I would define a 'Context' in this regard as a class that provides information about a particular application or service; or provides access to objects and methods that describe the current state of an application (or a particular facet of an application, such as a DataContext class in Linq To SQL or Entity Framework).
If you look up the Oxford English Dictionary for "context" it tells us:
the circumstances that form the
setting for an event, statement, or
idea, and in terms of which it can be
fully understood:
In programming a "context" class would be a class that provides your application code or code running within a framework with a set of data or objects relevant and meaningful to the task at hand.
For example, ASP.NET's HttpContext object provides information about the current HttpRequest (cookies, headers, user agent and so on). This data is meaningful only in the "context" of the current request as it may and will change for other requests.
Related
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.
I'm writing a desktop app using Gnome technologies, and I reached the
stage I started planning Semantic Desktop support.
After a lot of brainstorming, sketching ideas and models, writing notes
and reading a lot about RDF and related topics, I finally came up with a
plan draft.
The first thing I decided to do is to define the way I give URIs to
resources, and this is where I'd like to hear your advice.
My program consists of two parts:
1) On the lower level, an RDF schema is defined. It's a standard set of
classes and properties, possible extended by users who want more options
(using a definition language translated to RDF).
2) On the high level, the user defines resources using those classes and
properties.
There's no problem with the lower level, because the data model is
public: Even if a user decides to add new content, she's very welcome to
share it and make other people's apps have more features. The problem is
with the second part. In the higher level, the user defines tasks,
meetings, appointments, plans and schedules. These may be private, and
the user may prefer to to have any info in the URI revealing the source
of the information.
So here are the questions I have on my mind:
1) Which URI scheme should I use? I don't have a website or any web
pages, so using http doesn't make sense. It also doesn't seem to make
sense to use any other standard IANA-registered URI. I've been
considering two options: Use some custom, my own, URI scheme name for
public resources, and use a bare URN for private ones, something like
this:
urn : random_name_i_made_up : some_private_resource_uuid
But I was wondering whether a custom URI scheme is a good decision, I'm
open to hear ideas from you :)
2) How to hide the private resources? On one hand, it may be very useful
for the URI to tell where a task came from, especially when tasks are
shared and delegated between people. On the other hand, it doesn't
consider privacy. Then I was thinking, can I/should I use two different
URI styles depending on user settings? This would create some
inconsistency. I'm not sure what to do here, since I don't have any
experience with URIs. Hopefully you have some advice for me.
1) Which URI scheme should I use?
I would advise the standard urn:uuid: followed by your resource UUID. Using standards is generally to be preferred over home-grown solutions!
2) How to hide the private resources?
Don't use different identifier schemes. Trying to bake authorization and access control into the identity scheme is mixing the layers in a way that's bound to cause you pain in the future. For example, what happens if a user makes some currently private content (e.g. a draft) into public (it's now in its publishable form)?
Have a single, uniform identifier solution, then provide one or more services that may or may not resolve a given identifier to a document, depending on context (user identity, metadata about the content itself, etc etc). Yes this is much like an HTTP server would do, so you may want to reconsider whether to have an embedded HTTP service in your architecture. If not, the service you need will have many similarities to HTTP, you just need to be clear the circumstances in which an identifier may be resolved to a document, what happens when that is either not possible or not permitted, etc.
You may also want to consider where you're going to add the most value. Re-inventing the basic service access protocols may be a fun exercise, but your users may get more value if you re-use standard components at the basic service level, and concentrate instead on innovating and adding features once the user actually has access to the content objects.
Assume we create 3-tier module, which enables us to display/create/edit articles. Articles are:
• organized into categories
• before article can be published, admin has to approve it by setting Approve field of Articles DB table to true
• by setting MembersOnly field ( Articles table ) admin can also specify whether particular article can be viewed by anybody or only by registered users
• Articles table also has ExpiredDate field, which tells when will the article expire and thus no longer be published
a) At DAL layer we provide methods GetAllArticles, GetArticlesByCategory, GetPublishedArticles and GetPublishedArticlesByCategory for retrieving articles from the DB
At BLL layer we use GetArticles() overloads to call all of the above DAL methods.
What are the some of the benefits of using single overloaded method at BLL layer instead of BLL methods having one-to-one correspondence with DAL methods? Only advantage I can think of is that this way same ObjectDataSource control can call two or more of GetArticles() overloads, depending on the value of parameters, for example:
public static List<Article> GetArticles(bool publishedOnly)
{
if (!publishedOnly)
return GetArticles();
...
}
If you don’t also design UI layer and thus can’t be sure which methods UI programmer will prefer the most, would it be best practice for DLL layer to provide four overloads of GetArticles + GetAllArticles, GetArticlesByCategory, GetPublishedArticles and GetPublishedArticlesByCategory?
2) When designing DAL methods to retrieve data from DB, how can you in advance know/predict ( without first designing the UI ), exactly which methods (for accessing DB) we should create at the DAL layer?
Namely, in the previous example I’ve had several methods for retrieving articles based on number of parameters ( based on category they belong to, whether we only want published articles etc). Assuming I’m selling this module to third party UI developers, then there is no way to know which data access methods they would prefer the most:
a) so should I create as many data access methods as I can think of ( one for getting all articles that are already expired, one for getting all articles that are already expired, but were never published, one for getting all articles that are not published, one for getting all articles that can be view by registered users only… ) ?
b) Even if all three layer are written by myself – should I still create as many data access methods as I can think of?
thanx
EDIT:
A common way to achieve this is to use interfaces to define the behavior of the API.
a) I’m not sure I understand this. Which class should implement this interface? Perhaps DLL class? In other words, if the name of my DLL class is Article, then third party would derive class named ChildArticle from Article, where ChildArticle would also implement this interface? Or did you mean something else?
b) Anyways, as far as I understand it, providing interface ( which declares defines additional DLL methods to retrieve articles from DB ) would also require DAL class to already have appropriate methods defined, which would be called by methods declared in the interface?
To your point, I believe it is a good idea to prefer fewer coarse-grained methods in the BLL to cover all the functionality required by an entire business operation
I’m not familiar with this term, but you’re prob suggesting that we should prefer overloaded GetArticles() over GetAllArticles, GetArticlesByCategory, GetPublishedArticles and GetPublishedArticlesByCategory?
A) The design of an API is strictly related to what it is meant to achieve and by whom it will be used.
In practice, this means that you should know the target audience of your API, and give them only what they need to get the job done.
Unless I personally interview the people that would buy my product, I can generally guess which methods they would find useful, but within that space, there are still any number of possible methods I could define. Thus, how should I know whether they would also find use for, say, GetArticles() overload which retrieves articles that already expired?!
On the other side it is perfectly fine to have many smaller data-centric methods in the DAL to work with specific pieces of data.
If not DLL, should DAL have as many data access methods as I can come up with ( for particular target audience of course )?
SECOND EDIT:
A few extensibility points can be built into the API to obtain a certain degree of flexibility. A common way to achieve this is to use interfaces to define the behavior of the API. This will allow consumers to replace or extend the pieces of the built-in functionality by providing custom implementations.
Assume I create a BLL layer and then provide some additional interfaces, which consumers could implement to extend BLL’s build-in functionality. But for consumers to be able to implement these interfaces, they will need to have access to BLL’s source code, right? But what if I don’t want consumers to view BLL’s source code?
Interfaces should exist between layers. More specifically, classes should interact with classes from other layers exclusively through interfaces
a) So even DAL’s built-in functionality should be exposed through interfaces? But why? Namely, if we’d use abstract class instead of interfaces, then this class could already implement some utility functions common to all provider classes that inherit from this abstract class?! On the other hand, if DAL uses interfaces instead, then utility functions common to all providers will have to be implemented once for each provider, which could mean a lot of redundant coding?!
b) Anyways, I don’t quite see the benefits ( except when we provide interfaces with which consumers could extend the basic functionality ) in having classes from different layers interacting through interfaces?
For added clarity, instead of overloading methods to work with different parameters, I believe it is better to have one method that accepts a single parameter. This parameter would be an object containing all the data for the method to work with. Some of that data could be required, some could be optional and would influence the effect of the operation.
If I know UI will extensively make use Object Data Source controls, should I still prefer BLL to define a single method (this method having as parameter an object with all the data for the method to work with) instead of method overloads?
cheers mate
I took the liberty to summarize your post in two main questions. I hope I managed to capture the essence of what you are asking.
Q) What is the relationship between the intefaces exposed by the DAL and the ones exposed by the BLL?
A) The BLL is an outward-facing API, and as such it should implement functionality that is useful to the external consumers of the application and expose it in a way that makes sense to them.
The DAL, on the contrary, is a inward-facing API that exposes functionality to retrieve and persist data in way that hides the details of the storage mechanism being used.
In short, the DAL focuses on how data is being represented and managed internally in the application, while the BLL focuses on exposing data in way that is meaningful to consumers.
Q) How many methods should a public API have, and which ones?
A) The design of an API is strictly related to what it is meant to achieve and by whom it will be used.In practice, this means that you should know the target audience of your API, and give them only what they need to get the job done.
Since it is impossible to predict all the possible ways an API will be used, it is important to decide which main use cases to support, and work to make them really straightforward in the API. A good principle to keep in mind is what Alan Kay once said:
Simple things should be simple,
complex things should be possible.
A few extensibility points can be built into the API to obtain a certain degree of flexibility. A common way to achieve this is to use interfaces to define the behavior of the API. This will allow consumers to replace or extend the pieces of the built-in functionality by providing custom implementations.
To your point, I believe it is a good idea to prefer fewer coarse-grained methods in the BLL to cover all the functionality required by an entire business operation.On the other side it is perfectly fine to have many smaller data-centric methods in the DAL to work with specific pieces of data.
UPDATE:
About interfaces
Interfaces should exist between layers. More specifically, classes should interact with classes from other layers exclusively through interfaces. For example, the DAL should expose interfaces for the classes used to access data, like IOrderHeaderTable or IOrderRepository depending on the design pattern being used.
The BLL should expose classes used to execute business operations, like IOrderManagementWorkflow, or ICustomerService.
Note: common functionality inside a layer can still be placed in base classes, since in modern Object-Oriented languages like C#, VB.NET and Java a class can both inherit from a base class and implement one or more interfaces.
Also, external parties who wish to customize the built-in functionality by implementing any of the provided public interfaces can do so without needing access to the source code. Interfaces should however be self-describing and well-documented, in order to make it easy for extenders to understand its semantics.
About the BLL
The BLL should be explicit about the business logic it supports. Therefore it is generally a good idea to have methods that are directly related to business operations.For added clarity, instead of overloading methods to work with different parameters, I believe it is better to have one method that accepts a single parameter. This parameter would be an object containing all the data for the method to work with. Some of that data could be required, some could be optional and would influence the effect of the operation.
Implementation detail: this kind of BLL API is fully supported by ObjectDataSource control built into ASP.NET Web Forms.
About the API
An API should contain all methods the designer can come up with, within the scope defined by the use cases the API is intended to support.
What is the best way to implement DTOs?
My understanding is that they are one way to transfer data between objects. For example, in an ASP.Net app, you might use a DTO to send data from the code-behind to the business logic layer component.
What about other options, like just sending the data as method parameters? (Would this be easiest in asces wher there is less data to send?)
What about a static class that just holds data, that can be referenced by other objects (a kind of global asembly data storage class)? (Does this break encapsulation too much?)
What about a single generic DTO used for every transfer? It may be a bit more trouble to use, but reduces the number of classes needed to work with (reduces object clutter).
Thanks for sharing your thoughts.
I've used DTO's to:
Pass data between the UI and service tier's of a standard 3-tier app.
Pass data as method parameters to encapsulate a large number (5+) of parameters.
The 'one DTO to rule them all' approach could get messy, best bet is to go with specific DTO's for each feature/feature group, taking care to name them so they're easy to match between the features they're used in.
I've never seen static DTO's in the way you mention and would hesitate at creating DTO singletons like you describe.
I keep it simple and map one DTO class to one db table. They are lightweight so I can send them everywhere, including over the wire.
I wish it could be as simple. Though DTO originated due to network distribution tiers of a system there can be whole load of issues if domain objects are returned to View layers. Here are some of them:
1.By exposing Domain objects to View layer, Views become aware of structure of domain objects, which lets view makes some assumptions about how related objects are available. For example if a domain object "Person" was retunrned to a view to which it is "bound" and on some other view, "Address" of Person is to be bound, there would be a tendency for Application layer to use a semantic like person.getAddresse() which woukd fail since at that point Address domain object might have not been loaded at point. In essence, with domain objects becoming available to View layers, views can always make assumptions about how data is made available.
2.) when domain objects are bound to views (more so in Thick clients), there will alwyas be a tendency for View centric logic to creep inside these objects making them logically corrupt.
Basically from my experience I have seen that making domain objects available to Views create architectural issues but there are issues with use of DTO's also since use of DTO creates additional work in terms of creation of Assemblers (DTO to Domain objects and reverse), Proliferation of analogous objects like Patient domain object, Patient DTO and perhaps Patient bean bound to view.
Clearly there are no right answers for this specially in a thick client system.
I borrowed this short and not complete but true answer to DTO cliché from:
http://www.theserverside.com/discussions/thread.tss?thread_id=32389#160505
I think it's pretty common to use DataSet/DataTable as the "one DTO to rule them all". It's easy to load them from the database, and persist the values back, and they can be easily serialized.
I would definitely say they are more trouble to use. They do provide all of the plumbing, but programming against them is a pain (lots of casting, null checks, magic strings, etc). It would be interesting to see a good set of extension methods to make working with them a little more "natural".
DTOs are used to send data over the wire, not between objects. Check out this post:
POCO vs DTO
Thanks for all the helpful ideas...
A summary + my take on this:
--If there is a small amount of data to move and not too many places to move it, regular parameters may suffice
--If there is a lot of data and/or many objects to move it to, a specially created object may be easiest (DTO object).
--A global data object that can be referenced (rather than passed) by various objects would seem to be frowned on...however, I wonder if there isn't sometimes a place for it within a particular sub-system? It is one way to reduce the amount of data passing. It does push the limits of "good encapsulation", however in specific instances within specific layers, perhaps it could add simplicity to a particluar assemply of classes. Thus one would lose class-level encapsulation, but could still have assembly-level encapsulation.
Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing.
Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with:
Given a config file with lines like
x = "Hello World!"
y = 5.0
dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.)
When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.
When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate
!some_command arg1 arg2
into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel.
When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy.
So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.
I can list following usage for reflection:
Late binding
Security (introspect code for security reasons)
Code analysis
Dynamic typing (duck typing is not possible without reflection)
Metaprogramming
Some real-world usages of reflection from my personal experience:
Developed plugin system based on reflection
Used aspect-oriented programming model
Performed static code analysis
Used various Dependency Injection frameworks
...
Reflection is good thing :)
I've used reflection to get current method information for exceptions, logging, etc.
string src = MethodInfo.GetCurrentMethod().ToString();
string msg = "Big Mistake";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
instead of
string src = "MyMethod";
string msg = "Big MistakeA";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
It's just easier for copy/paste inheritance and code generation.
I'm in a situation now where I have a stream of XML coming in over the wire and I need to instantiate an Entity object that will populate itself from elements in the stream. It's easier to use reflection to figure out which Entity object can handle which XML element than to write a gigantic, maintenance-nightmare conditional statement. There's clearly a dependency between the XML schema and how I structure and name my objects, but I control both so it's not a big problem.
There are lot's of times you want to dynamically instantiate and work with objects where the type isn't known until runtime. For example with OR-mappers or in a plugin architecture. Mocking frameworks use it, if you want to write a logging-library and dynamically want to examine type and properties of exceptions.
If I think a bit longer I can probably come up with more examples.
I find reflection very useful if the input data (like xml) has a complex structure which is easily mapped to object-instances or i need some kind of "is a" relationship between the instances.
As reflection is relatively easy in java, I sometimes use it for simple data (key-value maps) where I have a small fixed set of keys. One one hand it's simple to determine if a key is valid (if the class has a setter setKey(String data)), on the other hand i can change the type of the (textual) input data and hide the transformation (e.g simple cast to int in getKey()), so the rest of the application can rely on correctly typed data.
If the type of some key-value-pair changes for one object (e.g. form int to float), i only have to change it in the data-object and its users but don't have to keep in mind to check the parser too. This might not be a sensible approach, if performance is an issue...
Writing dispatchers. Twisted uses python's reflective capabilities to dispatch XML-RPC and SOAP calls. RMI uses Java's reflection api for dispatch.
Command line parsing. Building up a config object based on the command line parameters that are passed in.
When writing unit tests, it can be helpful to use reflection, though mostly I've used this to bypass access modifiers (Java).
I've used reflection in C# when there was some internal or private method in the framework or a third party library that I wanted to access.
(Disclaimer: It's not necessarily a best-practice because private and internal methods may be changed in later versions. But it worked for what I needed.)
Well, in statically-typed languages, you'd want to use reflection any time you need to do something "dynamic". It comes in handy for tooling purposes (scanning the members of an object). In Java it's used in JMX and dynamic proxies quite a bit. And there are tons of one-off cases where it's really the only way to go (pretty much anytime you need to do something the compiler won't let you do).
I generally use reflection for debugging. Reflection can more easily and more accurately display the objects within the system than an assortment of print statements. In many languages that have first-class functions, you can even invoke the functions of the object without writing special code.
There is, however, a way to do what you want(ed). Use a hashtable. Store the fields keyed against the field name.
If you really wanted to, you could then create standard Get/Set functions, or create macros that do it on the fly. #define GetX() Get("X") sort of thing.
You could even implement your own imperfect reflection that way.
For the advanced user, if you can compile the code, it may be possible to enable debug output generation and use that to perform reflection.