简体   繁体   中英

gen_server:call vs. just calling a function directly

Let's say there are two processes running in gen_server (started by the supervisor). One calls a function in the other like this: brother:function(Param) . It could also do gen_server:call(brother, Param) . What are the use cases for each? In both cases the first process waits for the function in brother to finish, so I don't understand when each should be used.

There isn't any difference directly. However, using gen_server:call (or cast ) directly means that you are tying your other modules to the internals of the gen_server . Imagine that later on, you want to change the registration of brother so that it uses something else (for example, an external library such as gproc). Now you have to go and find every single place where you used gen_server:call(brother, ...) and fix it, and duplicate a lot of code to fetch the server name and so on. Overall it's just a lot easier to have that brother:function(...)

The same applies to changing the internal structure of calls or casts. It becomes a lot easier to just pass in everything as arguments to a function, and then use that function to construct the parameters. Like, say you use that function to create a record that's internal to the module.

So overall, it's mostly about encapsulation and separation of concerns. The module should generally take care of finding the proper server to send the call to, and the proper format for the calls.

the first process waits for the function in brother to finish

No, it doesn't. Or rather, it depends on how function is defined. It'll often be something like

function(Param) -> gen_server:call(?MODULE, {function, Param}) 
%% or gen_server:call(?MODULE, Param) if there's only one kind of request

and the actual implementation will be in brother:handle_call .

Obviously in that case there's no difference between the results of calling brother:function(Param) or doing gen_server:call manually, but calling brother:function is a better practice: it allows to hide the details calling module has no business knowing and allows brother to change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM