Why is Auth._currentUser not recommended in angular_devise? - angularjs

Per angular_devise docs, https://github.com/cloudspace/angular_devise, using Auth._currentUser is frowned upon.
Auth._currentUser
Auth._currentUser will be either null or the currentUser's object
representation. It is not recommended to directly access
Auth._currentUser, but instead use Auth.currentUser().
Why is this a bad idea?
I'm currently using it in an application because it allows me to be more concise and add functionality with fewer lines of code.

Underscored properties and methods are considered private, this means that this part of API can be changed without notice and their usage can lead to unforeseen circumstances.
Since getting current user is asynchronous operation, promise-based Auth.currentUser() should be used instead.
The last but not the least concern is that calls to Auth.currentUser can be spied in specs, this improves testability.

Related

Is Hystrix fallback implementation mandatory?

I have a method calling a third party resource to retrieve a Dog object. If the call fails, I have no alternative path to return the Dog object.
So, what is the preferred apporach here:-
1. Implement hystrix fallback and return a null Dog object.
2. Hystrix will throw an exception when the call fails and with the catching of exception, null Dog object will be returned.
Option 1 or 2?
Is hystrix fallback a mandatory implementation requirement is you don't really have a fallback approach?
I think not, what's your opinion? What does hystrix guidelines suggest?
From what you are saying, both options 1 and 2 result in the same outcome - a null Dog being returned. I would say that handling it using a fallback in such case is better because it's cleaner. Fallback will be defined as part of the command, and as such would be consistent among all the uses of this command. This would not be true if you handled it as an exception. In that case you would need to remember to implement the exception handling in all of the places where the call is made.. and in the same way - and it's easy to make a mistake by forgetting about handling some place.
Is it mandatory to have a fallback?
It's not mandatory. If not provided, an exception will be raised.
In your case, you do have a fallback strategy - it is just very simple. It is actually covered in the Hystrix Wiki as a Silent Fail and you can read more about it on https://github.com/Netflix/Hystrix/wiki/How-To-Use#Common-Patterns-FailSilent
It is worth to think about which operations need a fallback, or rather, what the fallback should be. It is worth providing a fallback for a read operation. For a write operation it may not be a good idea, as described here: https://github.com/Netflix/Hystrix/wiki/How-To-Use#Fallback.
Defining a fallback strategy is part of the pattern. Imagine a project with few developers where Hystrix is used. It will feel nice to know where exactly to go to see the fallback strategy. That is a huge benefit.
One thing to keep in mind is that exceptions are more expensive to process so using them as a fallback strategy is a waste of resources. This won't be an issue in a small project with a small number of requests, but could cause problems in a system that processes a lot of such calls.

React Simple Global Entity Cache instead of Flux/React/etc

