Одна строка функционирует в C?

Добавьте маршрут к / в router.js

Вот пример:

const router = new Router({
    mode: 'history',
    routes: [{
        {
            path: '/',
            name: 'Home',
            component: Home
        }
    ]
});
9
задан Ori Popowski 24 April 2009 в 09:29
поделиться

8 ответов

Don't be scared of 1-line functions!

A lot of programmers seem to have a mental block about 1-line functions, you shouldn't.

If it makes the code clearer and cleaner, extract the line into a function.

Performance probably won't be affected.

Any decent compiler made in the last decade (and perhaps further) will automatically inline a simple 1-line function. Also, 1-line of C can easily correspond to many lines of machine code. You shouldn't assume that even in the theoretical case where you incur the full overhead of a function call that this overhead is significant compared to your "one little line". Let alone significant to the overall performance of your application.

Abstraction Leads to Better Design. (Even for single lines of code)

Functions are the primary building blocks of abstract, componentized code, they should not be neglected. If encapsulating a single line of code behind a function call makes the code more readable, do it. Even in the case where the function is called once. If you find it important to comment one particular line of code, that's a good code smell that it might be helpful to move the code into a well-named function.

Sure, that code may be 1-line today, but how many different ways of performing the same function are there? Encapsulating code inside a function can make it easier to see all the design options available to you. Maybe your 1-line of code expands into a call to a webservice, maybe it becomes a database query, maybe it becomes configurable (using the strategy pattern, for example), maybe you want to switch to caching the value computed by your 1-line. All of these options are easier to implement and more readily thought of when you've extracted your 1-line of code into its own function.

Maybe Your 1-Line Should Be More Lines.

If you have a big block of code it can be tempting to cram a lot of functionality onto a single line, just to save on screen real estate. When you migrate this code to a function, you reduce these pressures, which might make you more inclined to expand your complex 1-liner into more straightforward code taking up several lines (which would likely improve its readability and maintainability).

25
ответ дан 4 December 2019 в 06:11
поделиться

If used more than once, definitely make it a function, and let the compiler do the inlining (possibly adding "inline" to the function definition). ()

5
ответ дан 4 December 2019 в 06:11
поделиться

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

Я настоятельно рекомендую в каждом вопросе такого рода посмотреть (купить, одолжить, (не) загрузить (бесплатно))) эту книгу: : Роберт К. Мартин - Чистый код . Это книга, на которую должен взглянуть каждый разработчик.

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

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

Поскольку в вашем примере используется синтаксис C (++), вам может потребоваться прочитать встроенные функции , которые устраняют накладные расходы при вызове простой функции. Это ключевое слово является только рекомендацией для компилятора, и оно может не включать все функции, которые вы пометили, и может включить встроенные немаркированные функции.

В .NET JIT встроит методы, которые, по его мнению, являются подходящими, но у вас нет контроля почему или когда это происходит, хотя (насколько я понимаю) отладочные сборки никогда не будут встроены, поскольку это остановит исходный код, соответствующий скомпилированному приложению.

5
ответ дан 4 December 2019 в 06:11
поделиться

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

Функции также следует отдавать предпочтение макросам, поскольку они легче отлаживают, модифицируют, читают и с меньшей вероятностью имеют непреднамеренные побочные эффекты.

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

1
ответ дан 4 December 2019 в 06:11
поделиться

If you use the code within that function 3 times or more, then I would recommend to put that in a function. Only for maintainability.

0
ответ дан 4 December 2019 в 06:11
поделиться

На каком языке? Если вы имеете в виду C, я бы также использовал встроенный классификатор . В C ++ у меня есть опция inline , boost.lamda или и продвижение собственной поддержки C ++ 0x для lamdas.

0
ответ дан 4 December 2019 в 06:11
поделиться

Sometimes it's not a bad idea to use the preprocessor:

#define addint(S, n) (*S)[n/CHAR_SIZE] |= (unsigned char) pow(2, (CHAR_SIZE - 1) - (n % CHAR_SIZE));

Granted, you don't get any kind of type checking, but in some cases this can be useful. Macros have their disadvantages and their advantages, and in a few cases their disadvantages can become advantages. I'm a fan of macros in appropriate places, but it's up to you to decide when is appropriate. In this case, I'm going to go out on a limb and say that, whatever you end up doing, that one line of code is quite a bit.

#define addint(S, n) do { \
    unsigned char c = pow(2, (CHAR_SIZE -1) - (n % CHAR_SIZE)); \
    (*S)[n/CHAR_SIZE] |= c \
  } while(0)
-1
ответ дан 4 December 2019 в 06:11
поделиться
Другие вопросы по тегам:

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