Каково преимущество XML-RPC по простому XML?

Первая форма эффективна, только если vector.size () является быстрой операцией. Это верно для векторов, но не для списков, например. Кроме того, что Вы планируете сделать в теле цикла? Если Вы планируете доступ к элементам как в

T elem = some_vector[i];

тогда, Вы делаете предположение, что контейнер имеет operator[](std::size_t) определенный. Снова, это верно для вектора, но не для других контейнеров.

использование итераторов приближают Вас к контейнерной независимости. Вы не делаете предположения о способности произвольного доступа или быстро size() операция, только что контейнер имеет возможности итератора.

Вы могли улучшить свой код далее при помощи стандартных алгоритмов. В зависимости от того, что это, Вы пытаетесь достигнуть, можно выбрать использовать std::for_each(), std::transform() и так далее. При помощи стандартного алгоритма, а не явного цикла Вы стараетесь не перестраивать колесо. Ваш код, вероятно, будет более эффективным (учитывая правильный алгоритм, выбран), корректный и допускающий повторное использование.

16
задан Peter Mortensen 12 November 2010 в 20:51
поделиться

4 ответа

The short answer is: Both protocols can be used to make remote procedure calls (RPC). Both protocols require an application-level schema to be defined, and generally speaking, neither protocol requires any additional schema for defining how to serialise language-level objects (see below for some details).

However, XmlRpc enjoys greater support from libraries which use meta-programming (reflection) features of language to map XmlRpc calls, directly (well, never 100% directly) to language level function calls. The reason there is better support for XmlRpc than plain XML is either (a) a historical accident/result of marketing on the part of the XmlRpc proponents, or (b) the sum of the minor translation issues listed below tip the scales in favour of XmlRpc.

On the other hand, XmlRpc suffers from 2 main disadvantages: (1) it requires approximately 4 times as much bandwidth, and (2) it subverts the intent of XML schema-validation tools: every packet will simply be stamped as "yes, this is valid XmlRpc", regardless of spelling mistakes and omissions in application-level fields.

The long answer:

Contrary to popular belief, you don't need a standard to define how to encode language level objects in plain XML - there is generally just one "sensible" way (provided the application level schema defines whether you use XML attributes or not), e.g.:

class Room {
    int id=1;
    String code="MR-101";
    String name="Maths room";
    int capacity=30;
};

encoded as:

<Room>
    <id>1</id>
    <code>MR-101</code>
    <name>Maths room</name>
    <capacity>30</capacity>
</Room>

XmlRpc was specifically designed to facilitate the creation of libraries which automatically serialise/unserialise language-level objects in RPC calls, and as such it has some minor advantages when used in this way:

  1. With plain XML, it's possible for a struct with a single member to be confused with an array with a single element.

  2. XmlRpc defines a standard time/date format. {Although treatment of timezones and pure time or pure date timestamps is defined at the application level.}

  3. XmlRpc lets you pass arguments to the function without naming them; Plain XML RPC calls require that you name each argument.

  4. XmlRpc defines a standard way to name the method being called: "methodName". With Plain XML, the tag of the root node would typically be used for this purpose, although alternatives are possible.

  5. XmlRpc defines a simple type system: integers, strings, and so on. {Note that with statically typed languages, the types have to be compiled into the destination object anyway, and therefore are known, and with dynamically typed languages, often int's and float's and strings can be used interchangeably; note also that the XmlRpc type system would typically be a poor match for the type system of the destination language which may have multiple integer types, and so on.}

  6. XmlRpc libraries generally integrate directly with an Http library, whereas Xml serialisation libraries all(?) require the application programmer to pass the XML text to the Http call. In more modern languages such as Java/Python/C#, this is a trivial matter, but not so for e.g. C++.

  7. There is a "marketing perception" that XML describes "documents", whereas XmlRpc is designed for procedure calls. The perception is that sending an XmlRpc message contains an obligation for the server to perform some action, whereas this perception is not as strong with plain XML.