I am writing a little "fun" Scala/Scala.js project.
On my server I have Entities which are referenced by uuid-s
(inside Ref-s).
For the sake of "fun", I don't want to use flux/redux architecture but still use React on the client (with ScalaJS-React).
What I am trying to do instead is to have a simple cache, for example:
when a React UserDisplayComponent wants the display the Entity User with uuid=0003
then the render() method calls to the Cache (which is passed in as a prop)
let's assume that this is the first time that the UserDisplayComponent asks for this particular User (with uuid=0003) and the Cache does not have it yet
then the Cache makes an AjaxCall to fetch the User from the server
when the AjaxCall returns the Cache triggers re-render
BUT ! now when the component is asking for the User from the Cache, it gets the User Entity from the Cache immediately and does not trigger an AjaxCall
The way I would like to implement this is the following :
I start a render()
"stuff" inside render() asks the Cache for all sorts of Entities
Cache returns either Loading or the Entity itself.
at the end of render the Cache sends all the AjaxRequest-s to the server and waits for all of them to return
once all AjaxRequests have returned (let's assume that they do - for the sake of simplicity) the Cache triggers a "re-render()" and now all entities that have been requested before are provided by the Cache right away.
of course it can happen that the newly arrived Entity-s will trigger the render() to fetch more Entity-s if for example I load an Entity that is for example case class UserList(ul: List[Ref[User]]) type. But let's not worry about this now.
QUESTIONS:
1) Am I doing something really wrong if I am doing the state handling this way ?
2) Is there an already existing solution for this ?
I looked around but everything was FLUX/REDUX etc... along these lines... - which I want to AVOID for the sake of :
"fun"
curiosity
exploration
playing around
I think this simple cache will be simpler for my use-case because I want to take the "REF" based "domain model" over to the client in a simple way: as if the client was on the server and the network would be infinitely fast and zero latency (this is what the cache would simulate).
Consider what issues you need to address to build a rich dynamic web UI, and what libraries / layers typically handle those issues for you.
1. DOM Events (clicks etc.) need to trigger changes in State
This is relatively easy. DOM nodes expose callback-based listener API that is straightforward to adapt to any architecture.
2. Changes in State need to trigger updates to DOM nodes
This is trickier because it needs to be done efficiently and in a maintainable manner. You don't want to re-render your whole component from scratch whenever its state changes, and you don't want to write tons of jquery-style spaghetti code to manually update the DOM as that would be too error prone even if efficient at runtime.
This problem is mainly why libraries like React exist, they abstract this away behind virtual DOM. But you can also abstract this away without virtual DOM, like my own Laminar library does.
Forgoing a library solution to this problem is only workable for simpler apps.
3. Components should be able to read / write Global State
This is the part that flux / redux solve. Specifically, these are issues #1 and #2 all over again, except as applied to global state as opposed to component state.
4. Caching
Caching is hard because cache needs to be invalidated at some point, on top of everything else above.
Flux / redux do not help with this at all. One of the libraries that does help is Relay, which works much like your proposed solution, except way more elaborate, and on top of React and GraphQL. Reading its documentation will help you with your problem. You can definitely implement a small subset of relay's functionality in plain Scala.js if you don't need the whole React / GraphQL baggage, but you need to know the prior art.
5. Serialization and type safety
This is the only issue on this list that relates to Scala.js as opposed to Javascript and SPAs in general.
Scala objects need to be serialized to travel over the network. Into JSON, protobufs, or whatever else, but you need a system for this that will not involve error-prone manual work. There are many Scala.js libraries that address this issue such as upickle, Autowire, endpoints, sloth, etc. Key words: "Scala JSON library", or "Scala type-safe RPC", depending on what kind of solution you want.
I hope these principles suffice as an answer. When you understand these issues, it should be obvious whether your solution will work for a given use case or not. As it is, you didn't describe how your solution addresses issues 2, 4, and 5. You can use some of the libraries I mentioned or implement your own solutions with similar ideas / algorithms.
On a minor technical note, consider implementing an async, Future-based API for your cache layer, so that it returns Future[Entity] instead of Loading | Entity.

When to Use a Callback function?

