AS3 referencing Singleton - performance

I have a GameEngine class which is a sprite, and a GameModel which is a Singleton and holds a lot of the data.
I then get the data with
GameModel.getInstance().variable;
my game engine has a lot of them in it now and i was wondering if it would be more efficient if i had a reference to the GameModel in my GameEngine instead of creating it all the time
private var _data:GameModel = GameModel.getInstance();
trace(_data.variable);
I have a pretty strong feeling it will be more efficient but if anyone could let me know for sure and let me know if you can potentially see flaws with this method that would be much appreciated, cheers, rory.

It's definitely a good idea to store the instance in a property, since the lookup will be faster, but also because it lowers the GameEngine's knowledge of the GameModel's implementation details.
For example, imagine you've got a bunch of GameModel.getInstance() calls inside your GameEngine class and you decide to drop the singleton behaviour. You'll be rewriting all those calls, however if you'd cached the instance in a property you'd only need to rewrite one line.
That said, forget about singletons altogether, they're a far greater evil than premature optimization, but if you MUST use one, at least store the instance in a property in your client classes.

You could certainly add it as an instance, but I doubt it would make a noticeable difference. Premature optimization is the root of all evil and that :)
If you are really curious you should try to benchmark it and see if it actually changes anything.
EDIT: Oh yes, as the other answer here mentions - might want to drop singletons altogether. I would recommend looking at swiftsuspenders https://github.com/tschneidereit/SwiftSuspenders/ for dependency injection (or even robotlegs, for a great light-weight MVC solution, including swiftsuspenders).

Related

Why do we need 'private' methods in Ruby

Can someone give me a concrete example where a 'private' method would accomplish something that can't be done with a 'protected' method? In other words I am want to know why a language designer would put 'private' methods in Ruby.
It really depends on your development team and how your code is going to be used. In Ruby these tags are often suggestions more than hard and fast rules, there's ways to bypass private and protected methods if necessary, but they can serve as a strong hint to someone using your code that calling them is undesirable.
private is something that should be used sparingly as it can make life very difficult for those trying to subclass something. protected is usually sufficient, and helps steer external code to the methods that should be used.
There are occasions where private is necessary, that is you want to prevent subclasses from knowing too much about how the parent class works. This is more common in libraries where you encourage people to subclass but you also want to wall off some of the internal functions that aren't intended to be used by them. This allows you to refactor these methods later at will without breaking someone else's code.
One of the principles of good object-oriented design is controlling how much method exposure you have. Too much exposure means you're committed to making them behave identically now and in the future unless you're prepared to make breaking changes. Too little exposure means your class might be difficult to use, if not useless. Finding that balance is always tricky.
So private and protected exist for reasons, and it's largely the same reasons that C++, Java, PHP, Python and many others have these. It's to assert control over how and where your methods should be used.

Multiple Controllers appropriate with one entity in spring framework

I'm starting to develop website that use the spring framework.I have three controller.There are newCustomerController,editCustomerController and deleteCustomerController.These controllers are mapped with view that use for create update and delete, but I create only customer.
So, I would like to know.Is it appropriate to declare the controllers like this.
Thank
The answer to this question is subjective and maybe more a topic for https://softwareengineering.stackexchange.com/. However, there is something very spring related about it that I would like to comment.
There are a few principles that attempt at guiding developers of how to strike a good balance when thinking about designing the classes. One of those is the Single responsibility principle.
In object-oriented programming, the single responsibility principle
states that every class should have a single responsibility, and that
responsibility should be entirely encapsulated by the class. All its
services should be narrowly aligned with that responsibility
A catchier explanation is
A class or module should have one, and only one, reason to change.
However, its still often hard to reason about it properly.
Nevertheless, Spring gives you means for it (think of this statement as a poetic freedom of interpretation). Embrace constructor based dependency injection. There are quite a few reasons why you should consider constructor based dependency injection, but the part relevent to your question is adressed in the quote from the blog
An often faced argument I get is: “Constructors just get too verbose
if I have 6 or 7 dependencies. With fields only, this is fine”.
Awesome, you’ve effectively worked around a clear indicator that the
code you write is doing way too much. An increase in the number of
dependencies a type has should hurt, as it makes you think about
whether you should split up the component into multiple ones.
In other words, if you stick to constructor based injection, and your constructor turns a bit ugly, the class is most likely doing too much and you should consider redesigning.
The same works the other way around, if your operations are a part of the logical whole (like CRUD operations), and they use the same dependencies (now "measurable" by the count and the type of the injected deps) with no clear ideas of what can cause the operations to evolve independently of each other, than no reason to split to separate classes/components.
It should be better if you define one controller for Customer class and in that class you should have all methods related to customer operations (edit,delete,create and read).

Magento, magic getters v getData

I have been using magento for a while now and always cant decide between using the magic getter and getData()
Can someone explain the main difference, apart from the slight performance overhead (and it must be very slight).
I am thinking in terms:
Future code proof (i think magento 2 will not be using magic getter)
Stylistically
Performance
Stability
Any other reasons to use 1 over the other
There is no clear way to go based on the core code as it uses a mixture of both
There's no one answer to fit all situations and it's best to decide based on the model you are using and the particular use case.
Performance is quite poor for magic methods, as well as the extra overhead of converting from CamelCase to under_score on each accessor.
the magic methods are basically a wrapper for getData() anyway, with extra overhead.
There's is one advantage of using magic methods though, for example:
if you use getAttributeName() rather than getData('attribute_name')
at some point in the future, the model may be updated to include a real, concrete getAttributeName() method, in which case your code will still work fine. However if you have used getData(), you access the attribute directly, and bypass the new method, which could include some important calculations which you are bypassing.
In my opinion, the safest way is to always use getData($key). The magic getter uses the same method as you already pointed out.
The advantage is that you can find all references to getData in your code and change it appropriately in case the getData() method is refactored. Compare that with having to find out all magic method calls where they are always named differently.
The second thing is that the magic getter can screw you up easily when you have a method which is named the same way (I think getName() got me once and it took quite some time to debug).
So my vote is definitely for using getData().
As stated before, it's best to use getData over the magic methods. Just wanted to add 2 quick points:
1) The performance overhead is not that slight, especially because of the implementation of _underscore in Varien_Object (as mentioned by Andrew).
2) The implementation of getData has some logic that helps "pretify" code, and although it is a little slower than typical getData calls, is still much faster than magic methods.
If you have nested Varien_Object's so that you need to perform a call like:
$firstObject->getData('second_object')->getData('third_object')->getData('some_string');
you can also perform that call like this:
$firstObject->getData('second_object/third_object/some_string');

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.

Alternatives to #VisibleForTesting

I understand that #VisibleForTesting is not desirable because it changes the interface of a class just for testing purposes. Ideally we should test the interface that we actually use. But what would be a good alternative?
You use #VisibleForTesting when, as you said, you want to test a part of code you're not exposing to the end user. If you want to test it then it most likely means it's complicated, or at least not trivial. Two solutions would be:
Split the method where you're calling this into several methods so you feel more comfortable about not having one big method doing a bunch of stuff at once.
See if you can move the behavior to an external object that takes care of it.
I like #2 a lot when stuff starts getting complicated, since I can have an external object that I can test and make sure it works without having to expose it through our interface.
Having said that, some times the behaviors don't warrant the extraction of the method into a new object and you use #VisibleForTesting just to save time. Experience is what tells you when it's worth it to do it (or not).

Resources