Some people will say "who cares - parsing XML data using recursive descent/DOM/SAX is pretty easy anyway", in which case most of the above objections are irrelevant.

For those who still prefer the ease of use of getting native language objects created automatically, many major languages have libraries which automatically serialise language-level objects into XML without resorting to XmlRpc, e.g.:

.NET - Java - Python

It may be that the success of XmlRpc, such as it is, stems from the availability of the libraries which automatically create language-level objects, and in turn these libraries have an advantage over their plain XML counterparts due to the list of issues above.

Disadvantages of XmlRpc are:

  • As mentioned in the question, it is horribly obese

  • Support for plain XML is ubiquitous and usually does not require integration with large 3rd party libraries. Many applications require a conversion of the automatically created objects to the application's own objects anyway.

  • Many XmlRpc implementations fail to produce true language-level objects of the sort programmers would expect and instead require e.g. run-time lookups of fields or extra syntax.

  • If a schema definition document is used to validate the RPC calls, such as a DTD file, then you lose the ability to check the application-level schema - the DTD file will simply tell you that "this is valid XmlRpc". There is not to my knowledge any standard way to define an application-level schema with an XmlRpc based protocol.

18
ответ дан 30 November 2019 в 17:15
поделиться

Основное преимущество состоит в том, что кто-то уже разработал для вас схему вызова. Это особенно полезно для языков с отражением, где вы можете просто слепо передать, скажем, сложную структуру вызову RPC, и он поможет вам преобразовать это в XML. Это менее ценно, скажем, в C ++, где вы должны явно сообщить библиотеке XML-RPC, какие типы данных представляют собой все типы данных.

Вы правы, что мир не покорил мир штурмом. Странности, которые вы обнаруживаете в библиотеках, связаны с низким уровнем интереса. Я сам использовал два и обнаружил ошибки в обоих. И оба были заброшенными программами, поэтому мне некуда было отправить исправления, поэтому у меня есть частные исправленные версии обоих. Вздох.

10
ответ дан 30 November 2019 в 17:15
поделиться

Основное значение XmlRpc заключается в том, что вам не нужно писать код для генерации и анализа XML-документов, передаваемых по HTTP, поскольку XML-RPC - это предопределенная XML-схема для представления функции. вызовов.

Даже с менее чем оптимальными библиотеками существует дополнительное производное значение, поскольку использование этого типа системы позволяет вам определять ваши удаленные интерфейсы как базовые языковые интерфейсы (абстрактный класс C ++, интерфейсы Java и т. д.), которые являются независимыми. проводного протокола, используемого для связи между компонентами.

Отделение определений интерфейсов от проводного протокола (XML-RPC, SOAP и т. д.) позволяет вам в конечном итоге заменить их на альтернативные протоколы, где это необходимо. Например, в нашей системе у нас есть службы, которые предоставляются с использованием Hessian для наших интерфейсов Flex и SOAP для наших.

2
ответ дан 30 November 2019 в 17:15
поделиться

Позвольте мне начать с конца и вернуться назад:

3) Да, вы можете выполнять удаленные вызовы процедур с помощью простого XML (или простых строк, или двоичного протокола). Разница в том, что XmlRpc - это четко определенный протокол со множеством доступных реализаций, что означает: а) вам не нужно писать столько кода и б) вы можете взаимодействовать с тем, кто находится на другом конце провода, без вам или им приходится иметь дело с кодом друг друга. XmlRpc служит мостом.

2) Я бы сказал, что он достаточно распространен :-) Я работал с XmlRpc на Java, поэтому не могу комментировать проблемы реализации C ++ / PHP.

1) обусловлено (3) выше. Многословие протокола является как следствием, так и причиной его взаимодействия.

1
ответ дан 30 November 2019 в 17:15
поделиться
Другие вопросы по тегам:

Похожие вопросы: