Magento, magic getters v getData - magento

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');

Related

Single responsibility principle - function

I'm reading some tuts about SOLID programming, and I'm trying to refactor my test project to implement some of those rules.
Often I have doubts with SingleResponsibilityPrinciple, so I hope someone could help me with that.
As I understood, SRP means that (in case of a function), function should be responsible for only one thing. And that's seems pretty easy and simple, but I do get in a trap of doing more than thing.
This is simplified example:
class TicketService {
private ticket;
getTicket() {
httpClient.get().then(function(response) {
ticket = response.ticket;
emit(ticket); <----------------------
});
}
}
The confusing part is emit(ticket). So, my function is named getTicket, that's exactly what I'm doing there (fetching it from server e.g.), but on the other hand, I need to emit that change to all other parts of my application, and let them know that ticket is changed.
I could create separate set() function, where I could do setting of private variable, and emit it there, but that seems like a same thing.
Is this wrong? Does it break the rule? How would you fix it?
You could also return the ticket from the getTicket() function, and then have a separate function called setUpdatedTicket() that takes a ticket and sets the private parameter, and at the end calls the emit function.
This can lead to unexpected behavior. If I want to re-use your class in the future and I see with auto-completion in my IDE the method getTicket() I expect to get a Ticket.
However renaming this method to mailChangedTicket, ideally you want this method to call the getTicket method (which actually returns the ticket) and this way you have re-usable code which will make more sense.
You can take SRP really far, for example your TicketService has a httpClient, but it probably doesn't matter where the ticket comes from. In order to 'fix' this, you will have to create a seperate interface and class for this.
A few advantages:
Code is becoming more re-usable
It is easier to test parts separately
I can recommend the book 'Clean Code' from Robert C. Martin which gives some good guidelines to achieve this.

Is there a common convension to put new methods(on top or on bottom)?

If we omit visibility modifiers(let's say all methods are public), is there any common convension to put new methods in class? I mean if I put them on bottom it's logically correct, because methods are sorted by date. If I put them on top, it's easy to see and compare what methods are added if the class is very long.
Just depends on what you and your team are comfortable with. I usually have method at the top of my class followed by fields. If there are many method that do different thing you are better off organizing them in a new class. Now without seeing any code I'm simply guessing.
No, I don't think there is.
As Kalagen said it's up to you and your team to decide it.
I would keep any methods that share similar functionality together and keep the class definition short.
The short answer in my opinion is no. Coding style might vary depending on the language you are using and the team you are working with. In addition you might have your own preference as well. I tend to add new methods close to methods that are related to it (e.g. if method1 calls method2 then method1 is above method2). Then it is relatively easy to find the method that's being called. On the other hand, most IDEs can find the method with a mouse click.
If you're using version control, you can easily see what methods were added and in which order, so sorting by date is not needed.
And as others have mentioned, keep the class small. Take a look at the Single responsibility principle. If the methods you are adding are not related to the responsibility of the class, extract them and create a new class.

AS3 referencing Singleton

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).

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).

Java design: too many getters

After writing a few lesser programs when learning Java the way I've designed the programs is with Model-View-Control. With using MVC I have a plethora of getter methods in the model for the view to use.
It feels that while I gain on using MVC, for every new value added I have to add two new methods in the model which quickly get all cluttered with getter & setters.
So I was thinking, maybe I should use the notifyObserver method that takes an argument. But wouldn't feel very smart to send every value by itself either so I figured, maybe if I send a kind of container with all the values, preferably only those that actually changed.
What this would accomplish would be that instead of having a whole lot of getter methods I could just have one method in the model which put all relevant values in the container.
Then in the view I would have a method called from the update which extracted the values from the container and assigning them to the correct fields.
I have two questions concerning this.
First: is this actually a viable way to do this. Would you recommend me doing something along these lines?
Secondly: if I do use this plan and I don't want to keep sending fields that didn't actually change. How would I handle that without having to have if statements to check if the value is not null for every single value?
I've more familiar with the MVP paradigm, but hopefully they're similar enough to comment. While getters (and setters) in and of themselves are not necessarily evil, they are sometimes a sign that your subsystems are too strongly coupled. One really great way to decouple this is to use an event bus: see Best practices for architecting GWT apps. This allows the view to just shoot off events for the controller to listen for whenever something important happens, and the view can listen for events whenever something changes in the model that corresponds to updating the view. Ideally you wouldn't even need to ever pass the model to the view, if you can break up any changes into incremental pieces and just tell the view to change this part and then this other part.
If you feel you have too many getters (and setters) in your model class, maybe you have too many fields altogether. Is it possible that there are several distinct classes hiding within your model? If you extract these into separate classes, it may make your model more manageable.
OTOH the associated container you are thinking about could also be viable - but then why duplicate all data? You could instead use the associated container directly in the model to store all properties you can think of. And you can also pass this around for observers to get updates (preferably wrapped into an unmodifiable container, of course) - although in this setup you wouldn't need to.
In general, Java is a verbose language which expects you to put all those getters and setters (and a lot more) in place. However, any decent IDE can generate those for you with a few keypresses. Note also that you need to write them only once, and you will read and call them many many more times. Verbose also means easily readable.
If you have too many getter it's ok. But you shouldn't need the setter. The view is supposed to only read/query the model.
The MVC pattern should promote something that is asymmetric: the control update the model by calling methods in the model that embed the logic and update the sate accordingly; this respects encapsulation. The view reads/queries the model via the getters. This goes a bit against information hiding, but that's how MVC works.
I wouldn't personally pass all information in the events. It sounds complicated to me: either you end up with something that is not statically typed (e.g. you pass hashmaps), or with a plethora of typed events. I would stick with something simple, and have (possibly many) getter in the model.

Resources