Showing posts with label программирование. Show all posts
Showing posts with label программирование. Show all posts

Sunday, August 4, 2024

ASP.NET Core Best Practices

09/14/2023

By Mike Rousos

This article provides guidelines for maximizing performance and reliability of ASP.NET Core apps.

Thursday, December 8, 2022

Art of Readable Code

Key 1. Fundamental Theorem of Readability.

Code should be written to minimize the time it would take for someone else to understand it (Time-Till-Understanding metric).


Key 2. Packing Information into Names. Pack information into your names: 

  1.   Choose Specific Words; 
  2.   Finding More 'Colorful' Words, (Word Alternatives: send - deliver, dispatch, announce, distribute, route; find - search, extract, locate, recover; start - launch, create, begin, open; make - create, set up, build, generate, compose, add, new) ItТs better to be clear and precise than to be cute;
  3.   Avoid Generic Names Like tmp and retval;
  4.   Prefer Concrete Names over Abstract Names;
  5.   Attaching Extra Information to a Name;
  6.   Shorter Names Are Okay for Shorter Scope;
  7.   Use Name Formatting to Convey Meaning;


Key 3. Actively scrutinize your names by asking yourself, 'What other meanings could someone interpret from this name?'

Before you decide on a name, play devil's advocate and imagine how your name might be misunderstood. The best names are resistant to misinterpretation. 

  1.  When it comes to defining an upper or lower limit for a value, max_ and min_ are good prefixes to use. 
  2.  For inclusive ranges, first and last are good. For inclusive/exclusive ranges, begin and end are best because theyТre the most idiomatic.
  3.  When naming a boolean, use words like is and has to make it clear that itТs a boolean. Avoid negated terms (e.g., disable_ssl).
  4.  Beware of usersТ expectations about certain words. For example, users may expect get() or size() to be lightweight methods.


Key 4. Aestetics vs Design: Consistent style is more important than the 'right' style.

  1.   Use consistent layout, with patterns the reader can get used to.
  2.   Make similar code look similar.
  3.   Group related lines of code into blocks: Rearrange Line Breaks to Be Consistent and Compact; Use Column Alignment When Helpful; Break Code into 'Paragraphs'; 


Key 5. The purpose of commenting is to help the reader know as much as the writer did.

 What not to comment:

  •   Facts that can be quickly derived from the code itself.
  •   'Crutch comments' that make up for bad code (such as a bad function name)-fix the code instead.

 Thoughts you should be recording include:

  •  Insights about why code is one way and not another ('director commentary').
  •  Flaws in your code, by using markers like: TODO: Stuff I haven’t gotten around to yet; FIXME: Known-broken code here; HACK: Admittedly inelegant solution to a problem; XXX: Danger! major problem here;
  •  The 'story' for how a constant got its value.

 Put yourself in the reader’s shoes:

  •  Anticipate which parts of your code will make readers say 'Huh?' and comment those.
  •  Document any surprising behavior an average reader wouldn’t expect.
  •  Use 'big picture' comments at the file/class level to explain how all the pieces fit together.
  •  Summarize blocks of code with comments so that the reader doesn’t get lost in the details.


Key 6. Making Comments Precise and Compact: Comments should have a high information-to-space ratio

  1.   Avoid pronouns like 'it' and 'this' when they can refer to multiple things.
  2.   Describe a function’s behavior with as much precision as is practical.
  3.   Illustrate your comments with carefully chosen input/output examples.
  4.   State the high-level intent of your code, rather than the obvious details.
  5.   Use inline comments (e.g., Function(/* arg = */ ... ) ) to explain mysterious function
  6. arguments.
  7.   Keep your comments brief by using words that pack a lot of meaning.


Key 7. Making Control Flow Easy to Read: Make all your conditionals, loops, and other changes to control flow as 'natural' as possible-written in a way that doesn't make the reader stop and reread your code.

  1.  In a comparison better to put the changing value on the left and the more stable value on the right.
  2.   You can also reorder the blocks of an if/else statement. Generally, try to handle the positive/easier/interesting case first.
  3.   Programming constructs, like ternary operator (: ?), do/while loop, and goto often result in unreadable code; usually best not to use them, as clearer alternatives almost always exist.
  4.   Nested code blocks require more concentration to follow along. Each new nesting requires more context to be 'pushed onto the stack' of the reader.
  5.   Returning early can remove nesting and clean up code in general. 'Guard statements' - simple cases at the top of the function are especially useful.


Key 8. Break down your giant expressions into more digestible pieces.

 a. introduce 'explaining variables' that capture the value of some large subexpression. This approach has three benefits: breaks down a giant expression into pieces; documents the code by describing subexpression with a succinct name; helps the reader identify the main 'concepts' in the code.

 b. manipulate your logic using De Morgan's laws—this technique can sometimes rewrite a boolean expression in a cleaner way (e.g., if (!(a && !b)) turns into if (!a || b)).


Key 9. How the variables in a program can quickly accumulate and become too much to keep track of. You can make your code easier to read by having fewer variables and making them as 'lightweight' as possible:

 a. Eliminate variables that just get in the way. 

 b. Reduce the scope of each variable to be as small as possible. 

 c. Prefer write-once variables. Variables that are set only once (or const, final, or otherwise immutable) make code easier to understand.


Key 10. Extracting Unrelated Subproblems: separate the generic code from the project-specific code. 

 As it turns out, most code is generic. By building a large set of libraries and helper functions to solve the general problems, what’s left will be a small core of what makes your program unique.


Key 11. One Task at a Time: 

Code should be organized so that it's doing only one task at a time (defragmenting).

 

Key 12. Turning Thoughts into Code

  1.   Describe what code needs to do, in plain English, as you would to a colleague.
  2.   Pay attention to the key words and phrases used in this description.
  3.   Write your code to match this description.


Key 13. Writing Less Code: most readable code is no code at all 
[ Adventure, excitement-a Jedi craves not these things. ^ Yoda ]

 Each new line of code needs to be tested, documented, and maintained. Further, the more code in your codebase, the 'heavier' it gets and the harder it is to develop in.

 Avoid writing new lines of code by:

  1.   Eliminating nonessential features from your product and not overengineering.
  2.   Rethinking requirements to solve the easiest version of the problem that still gets the job done.
  3.   Staying familiar with standard libraries by periodically reading through their entire APIs.


Key 14. Testing and Readability: Test code should be readable so that other coders are comfortable changing or adding tests.

  1.   Make Tests Easy to Read and Maintain
  2.   Making Error Messages Readable
  3.   Pick the simplest set of inputs that completely exercise the code.
  4.   Prefer clean and simple test values that still get the job done.
  5.   Give your test functions a fully descriptive name so it’s clear what each is testing. Instead of Test1(), use a name like Test_<FunctionName>_<Situation>.


Appendix: Designing and Implementing

 a. First, start by coding a naive solution. This helped us realize two design challenges: speed and memory use.

 b. Next, try a 'conveyor belt' design. This design improved the speed and memory use but still wasn’t good enough for high-performance applications.

 c. Our final design solved the previous problems by breaking things down into subproblems.


Monday, October 1, 2018

Software disenchantment

 Source   French   Russian  

I’ve been programming for 15 years now. Recently our industry’s lack of care for efficiency, simplicity, and excellence started really getting to me, to the point of me getting depressed by my own career and the IT in general.
Modern cars work, let’s say for the sake of argument, at 98% of what’s physically possible with the current engine design. Modern buildings use just enough material to fulfill their function and stay safe under the given conditions. All planes converged to the optimal size/form/load and basically look the same.
Only in software, it’s fine if a program runs at 1% or even 0.01% of the possible performance. Everybody just seems to be ok with it. People are often even proud about how much inefficient it is, as in “why should we worry, computers are fast enough”:
@tveastman: I have a Python program I run every day, it takes 1.5 seconds. I spent six hours re-writing it in rust, now it takes 0.06 seconds. That efficiency improvement means I’ll make my time back in 41 years, 24 days :-)
You’ve probably heard this mantra: “programmer time is more expensive than computer time”. What it means basically is that we’re wasting computers at an unprecedented scale. Would you buy a car if it eats 100 liters per 100 kilometers? How about 1000 liters? With computers, we do that all the time.

Wednesday, December 9, 2015

Best Practices for Developing World-Ready Applications

Technical Issues

Developers can reduce their development time on almost any international application by considering the following issues prior to the start of the development cycle:
  • Use Unicode as your character encoding to represent text. If you cannot use Unicode, you will need to implement DBCS enabling, bi-directional (BiDi) enabling, code page switching, text tagging, and so on.
  • Consider implementing a multilingual user interface. If you design the user interface to open in the default UI language and offer the option to change to other languages, users of the same machine who speak different languages reduce down time related to software configuration. This may be a particularly useful strategy in regions such as Belgium with more than one culture/locale and official language.
  • Watch for Windows messages that indicate changes in the input language, and use that information for spell checking, font selection, and so on.
  • If you are developing for Windows 2000, test your application on all language variants of Windows 2000, using all possible cultures/locales. Windows 2000 supports the languages used in more than 120 cultures/locales.

Underutilized Features of .NET

1. ObsoleteAttribute

ObsoleteAttribute applies to all program elements except assemblies, modules, parameters, and return values. Marking an element as obsolete informs users that the element will be removed in future versions of the product.
Message property contains a string that will be displayed when the attribute assignee is used. It is recommended a workaround to be provided in this description.
IsError– If set to true the compiler will indicate an error if the attribute target is used in the code.

public static class ObsoleteExample
{
    // Mark OrderDetailTotal As Obsolete.
    [ObsoleteAttribute("This property (DepricatedOrderDetailTotal) is obsolete. Use InvoiceTotal instead.", false)]
    public static decimal OrderDetailTotal
    {
        get
        {
            return 12m;
        }
    }

    public static decimal InvoiceTotal
    {
        get
        {
            return 25m;
        }
    }

    // Mark CalculateOrderDetailTotal As Obsolete.
    [ObsoleteAttribute("This method is obsolete. Call CalculateInvoiceTotal instead.", true)]
    public static decimal CalculateOrderDetailTotal()
    {
        return 0m;
    }