When do you use a callback function? I know how they work, I have seen them in use and I have used them myself many times.
An example from the C world would be libcurl which relies on callbacks for its data retrieval.
An opposing example would be OpenSSL: Where I have used it, I use out parameters:
ret = somefunc(&target_value);
if(ret != 0)
//error case
I am wondering when to use which? Is a callback only useful for async stuff? I am currently in the processes of designing my application's API and I am wondering whether to use a callback or just an out parameter. Under the hood it will use libcurl and OpenSSL as the main libraries it builds on and the parameter "returned" is an OpenSSL data type.
I don't see any benefit of a callback over just returning. Is this only useful, if I want to process the data in any way instead of just giving it back? But then I could process the returned data. Where is the difference?
In the simplest case, the two approaches are equivalent. But if the callback can be called multiple times to process data as it arrives, then the callback approach provides greater flexibility, and this flexibility is not limited to async use cases.
libcurl is a good example: it provides an API that allows specifying a callback for all newly arrived data. The alternative, as you present it, would be to just return the data. But return it — how? If the data is collected into a memory buffer, the buffer might end up very large, and the caller might have only wanted to save it to a file, like a downloader. If the data is saved to a file whose name is returned to the caller, it might incur unnecessary IO if the caller in fact only wanted to store it in memory, like a web browser showing an image. Either approach is suboptimal if the caller wanted to process data as it streams, say to calculate a checksum, and didn't need to store it at all.
The callback approach allows the caller to decide how the individual chunks of data will be processed or assembled into a larger whole.
Callbacks are useful for asynchronous notification. When you register a callback with some API, you are expecting that callback to be run when some event occurs. Along the same vein, you can use them as an intermediate step in a data processing pipeline (similar to an 'insert' if you're familiar with the audio/recording industry).
So, to summarise, these are the two main paradigms that I have encountered and/or implemented callback schemes for:
I will tell you when data arrives or some event occurs - you use it as you see fit.
I will give you the chance to modify some data before I deal with it.
If the value can be returned immediately then yes, there is no need for a callback. As you surmised, callbacks are useful in situations wherein a value cannot be returned immediately for whatever reason (perhaps it is just a long running operation which is better performed asynchronously).
My take on this: I see it as which module has to know about which one? Let's call them Data-User and IO.
Assume you have some IO, where data comes in. The IO-Module might not even know who is interested in the data. The Data-User however knows exactly which data it needs. So the IO should provide a function like subscribe_to_incoming_data(func) and the Data-User module will subscribe to the specific data the IO-Module has. The alternative would be to change code in the IO-Module to call the Data-User. But with existing libs you definitely don't want to touch existing code that someone else has provided to you.

Should an API assume the proper calling sequence, or should it verify the assumptions?

I have 2 api calls to implement, let's call them "ShouldDoSomething" and "DoSomething". The first is a test to see if a particular action needs to be taken and the other actually takes that action. Naturally, taking the action is only necessary or valid if the test returns true. There are cases where the test is needed without actually taking the action, so both are necessary.
Should the action call internally run the test and become a no-op if it's not needed, or should the implementation assume that it will only ever be called in the case where the test has already returned true? It seems simpler and safer to validate the assumptions, but then the 'action' call has 3 possible return states instead of two (success, failure, and not needed). Another approach would be to make the test an assertion and abort if the action was called unnecessarily. (this is in C, so exceptions aren't really a good idea)
But it comes down to a choice - simpler api calls or fewer api calls?
Pick a policy according to what you think is cleanest for the intended use cases. Document it clearly and carefully. The most important thing with API decisions like this is documentation, not the specifics of what convention is chosen.
If you decide to use the first option, do you actually need to add a "not needed" return state, or can it simply indicate "success" if the operation is not needed? Don't add complexity unless it's necessary.
I think it would be best to go with:
Another approach would be to make the
test an assertion and abort if the
action was called unnecessarily.
So for example if "DoSomething" is called and "ShouldDoSomething" is telling you that you shouldn't take that particular action then "DoSomething should abort without doing anything. Do you really need to expose "ShouldDoSomething" to the client, if its only testing whether "DoSomething" should be called?
I think it also comes down to what will be changed. Could it be fatal if called inappropriately? If so I think you should put assertions in. If it will be harmless then it doesn't really matter.
I would say safer is the way to go.
Hope this helps.
Stephen Canon is correct about consistency and documentation.
Personally I tend to err on trying to protect people from themselves unless it is a serious performance penalty. In most situations I would lean to checking ShouldDoSomething internally from DoSomething and return an error if DoSomething wasn't required. That indicates a logic error to the user and is a lot nicer than letting them blow up or leaving something in an invalid state that might be hard to debug down the line.
The simplest API (from a user perspective) would be to have the function DoSomethingIfNeeded(), and let you take care of the conditions. Why bother the user?
The least friendly user interface is the one that says: "Now call one of these functions! No, not that one!".

Question using Ext's update() instead of dom.innerHTML

I have a question concerning the performance, reliability, and best practice method of using Extjs's update() method, versus directly updating the innerHTML of the dom of an Ext element.
Consider the two statements:
Ext.fly('element-id').dom.innerHTML = 'Welcome, Dude!';
and
Ext.fly('element.id').update('Welcome, Dude!', false);
I don't need to eval() any script, and I'm certain that update() takes into consideration any browser quirks.
Also, does anyone know if using:
Ext.fly('element-id').dom.innerHTML
is the same as
d.getElementById('element-id').innerHTML
?
Browser and platform compatibility are important, and if the two are fundamentally the same, then ditching Ext.element.dom.innerHTML altogether for update() would probably be my best solution.
Thanks in advance for your help,
Brian
If you do not need to load scripts dynamically into your updated html or process a callback after the update, then the two methods you've outlined are equivalent. The bulk of the code in update() adds the script loading and callback capabilities. Internally, it simply sets the innerHTML to do the content replacement.
Ext.fly().dom returns a plain DOM node, so yes, it is equivalent to the result of getElementById() in terms of the node it points to. The only subtlety to understand is the difference between Ext.fly() and Ext.get(). Ext.fly() returns a shared instance of the node wrapper object (a flyweight). As such, that instance might later point to a different node behind the scenes if any other code calls Ext.fly(), including internal Ext code. As such, the result of a call to Ext.fly() should only be used for atomic operations and not reused as a long-lived object. Ext.get().dom on the other hand returns a new, unique object instance, and in that sense, would be more like getElementById().
I think you answered your own question: "Browser and platform compatibility are important, and if the two are fundamentally the same, then ditching Ext.element.dom.innerHTML altogether for update() would probably be my best solution." JS libraries are intended (in part) to abstract browser differences; update is an example.
#bmoeskau wrote above, update() provides additional functionality that you don't need right for your current problem. Nevertheless, update is a good choice.

Resources