Spring framework scope - Is it a misnomer? - spring

I know there is a term Bean scope in Spring framework, and for some reasons it is confusing me, mainly because of the term scope, because we have this terms (scope) in languages, like C, Java applied to a variable scope (that is where a variable is visible).
I know there are five bean scope, and I am not asking explanation on them, I am not clear on what Bean scope means. Can anyone help me understand what does this term mean?

In programming languages scope of the variables defines where in the code, the variable can be reached.
Global variables can be accesed from everywhere.
Function parameters or local variables can be accesed only in the function.
In Spring framework scope of the bean defines when during the application runtime we are dealing with the same object.
Singleton scoped bean is an object that is unique to the whole application. Like global variable in programming languages.
Session scoped bean is an object that is unique to the session.
Request scoped bean is an object that is unique to the request. Like function parameters.
Prototype scoped bean is not unique to anything. Every time you get it, you have a new copy. Hard to compare but it can be a heap allocated variable.
In computer science, the scope term is overloaded, the same as the term interface. You can have a Go or Java interface as well as PCI or ISA.
Well, the term overload is also overloaded.

Related

Alternatives to global variables

I have a program that will grab several global settings from an API when first logged in. These values are then used extensively throughout the program. Currently I am storing them in global variables, but it does not seem very OOP.
What are the alternatives to global variables for storing extensively used settings? Use constants? Class variables? Where would I initialize the values through the API call, since this would only need to happen once? I have seen some examples that instantiate a class to get to the variables but that does not make much sense to me.
I would like to set the values on login and after this call the variables everywhere else with a simple expression like Global.myvalue or GLOBAL_MYVALUE
The Singleton Pattern might be handy for this:
https://ruby-doc.org/stdlib-2.1.0/libdoc/singleton/rdoc/Singleton.html
It's hard to give you a concise answer based on the information you provided, but I would avoid using global variables at all costs.
A good starting point would be to think of a class that could be a common ancestor to all the places where you use these variables and store them in that class. If your subclasses inherit from that class, these variables will automatically be available in their context.
Edit: like #seph posted, the singleton pattern seems to be a much better solution though

Wrapping instance variables in accessor methods

Sandy Metz says (POODR book, page 26):
Because it is possible to wrap every instance variable in a method and to therefore treat any variable as if it's just another object, the distinction between data and a regular object begins to disappear.
I am not sure if I understand what she is explaining. When we define the accessors, we are wrapping the instance variables (data) on a method but methods are not objects. So what does she mean when she says that we can treat variables as if they're just another object?
The primary difference between data and objects is behaviour. Objects can modify their internal state without changing their interfaces, while data are static structures.
When we wrap data access within a method, we get the same benefits of an object - the interface remains static to consumers even if the underlying data structure needs to change.

Avoiding singletons and global variables - but what about caching, providers, controllers, ...?

I'm currently "updating" my development knowledge especially on TDD principles by reading books, articles on the web and watching videos. Something that pops up everywhere is the warning, not to use global state variables as they make the system fragile and less easy to test and since singletons are not much better or rather the same, not to use those either.
Now I'm wondering: Can I actually be consistent about this?
What about a cache, that the application uses so it doesn't have to look up frequently used database objects again and again? I NEED a single instance of that cache to be passed around, otherwise what would be the point?
Another example are DAOs or as we call them providers. They do nothing but provide JPA database access for us but otherwise have no state. So why not make them singleton?
And controllers in the web frontend? All they do is react to requests - again with no internal state.
Wouldn't it waste a lot of performance instantiating the latter two again and again? I'm sure there are a few more examples where this applies.
Maybe it's okay to use singletons, as long as they don't have any member variables except for finals?
And even if they have member variables but all of them are injected into them, it should be save to use them, as any object, singleton or not, can modify injected objects so it really doesn't make any difference.
I'm a bit confused about this whole "avoid singletons" business, I'm not even sure I fully understand the risks involved. But most of all I'd like to hear thoughts on the above examples, as those are the most common places in our application where we use singletons.
Thanks!
btw: we're using springs dependency injection, so how to do it is not my question, rather why avoid it and where it is okay.
The issue with Singletons is not so much the Singleton design pattern per se as their being overused under the covers as stateful global God objects all over applications.
That way of using them has 2 major drawbacks :
Dependencies on singletons are hidden dependencies, and objects are tightly coupled to them, which hampers discoverability, maintainability and testability of the code.
Objects depend on singletons they don't have any idea which state they're in. The order in which a singleton's behaviors are used here and there starts to become important, and you start seeing "MySingleton.Initialize()"s all over the place, which is dangerous and defeats the whole purpose of having a single instance.
Only singletons that trump these pitfalls are IMO worth considering - that means stateless, immutable objects that somehow get injected into their consumers and can be replaced with other instances with the same contract.
Other than that, Singleton-ification is most often premature optimization applied on the wrong objects.
This blog post pretty much sums it up : http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx
You are absolutely correct -- there are cases when single instance is needed. However "avoid singletons" business does not tell that they are not needed. In my understanding it states that singleton behavior should be added by Dependency Container, not by static instance.
That would allow you to mock it in your unittests while having only one instance in production. you may find this link useful: Object Scopes in Ninject
The problem with singletons and global variables is that we need them but that most programming languages offer only one "global" context.
Imagine that you could do this:
Global g1 = new Global();
g1.run( ... some code ... );
Global g2 = new Global();
g2.run( ... some code ... );
When the code is run by g2, none of the singletons and globals from the run of g1 are visible. This is actually what we want: A efficient way to say "okay, I'm done with the globals and stuff, get rid of them".
The solution is a factory which can build all your singletons and globals for you and put them into the code in the right place. Then you can create new instances of this factory (along with new singletons and globals) in your tests as you need it.
This is what "dependency injection" is all about. Here is a short introduction.