    public static decimal CalculateInvoiceTotal()
    {
        return 1m;
    }
}

Thursday, August 6, 2015

Шаблоны Проектирования


Основные
Делегирования •
 Функционального дизайна •
 Неизменяемый объект • 
Интерфейс
Порождающие
Абстрактная фабрика • 
Строитель • 
Фабричный метод • 
Прототип • 
Одиночка • 
Отложенная инициализация • 
Объектный пул
Структурные
Адаптер • 
Мост • 
Компоновщик • 
Декоратор • 
Фасад • 
Заместитель • 
Приспособленец • 
Выделение частного класса данных
Поведения
Цепочка обязанностей • 
Команда • 
Интерпретатор • 
Итератор • 
Посредник • 
Хранитель • 
Наблюдатель • 
Состояние • 
Стратегия • 
Шаблонный метод • 
Посетитель
Параллельного
программирования
Блокировка с двойной проверкой • 
Планировщик • 
Однопоточное выполнение


Monday, March 9, 2015

Факты, которые знают программисты, и не знают все остальные

Факт 1

Под капотом самых критичных программ, которые вы используете на ежедневной основе (Mac OS X или Facebook) содержится ужасное количество хаков и костылей, которые с трудом уживаются друг с другом. Это как если бы вы разобрали боинг 747 и увидели, что топливопровод держится вешалкой для одежды, а шасси смотаны изолентой.
Бен Черри
Код программ таков, что даже если сайт или программа прекрасно работают и отлично выглядят, то за кулисами всё, что заставляет его работать, состоит из ошибок, ляпов и костылей. Он работает едва-едва и иногда вообще непонятно, почему.
Факт 2

25% времени в программировании уходит на размышления о том, что пользователь может сделать не так.
Брайан Хьюмс
Занимает это на деле больше или меньше процентов времени, но каждый раз нам действительно необходимо подумать – а что пользователь может тут сломать. Куда нажмёт, что введёт, и как можно понять то, что мы пытаемся сделать, неправильно. Если бы мы рассчитывали только на себя, у программ было бы слишком много проблем – ведь мы знаем, как программа работает, а пользователь не знает.

Monday, April 22, 2013

Art of Readable Code


Key 1. Fundamental Theorem of Readability.
Code should be written to minimize the time it would take for someone else to understand it (Time-Till-Understanding metric).

Key 2. Packing Information into Names. Pack information into your names: 
 a. Choose Specific Words;
 b. Finding More 'Colorful' Words, (Word Alternatives: send - deliver, dispatch, announce, distribute, route; find - search, extract, locate, recover; start - launch, create, begin, open; make - create, set up, build, generate, compose, add, new) ItТs better to be clear and precise than to be cute;
 c. Avoid Generic Names Like tmp and retval;
 d. Prefer Concrete Names over Abstract Names;
 e. Attaching Extra Information to a Name;
 f. Shorter Names Are Okay for Shorter Scope;
 g. Use Name Formatting to Convey Meaning;

Key 3. Actively scrutinize your names by asking yourself, 'What other meanings could someone interpret from this name?'
Before you decide on a name, play devil's advocate and imagine how your name might be misunderstood. The best names are resistant to misinterpretation.
 a. When it comes to defining an upper or lower limit for a value, max_ and min_ are good prefixes to use.
 b. For inclusive ranges, first and last are good. For inclusive/exclusive ranges, begin and end are best because theyТre the most idiomatic.
 c. When naming a boolean, use words like is and has to make it clear that itТs a boolean. Avoid negated terms (e.g., disable_ssl).
 d. Beware of usersТ expectations about certain words. For example, users may expect get() or size() to be lightweight methods.

Tuesday, February 7, 2012

Жизненный цикл Программного Обеспечения

Жизненный цикл ПО - период времени, который начинается с момента принятия решения о необходимости создания программного продукта и заканчивается в момент его полного изъятия из эксплуатации. Этот цикл - процесс построения и развития ПО.

Стандарты жизненного цикла ПО

  • ГОСТ 34.601-90
  • ISO/IEC 12207:1995 (российский аналог - ГОСТ Р ИСО/МЭК 12207-99)

Sunday, January 22, 2012

List of freely available programming books

I am trying to amass a list of programming books that are freely available on the Internet. The books can be about a particular programming language or about computers in general. Which are some freely available programming books on the Internet.

Sunday, January 8, 2012

Основные источники информации по Java

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

С момента представления в 1995 г. Java-платформы как единого целого мира, Java прошел радикальный эволюционный путь от концепции “апплеты повсюду”, которую исповедовали первые идеологи и приверженцы. Вместо этого мир Java развился до Swing, сконцентрировался вокруг сервлетов, направил движение к J2EE, споткнулся на EJB, нашел обходной путь через Spring и Hibernate, добавил возможности абстрактного программирования и стал более динамичным, а затем и более функциональным, и продолжает развиваться во множестве интересных направлений, в то время как я пишу эту статью. Это многообразие может несколько озадачить Java-программиста, если он не рос и не развивался профессионально вместе с данным языком все эти годы.