I'm currently learning Struts 1.3!
Why do we extend Action class in struts 1.3
public class LoginAction extends Action
And when i look into web.xml file the mapping says
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
what is the Significance of ActionServlet class, why ActionServlet is mapped with Action.
Thanks
Simple answers:
Because that's how Struts 1 works.
Because you have to map requests to actions somehow.
Longer answers:
1. In S1 everything depends on subclassing framework classes.(See notes) The base Action class really only provides a small portion of framework functionality (messaging and resources, primarily), along with a small collection of other non-POJO framework classes, notably ActionForm.
In Struts (and in lots of older software) programs were written to implementations, not interfaces. Action is a class, not an interface. Most of the S1 framework's implementation references Action, meaning that in order to fulfill framework method signatures and return values, you must subclass Action.
2. One goal of MVC is to route requests to appropriate handlers. In S1 this is handled by the ActionServlet. It looks at the request and, based on the Struts configuration, determines which action will handle the request. It acts (more or less) as the controller.
For further study: A significant portion of functionality, and a main point of extension, lies further beneath the surface, in the RequestProcessor class. Note that instantiating actions to handle requests requires an Action to be returned. This means that requests must be handled by an Action, although any Action subclass may be used, e.g., your own actions, a framework action like DispatchAction or ForwardAction, etc.
I would add that your questions can be answered by reading the wealth of information available about Struts 1 on its site and on the internet. Since the source is available it's also important to check and verify assumptions against it. I might recommend looking at Struts 1.2 source instead of 1.3 since there's a small layer of functionality added that clouds the basics.
All this said, unless you have a very compelling reason to do so, studying Struts 1 is a waste of time. It's been EOL'd, hasn't been recommended for new projects for years, is written in a pretty old style, etc. Modern Java web frameworks are much, much easier to work with. Struts 1 was written a Pretty Long Time Ago, before inheritance had fallen out of favor, before annotations existed, before marker interfaces were used all over the place, etc.
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.
Can someone help me understand the advantages of Spring Web Flow.
What I have understood is
All the flows can be centrally configured in an XML file.
Need not have an overhead of carrying over the data from one request to another as it can be done by flow scope.
It helps especially in cases like Breadcrumbs navigation.
Flows can be further divided into Sub Flows to reduce the complexity.
Are there any other ones which I am have not tweaked into?
I'm going to play devil's advocate and say don't use it for anything other than simple use cases. Simple use cases meaning no ajax calls, no modal dialogs, no partial updates just standard html forms/flows for simple persistence (i.e page A -> page B -> Page C where each 'page' maps to a view-state definition in a 1 to 1 relationship all defined in the same flow xml file).
Spring webflow cons:
Yes everything is in xml files in theory it is suppose to be simple but when you have multiple flow xml files each with multiple state definitions and possibly subflow definitions it can become cumbersome to maintain or easily determine what the sequential logic of a flow is. (kind of like the old "GOTO operator" where any part of a flow logic can jump back to any previously or later defined part making the flow logic although seemingly "sequential" in xml... un-intuitive to follow)
Some features of Spring Webflow's documentation are unintuitive or flat out undocumented leading to hours of trial and error. For instance, exception handeling, usauge of 'output' tag (only works in subflow->back to parent caller undocumented), sending back flash view responses to a user is also unintuitive and uses a different container than Spring MVC (many times when a flow ends you want to send a msg to the user that is defined in a controller outside of webflow... but since the flow ended you can't do it with in spring webflow using flashScope container), etc...
Adding subflows although sounds good does not reduce complexity actually increases it. Due to the way subflows are defined. Definitions are long and complex and can be confusing when you have many end-states in both the main parent flow and the child subflows.
Initial setup and configuration can be painful if integrating with certain 3rd party view frameworks like Apache Tiles or Theymeleaf... I recall spending a few hours if not days on this.
State snapshots (Saving the user's input between pages) although a powerful feature from Flow A's view-state_1 <-> Flow A's view-state_2 and vise versa. This does not work between Main Flow A <-> Sub Flow B and vise versa... forcing the developer to manually bind (or rather hack) saving a user's state between Parent main flow's <-> subflows.
Debugging application logic placed inside webflow can be difficult. For instance, in webflow you can assign variables and perform condition checks all using SPEL inside the xml but this tends to be a pitfall. Over time you learn to avoid placing application logic inside the actual webflow xml and only use the xml to call service class methods and to place the returned values in the various scopes (again this hard learned lesson/best practice is undocumented). Also, because you are executing logic using SPEL... refactoring classes, method names, or variables sometimes silently break your application significantly increasing your development time.
fragment rendering... a powerful but unintuitive feature of webflow. Setting up fragment rendering was 1 of the most painful things I had to do with webflow. The documentation was lacking. I think this feature could easily go in the pros side if it was better documented and easy to setup. I actually documented how to use this feature via stackoverflow... How to include a pop-up dialog box in subflow
Static URLs per flow. If your flow has multiple views defined with in 1 flow your URL will not change navigating from view-state to view-state. This can be limiting if you want to control or match the content of the page with a dynamic url.
If your flow is defined in "/WEB-INF/flows/doSumTing/sumting-flow.xml" and your "base-path" is set to "WEB-INF/flows". Then to navigate to your flow you goto http://<your-host>/<your-webapp-name-if-defined>/doSumTing . The flow file name is completely ignored and not used in the URL at all. Although clear now I found this unintuitive when I first started.
Spring Webflow pros:
concept of "scope" containers flowScope, viewScope, flashScope, sessionScope and having easy access to these containers WITH IN A FLOW gives the developer flexibility as these are accessible from anywhere and are mutable.
Easily define states view-state,action-state,decision-state,end-state which clearly defines what each state is doing but as mentioned in the cons... if your application is complex and has MANY different states and transitions constantly Going back and forth... this can clutter your -flow.xml file makes it hard to read or follow the sequential logic. It's only easy if you have simple use cases with a small number of state definitions.
Seldom used but a powerful feature of webflow is flow inheritance. Common flow functionality across multiple flows can be defined in a single abstract parent flow and extended by child flows (similar to an abstract class definition in java). This feature is nice with regards to the DRY principle if you have many flows that share common logic.
Easily defined validation rules and support for JSR-303 (but Spring MVC has this as well)
The output tag can be used to send POJOs back and forth between Main flow <-> subflow. This feature is nice because the parameters don't need to be passed through the url via get/post and can pass as many POJOs as you wish.
Clearly defined views. What the view name is and which model variable it is being mapped to (e.g <view-state id="edit" view="#{flowScope.modelPathName}/editView" model="modelObj"> ). Also in the example just demonstrated can use preprocessing expressions for viewnames or most arguments in webflow... nice feature though not very well documented :/
Conclusion: Spring Webflow project was a good idea and sounds great on paper but the cons make it cumbersome to work with in complex use cases increasing development time significantly. Since a better solution exists for complex use cases (Spring MVC) to me it is not worth investing heavily in web flow because you can achieve the same results with Spring MVC and with a faster development time for both complex and simple use cases. Morever, Spring MVC is actively maintained, has better documentation, and a larger user community. Maybe if some of my cons are addressed it would tip the scales in Webflow's favor but until then I will recommend Spring MVC over webflow.
Note: I might be missing some things but this is what I came up with off the top of my head.
Additionally, you can use the back button and retain state up to the number of snapshots you choose to store.
You also may find this related question useful.
I want my mxml or actionscript components to be reusable and loosly coupled. I am wondering if it is good practice to use the FlexGlobals.topApplication to dispatch and listen for events. For instance I want my login component to dispatch events to the topApplication so when i reuse that component in a different project I won't have to change anything being all applications have a topApplication.
My other option is to have a separate static class to handle event dispatching but then I am creating a dependency on that static class.
Any suggestions would be appreciated.
Thanks.
I would recommend that you read about event propagation and have your login component dispatch the event to "whoever" catches it as it bubbles up through the hierarchy.
http://livedocs.adobe.com/flex/3/html/help.html?content=events_08.html
I have to agree with the answer by Stian here for the most part. With regard to weltraumpirat's comment I feel dependency injection can be great but also adds a lot of complication with regard to debugging/testing IMO and if you're not actually going to have different implementations of an interface just adds a lot of garbage code to look through without any real benefit. I feel like Spring on the service layer side works out well because you can change out implementations for the data access layer (DAO) if you switch DBs or something of that nature but it's hard for me to see the benefit on the front-end.
I would not recommend using the topLevelApplication as you'll end up with something like cairngorm where you have this humongous set of events/event handlers happening at the top level. Not to mention if you follow their suggested model you end up with a bunch of pointless event classes that simply define a string (there's better and worse ways to go about it using Cairngorm but I'm not a fan of what I've seen in the wild).
A developer at my company wrote a custom MVC "micro-framework" that works great for us where we can attach a controller to any display object to handle events for it, this works wonderfully but does require the initial overhead of developing/testing it. It's built on top of the existing Event scheme in Flex so our MVCEvent class extends Event (ours just bubble by default as we tend to want this for the types of events we're creating where the controller could be at any level above the UIComponent dispatching the event, and can always opt to turn off bubbling, however starting with the Event base class means we can utilitze the built in EventDispatcher dispatchEvent() method). He wrote just about everything using an interface to define the methods for each part and only assuming objects implement a given interface to be used in a particular context (as in IMVCEvent, IMVCCommand) this way if the built in framework implementation doesn't work for your particular scenario you just need to create a new class that implements the same interface (if extension also doesn't work for your case). This gives a huge amount of flexibility yet at the same time we're generally able to just re-use existing implementations of events, commands, or controllers. In each app we're just defining new views and commands for things that are specific to the business rules of the application.
So what's that all boil down to, I suggest you roll your own as a library then re-use that library for your many projects. You will know your own library in and out and can tweak it as you see fit quickly without trying to understand the many use cases someone designed their MVC framework to handle.
I realize this isn't an ideal solution in terms of speed to get something done now, but I think it really is the best solution for the long haul (it's been great for us that's really all I can say).
Amendment here to acknowledge the existing Flex MVC frameworks available and appease the crowd.
Robot Legs
By the way see what the creator of robot legs has to say about using his code: His words not mine
Swiz
Mate
Stackoverflow question about flex frameworks
I'm working on a fairly large project at the moment and am currently in the planning stages. I've done a lot of reading into the various patterns suggested for development, somthing that has split the team at the moment is when using Entity Framework should the classes be passed through the applciation layers so that a view accepts an Entity Framework class or should these classes be mapped to BLL Classes and if so at which point (Controller or Library) should this be done?
I'm interested in hearing some positives and negitives for each solutions.
This is one of those great "it depends" questions ....
For me it's a matter of pragmatism. I use the raw entity classes where ever I can for expediency. I start using DTOs when either the object graph in question starts becoming too cumbersome or the object in question has sensitive data I don't want sent over the wire.
This is again one of those questions that doesn't really have a right or wrong answer, its personal taste really. Personally I would opt for using DTO's or interfaces when passing data to the Views. I don't tend to pass around entity objects to different layers of my application they are strictly confined to the DAL, or if I do need to pass it up a layer I would almost always use an interface never the concrete type.
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