Performance gain of marking class methods as static

I am using FxCop to look for improvements on our application. One of the rules we are often breaking is "Mark members as static" which is marked as a performance rule.
Certainly we have a lot of class methods that do not action on any of the class members, which could be marked as static, but is there really a performance gain to this?
My understanding is that static will be intantiated once at execution time. If the method is never invoked that it would have been a waste. If the method is invoked multiple times than there might be a small benefit.
With variables there are obvious implications as to whether or not they are marked static, and it is critical to the operation of your application how they are defined. For methods though I don't believe there is any functional affect on whether or not they are marked static if they do not reference any instance variables or methods.
Am I missing the point here? Is the standard to mark all of these methods as static?
Performance becomes better because static method doesn't have hidden "this" pointer.
Every instance (non-static) method has hidden "this" pointer, which is passed to the method to access instance members. If no non-static members are used, "this" pointer remains unused. Passing additional parameter on the stack or in CPU register takes a time which can be saved by declaring such method as static.
"My understanding is that static will be instantiated once at execution time."
Both static and non-static methods exist only once in the program code. Only non-staic data members are duplicated, when there are different class instances. Non-static class method works with specific instance using class reference (hidden parameter). Code itself is never duplicated.
As you said, when a method is marked as static, it is instantiated once, the first time it is used. Whenever subsequent calls are made, the runtime environment doesn't need to validate it, because it is guaranteed to exist. Here is the Microsoft doc for it: http://msdn.microsoft.com/en-us/library/ms245046%28v=vs.80%29.aspx
Here's some more guidance: Method can be made static, but should it?

Is it normal to have a long list of arguments in the constructor of a Presenter class?

Warning acronym overload approaching!!! I'm doing TDD and DDD with an MVP passive view pattern and DI. I'm finding myself adding dependency after dependency to the constructor of my presenter class as I write each new test. Most are domain objects. I'm using factories for dependency injection though I will likely be moving to an IoC container eventually.
When using constructor injection (as apposed to property injection) its easy to see where your dependencies are. A large number of dependencies is usually an indicator that a class has too much responsibility but in the case of a presenter, I fail to see how to avoid this.
I've thought of wrapping all the domain objects into a single "Domain" class which would act as a middle man but I have this gut feeling that I'd only be moving the problem instead of fixing it.
Am I missing something or is this unavoidable?
Often a large number of arguments to a method (constructor, function, etc) is a code smell. It can be hard to understand what all the arguments are. This is especially the case if you have large numbers of arguments of the same type. It is very easy for them to get confused which can introduce subtle bugs.
The refactoring is called "Introduce Parameter Object". Whether that's really a domain object or not, it is basically a data transfer object that minimizes the number of parameters passed to a method and gives them a bit more context.
I only use DI on the Constructor if I need something to be there from the start. Otherwise I use properties and have lazy loading for the other items. For TDD/DI as long as you can inject the item when you need it you don't need to add it to your constructor.
I recommend always following the Law of Demeter and not following the DI myth of everything needs to be in the constructor. Misko Hevery (Agile Coach at Google) describes it well on his blog http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/
Having a Layer Supertype might not be a bad idea, but I think your code smell might be indicating something else. Geofflane mentioned the refactor pattern, Introduce Parameter Object. While it's a good pattern for this sort of problem, I'm not entirely sure it's the way to go for this situation.
Question: Why are you passing in Domain Model objects to the constructor?
There is such a thing as having too much abstraction. If there's one solid layer of code you should be able to trust, it's your Domain Model. You don't need to reference 3 IEntity objects when you're dealing with Customer, Vendor, and Product classes if those are part of your basic Domain Model and you don't necessarily need polymorphism.
My advice: Pass in application and domain services. Trust your Domain Model.
EDIT:
Re-reading the problem when it's not horribly late at night, I realize your "Domain class" is already the Introduce Parameter Object refactoring and not, in fact, a Layer Supertype, as I thought at 3AM.
I also realize that perhaps you need to reference the Model objects in the application code, outside the Presenter. Perhaps you're doing some initial setup of your Model objects before passing them in to the Presenter. If this is the case, your "Domain class" idea might be best. If there is some initial setup, when moving to an IoC, you'll want to look at something like Factory Support in Castle Windsor. (Other IoC containers have similar concepts.)

Resources