1

On What is a callback function? there's a detailed description of callback methods. According to it, assume function A is provided as an argument of function B as a callback, then when B is triggered by some event, it calls A, and A will return a result to B. Now I have a SAX parser that parses an xml document. It has several callback methods, such as startElement(), endElement() ...in which I can do operations such as setting up a new node. My questions is, why are they called callbacks? They didn't return any result to the caller, i.e. the parser object.

Community
  • 1
  • 1

2 Answers2

4

Generally a piece of software that wants something done is called a client, and the software that provides the service is called a server. The normal mode of interaction is that the client makes calls on the server. A more powerful form of interaction is where the client provides code (functions, methods) that the server can call when specific things happen. These are called callbacks.

In this case, the application is a client and the XML parser is providing the service. The application supplies a ContentHandler to the parser, to be called when parsing events occur. The ContentHandler is a set of callbacks because it is code that is part of the client application to be called by the parsing service.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
1

The essence of being a callback is more a matter of a transfer of control than of a value being returned.

You are given the opportunity to register a callback (aka a handler) for parsing events such as the encountering of an XML element. A SAX parser, once having begun parsing an XML document, will call your callback/handler as it encounters elements. It calls you back, providing information about the element that it has encountered.

See also What is Inversion of Control?

Community
  • 1
  • 1
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • what do you mean by calling *back* ?? In my understanding, it is the handler that should *call the parser back*... – justgivememyicecream Apr 29 '14 at 20:12
  • The sequence is like this: (1) Your code registers your callback method with the SAX parser; (2) your code tells the SAX parser to start parsing; (3) the SAX parser ***calls back*** to your registered callback method when it encounters an XML element; (4) your callback method handles the new XML element per your needs. – kjhughes Apr 29 '14 at 20:28
  • You are correct that control has to return to the parser after the handler finishes step (4), but this transfer is a return, not a call. The parser ***calls back*** the given handler in (3), and the handler returns control to the parser when it ends after (4), typically via a common stack-based return mechanism, not a new call. – kjhughes Apr 30 '14 at 01:51