Каково объяснение позади заголовков?

JSLint помогает Вам поймать проблемы, это не тест законности или замены для размышления. jQuery довольно совершенствуется, когда js идет, который делает такой результат понятным. Я подразумеваю, что эти первые две строки являются взломами скорости, неудивительными, что самый твердый js синтаксический анализатор идет, имеют несколько ошибок.

В любом случае, предположение, что популярный код является совершенно правильным кодом или даже 'хороший', испорчено. Код jQuery хорош, и можно узнать о большом количестве из из чтения его. Необходимо все еще выполнить материал через JSLint, если только потому, что хорошо услышать другое мнение о том, что Вы записали.

Из описания JSLINT:

JSLint берет источник JavaScript и сканирует его. Если это находит проблему, это возвращает сообщение, описывающее проблему и приблизительное местоположение в источнике. Проблемой является не обязательно синтаксическая ошибка, хотя это часто. JSLint смотрит на некоторые конвенции стиля, а также структурные проблемы. Не оказывается, что Ваша программа корректна. Это просто обеспечивает другую пару глаз, чтобы помочь определить проблемы.

JSLint определяет профессиональное подмножество JavaScript, более строгого языка, чем определенный Выпуском 3 Спецификации языка ECMAScript. Подмножество связано с рекомендациями, найденными в Конвенциях Кода для Языка программирования JavaScript.

6
задан Jim Ferrans 2 October 2009 в 06:15
поделиться

9 ответов

It simplifies the compilation process. When you want to compile units independently, you need something to describe the parts that will be linked to without having to import the entirety of all the other files.

It also allows for code hiding. One can distribute a header to allow others to use the functionality without having to distribute the implementation.

Finally, it can encourage the separation of interface from implementation.

They are not the only way to solve these problems, but 30 years ago they were a good one. We probably wouldn't use header files for a language today, but they weren't invented in 2009.

20
ответ дан 8 December 2019 в 02:46
поделиться

The architects of many modern languages such as Java, Eiffel and C# clearly agree with you -- those languages extract the metadata about a module from the implementation. However, per se, the concept of headers doesn't preclude that -- it would obviously be a simple task for a compiler to extract a .h file while compiling a .c, for example, just like the compilers for those other languages do implicitly. The fact that typical current C compilers do not do it is not a language design issue -- it's an implementation issue; apparently there's no demand by users for such a feature, so no compiler vendor bothers implementing it.

As a language design choice, having separate .h files (in a human-readable and editable text format) gives you the best of both worlds: you can start separately compiling client code based on a module implementation that doesn't yet exist, if you wish, by writing the .h file by hand; or you (assuming by absurd a compiler implementation that supplies it;-) can get the .h file automatically from the implementation as a side effect of compiling it.

If C, C++, &c, keep thriving (apparently they're still doing fine today;-), and demand like yours for not manually writing headers grows, eventually compiler writers will have to supply the "header generation" option, and the "best of both worlds" won't stay theoretical!-)

4
ответ дан 8 December 2019 в 02:46
поделиться

Не забывайте документацию, которую предоставляет заголовок. Обычно в нем есть все, что вам нужно знать для использования модуля. Я, со своей стороны, не хочу сканировать длинный исходный код, чтобы узнать, что мне нужно использовать и как это назвать ... Вы все равно извлечете эту информацию, что фактически приведет к - файлу заголовка. Конечно, это больше не проблема современных IDE, но, работая с некоторым старым кодом C, мне очень нравится иметь вручную созданные файлы заголовков, которые включают комментарии об использовании, а также о предварительных и постусловиях.

Сохранение исходного кода, заголовка и дополнительных синхронизированная документация - еще одна банка червей ...

2
ответ дан 8 December 2019 в 02:46
поделиться

The whole idea of inspecting the binary output files of language processors would have been hard to comprehend when C invented .h files. There was a system called JOVIAL that did something like it, but it was exotic and confined more-or-less exclusively to military projects. (I've never seen a JOVIAL program, I've only heard about it.)

So when C came out the usual design pattern for modularity was "no checks whatsoever". There might be a restriction that .text symbols could only link to .text and .data to .data, but that was it. That is, the compilers of the day typically processed one source file at a time and then linkers put them together without the slightest level of error checking other than, if you were lucky, "I'm a function symbol" vs "I'm a data symbol".

So the idea of actually having the compiler understand the thing you were calling was somewhat new.

Even today, if you make a totally bogus header, no one catches you in most AOT compilers. Clever things like CLR languages and Java actually do encode things in the class files.

So yes, in the long run, we probably won't have header files.

2
ответ дан 8 December 2019 в 02:46
поделиться

Нет, у вас нет заголовков в Java, но у вас есть интерфейсы, и я, каждый серьезный гуру Java рекомендует вам определять все, что используется другими проектами / системами в качестве интерфейса и реализации.

Давайте посмотрим, что определение интерфейса Java содержит сигнатуры вызовов, определения типов и константы.

БОЛЬШИНСТВО файлов заголовков C содержит сигнатуры вызовов, определения типов и константы.

Таким образом, для всех практических целей файлы заголовков C / C ++ являются просто определениями интерфейсов и, таким образом, должны считаться хорошей вещью. Теперь я знаю, что в файлах заголовков можно определить множество других вещей (MARCRO, константы и т.д.), но это лишь часть всего прекрасного мира C: -

int function target () {
    // Default for shoot
    return FOOT;
}
1
ответ дан 8 December 2019 в 02:46
поделиться

Подробнее Прочтите здесь

Заголовочный файл обычно содержит предварительные объявления классов, подпрограмм, переменных и других идентификаторов. Программисты, желающие объявить стандартизованные идентификаторы более чем в одном исходном файле, могут поместить такие идентификаторы в один файл заголовка, который затем может включать другой код всякий раз, когда требуется содержимое заголовка.

Стандартная библиотека C и стандартная библиотека C ++ традиционно объявляют свои стандартные функции в файлах заголовков.

1
ответ дан 8 December 2019 в 02:46
поделиться

And what if you want to give somebody else the declarations to use your library without giving them the implementation?

As another answer points out - the original reason for headers was to make the parse/compile easier on platforms with very simple and limited tools. It was a great step forward to have a machine with 2 floppies so you could have the compiler on one and your code on the other - made things a lot easier.

0
ответ дан 8 December 2019 в 02:46
поделиться

Когда вы разделяете код на заголовочные и исходные файлы, вы разделяете объявление и определение. Когда вы смотрите в файлы заголовков, вы можете видеть, что у вас есть, и если вы хотите увидеть детали реализации, вы переходите к исходному файлу.

0
ответ дан 8 December 2019 в 02:46
поделиться

It helps to think a bit about the capabilities of the computers that were available when, say c, was written. Main memory was measured in kilowords, and not necessarily very many of them. Disks were bigger, but not much. Serrious storage meant reel-to-reel tapes, mounted by hand, by grumpy operators, who really wanted you to go away so they could play hunt the wumpus. A 1 MIPS machine was screaming fast. And with all these limitation you had to share it. Possibly with a score of other users.

Anything that reduced the space or time complexity of compilation was a big win. And headers do both.

3
ответ дан 8 December 2019 в 02:46
поделиться