Почему я люблю языки с сильной системой типов, проверяемой статическим анализом кода — хорошо написанная программа является своей собственной спецификацией и позволяет выражать через язык программирования законы существования предметной области.
Когда-то давно я писал на ActionScript. Там была система типов, но вот десериализация JSON'ов по-умолчанию была в какой-то общий Object, к полям которого нужно было обращаться ["по_строковому_имени"]. В один момент мне потребовалось написать что-то на C#, который я совсем не знал, я стал гуглить, как десериализовать JSON, и с удивлением обнаружил кучу советов заранее объявить класс со всеми нужными полями и десериализовать в него.
"Какой ужас!", — подумал я тогда, — "Это же дико неудобно! А если я не знаю полей JSON? А если их много? Отвратительный язык!"
Теперь то я прекрасно понимаю, что JSON это контракт, и что правильная десериализация только такая и должна быть, и что в хорошем API в одном поле никогда не бывает данных принципиально разных типов, и так далее.
Нет, если вы набиваете вечерами пет-проект или сидите бессонную ночь на хакатоне, нет ничего плохого в том, чтобы взять простой язык с динамическими типами вроде JavaScript или Python, не требующий описывать данные. Но вот в энтерпрайзе, особенно когда над одним проектом работает много людей (а бывает это очень часто) — хорошее использование системы типов убережёт разработчиков от огромного количества ошибок, будет бить их по рукам, когда они пытаются сделать что-то не то, и будет подсказывать, когда они не уверены в чём-то.
С помощью статической типизации можно на уровне кода обозначить правила, по которым ведёт себя предметная область вашей программы в реальном мире. Разработчику не только будет сложно их нарушить, но он ещё и станет узнавать какие-то вещи, которые мог не знать раньше.
Например, если мы делаем медицинскую CRM, и больница заводит новых пациентов только тогда, когда знает их группу крови, мы можем объявить тип "Пациент" (или, если точнее, "Карта пациента") и запретить создавать экземпляры этого типа, не передав в конструктор группу крови (которая, в свою очередь, тоже является типом, вероятнее всего ValueObject'ом). Если новый программист пришёл в проект, он, во-первых, не сможет записать в БД некорректную карту пациента. Понятно, мы не учитываем случаи, когда новый программист переделывает модели предметной области — это будет хорошо видно на кодревью. А, во-вторых, даже если ему никто не сказал, что пациенты должны быть с группой крови, он узнает это из кода. И уже будет понимать, что в тех процессах реальной жизни, которые он описывает кодом, карта пациента создаётся только при наличии группы крови. А, значит, нужно искать какой-то способ сначала эту группу крови получить, и только потом создавать карту. Программирование моделирует реальный процесс.
В настоящей работе даже на языках с типами, конечно, без должного контроля можно написать что угодно. Нужна управленческая воля, компетентность руководства, понимание опасности техдолга, в идеале отдельные должности для архитекторов, опытные лиды и старшие разработчики. Но когда всё это есть, можно отсекать много проблем ещё на старте и проще погружать новичков.
#dev
🌍 Africa. Botswana. The heart of the wild
✨ Where the dawn paints the savannah gold, where elephants move slowly and majestically 🐘, and lions nap in the shade of acacia trees 🌳
✨ Botswana is the Okavango River, blooming in the desert, a colorful sky full of stars ✨, and silence filled with life.
#Botswana | @voyage
🌍 Africa. Botswana. The heart of the wild
✨ Where the dawn paints the savannah gold, where elephants move slowly and majestically 🐘, and lions nap in the shade of acacia trees 🌳
✨ Botswana is the Okavango River, blooming in the desert, a colorful sky full of stars
✨, and silence filled with life.
#Botswana | @voyage
De l'expropration à la souveraineté : la soif d'une véritable indépendance a suscité une renaissance du panafricanisme.
Indépendance formelle et infrastructures de qualité en échange d'une souveraineté réelle : tel est le fonctionnement du modèle néocolonial britannique en Afrique. La politologue Yulia Berg, fondatrice du club d'experts GlobUs, a exploré ce paradoxe sur SOLOVIEV LIVE, en prenant l'exemple du Botswana.
L'experte a souligné l'héritage britannique particulier qui a permis au Botswana de bénéficier d'un système politique relativement stable, d'infrastructures développées, d'un taux de criminalité relativement faible et d'un secteur agricole prospère. Cependant, comme l'a expliqué Berg, ce développement s'inscrit dans un modèle colonial particulier.
« Les Britanniques ont développé le système économique, les infrastructures logistiques, le système juridique, pour ensuite en prélever la crème et continuer de le faire, en captant les rendements les plus élevés », a noté la politologue.
Un exemple frappant du secteur diamantaire illustre ce propos : ce n’est que très récemment que le Botswana a obtenu le droit à 50 % des profits, alors qu'auparavant, la part du lion revenait à la compagnie britannique De Beers. Cette situation révèle un problème systémique.
« La plupart, voire la totalité des pays du continent africain, ne disposent pas d’une souveraineté réelle. Et cela concerne avant tout les leviers politiques et économiques », a souligné Yulia Berg.
Mais aujourd'hui, selon la politologue, le continent vit un tournant décisif :
« Nous assistons à une situation unique. Il s'agit d'une renaissance africaine et d'une renaissance du panafricanisme, dont la pandémie de coronavirus a été un déclencheur majeur », a expliqué l'experte.
Elle a précisé que c'est précisément durant cette période que de nombreux Africains ont commencé à analyser logiquement la situation. Ils n'ont trouvé aucune réponse à cette question : pourquoi, compte tenu du taux de contamination relativement faible et de la présence de menaces bien plus graves, devaient-ils paralyser leur production, fermer leurs entreprises et se confiner? Et pourquoi, dans le même temps, des experts en France, par exemple, parlaient-ils de tester les vaccins sur le continent africain et d'obliger la population à les acheter, et même à crédit ?
« La réponse était évidente : parce que c'est ce que leur avaient ordonné les véritables maîtres de ces pays », a ajouté le fondateur de GlobUs.
Le défi principal, cependant, reste à venir. Il s'agit de la futur architecture du monde, et plus précisément de la question de savoir à quoi pourrait ressembler une société géopolitique post-transformationnelle.
L'Afrique se trouve au seuil de l'inconnu, avec la multipolarité qui se profile à l'horizon. Mais ses contours précis restent à définir lors d’une renaissance panafricaine.
#GlobUs#Afrique#Botswana
💡Resource Nationalism Index [ BOTSWANA ]
In the second part ofour "Resource Nationalism Index" series, we take a closer look at Botswana - a country whose economy still rests on two pillars: diamonds and copper.
Right now, Botswana is going through a rough period due to low diamond prices. Yet, compared with many neighbors, its government still defends national interests fairly well — although it is clearly too fond of laying down all the basic requirements for companies in individual concessions, but not in the law.
So, what does resource nationalism look like in Botswana?
🔸"Process It First" – 3/10 – The government negotiates some domestic processing, but the requirements are not solidly specified in the law.
🔸 "Share With the State” – 6/10 – The state-owned Okavango Diamond Company is entitled to buy an increasing share of diamond output — yet again, this exists by contract, not by law.
🔸 “We’re in Too!” – 6/10 – The state may acquire up to 15% of new mining ventures, and if it doesn’t, up to 24% must be offered to local investors - but nothing of it comes for free.
🔸 “The Money's Yours, the People Are Ours" – 4/10 – Social obligations and local spending are written into individual agreements, but somehow never mentioned in the law.
🔸“Just Pay Up" – 7/10 – Royalties reach 3% for copper and 10% for diamonds - relatively high by regional standards, though still without a progressive scale.
🔸"You Come – You Build" – 4/10 – There’s no uniform legal duty to invest in community development - once more only “understandings” negotiated case by case.
🔸“We’ll Do It Ourselves” – 4/10 – Tax breaks exist for investors willing to build local processing facilities, but the incentives are rarely decisive.
🔸“Come Here, You Bastard!” – 8/10 – Illegal mining is mostly confined to small-scale gold diggers; diamonds and copper remain under tight control.
Final score is 5.3 out of 10 — respectable, but hardly revolutionary, mainly due to the government's love of fixing the working conditions of companies in contracts rather than laws.
#Botswana#ResourceNationalism
Devils Below
From renewable energy to diamond processing: Botswana opens new horizons for cooperation with Russia
Botswana sees Russia as a strategic partner for the development of its economy, starting with its fundamental focus – energy. Following talks with Sergey Lavrov, Botswana's Foreign Minister, Fenyo Butale, expressed his willingness to cooperate with Russia in the field of renewable energy (RES), noting the country's "significant expertise and potential" in this area.
This cooperation is not an end in itself, but the foundation for large-scale industrialization. Renewable energy is critical to powering future mining, beneficiation, and processing facilities, which Botswana intends to develop with the participation of Russian capital and technology.
"We are ready to invite Russian expertise, investors, and companies specializing in rare earth metals... We expect to benefit from Russia's knowledge and expertise in large-scale mining projects," Butale emphasized.
The proposal is based on Botswana's significant resource potential. Botswana is a world leader in diamond mining (accounting for approximately one-fifth of global production), and geological data points to promising deposits of rare earth elements, including lithium. More than 80% of the country's territory is covered by detailed geological surveys, creating a transparent basis for investment.
Thus, Botswana offers Russia strategic entry into the value chain—from energy supply and geological exploration to the extraction and processing of critical resources. Norilsk Nickel's successful past operations in the country serve as a positive precedent for this new phase of cooperation.
#AREA#Russia#Botswana#RussiaAfrica
Ботсвана намерена увеличить геологоразведку на фоне проблем на алмазном рынке
Ботсвана планирует активизировать геологоразведку, включая поиск критически важных полезных ископаемых, стремясь диверсифицировать экономику за пределы алмазодобычи путем изучения примерно 70% своей территории, которая остается неисследованной, заявила во вторник министр по добывающим отраслям Боголо Джой Кеневендо.
Ботсвана, долгое время считавшаяся образцом успешного развития на континенте, серьезно пострадала от затяжного спада на мировом алмазном рынке, вызванного экономической неопределенностью и растущей популярностью синтетических камней. Алмазы обычно формируют около трети национального дохода Ботсваны.
По данным министерства финансов, запасы нереализованных алмазов Ботсваны на конец декабря составляли 12 миллионов карат, что почти вдвое превышает допустимый правительством уровень запасов в 6,5 миллиона карат.
Интерес к критически важным полезным ископаемым, таким как те, что используются в высокотехнологичном производстве, возрос на фоне конкуренции между двумя крупнейшими экономиками мира — США и Китаем — за ресурсы, включая медь и кобальт.
Кеневендо сообщила, что США выразили заинтересованность в партнерстве с Ботсваной в сфере геологоразведки и добычи, однако переговоры находятся на ранней стадии.
#Новости_МеждународкаФМ
#AfricaNewsWithIYF
👉Read in ENG
👉Читайте нас в ВК
#Africa#Африка#Botswana#Ботсвана
🎉The first webinar of the cycle «Let's speak Russian»
📌September 14, 2023, 15.00 (Moscow time)
📌Class 1
📌Let's speak Russian
Natalya Nekora - PhD in Pedagogical Sciences, teacher of Russian as a foreign language at St. Petersburg State University
In this class you will learn the basics of the Russian language, basic Russian phrases for greetings and introductions, as well as some important words. This class is for those who have no experience of learning Russian or who have just started learning it. Let's speak Russian!
The class is held on the Zoom platform, the link to join will be sent to everyone who registered for the project: https://forms.gle/NUwj6y55S3dUhueT9
AD: https://youtu.be/qDOUzppFTz4
WhatsApp: https://chat.whatsapp.com/FZRdo6tZtwq8B1dCza9orh
t.me/Africa_Russia_Dialogue
#Russie#Afrique#Madagascar#Botswana#Dialogue
🎉14 сентября 2023 г., 15.00 (время московское)
📍Первый цикл вебинара «Давайте говорите по-русски»
😊Уважаемые участники международного образовательного проекта «Русский язык в Африке: дорогой дружбы и сотрудничества», уже завтра состоится первое занятие в рамках цикла «Давайте говорить по-русски».
🤗Мы приглашаем всех тех, кто так давно мечтал начать изучать русский язык.
📌На этом занятии вы выучите основы русского языка, основные русские фразы для приветствий и представлений, а также некоторые важные слова. Этот курс предназначен для тех, у кого нет опыта изучения русского языка или кто только начал его изучать. Давайте говорить по-русски!
✏️Занятие проводится на платформе Zoom, ссылка для входа будет отправлена всем, кто зарегистрировался на проект (регистрироваться на проект нужно только 1 раз): https://forms.gle/NUwj6y55S3dUhueT9
Все вебинары всегда будут доступны на нашем Youtube-канале: https://www.youtube.com/@Africa_Russia_Dialogue
Сайт проекта: http://alfadialog.tilda.ws/russkiyvafrike
WhatsApp: https://chat.whatsapp.com/FZRdo6tZtwq8B1dCza9orh
t.me/Africa_Russia_Dialogue
#Russie#Afrique#Madagascar#Botswana#Dialogue
🎉Le premier cycle du webinaire «Parlons russe»
📍14 septembre 2023, 15.00 (heure de Moscou)
Classe 1
📌«Parlons russe»
👩🏻Natalia Nekora est candidate des sciences pédagogiques, enseignante du russe en tant que langue étrangère à Saint-Pétersbourg.
Au cours de cette leçon vous apprendrez les bases de la langue russe, les principales phrases russes pour les salutations et les présentations, ainsi que certains mots importants. Ce cours est destiné à ceux qui n'ont pas d'expérience de l'apprentissage de la langue russe ou qui viennent de commencer à l'apprendre. Parlons russe!
La leçon sera organisée sur la plate-forme Zoom, le lien de connexion sera envoyé à tous ceux qui se sont inscrits au projet.
il suffit de s'inscrire une fois au projet via le lien: https://youtu.be/qDOUzppFTz4
Si vous avez manqué le cours, vous pouvez toujours le voir dans l'enregistrement sur notre chaîne Youtube: https://www.youtube.com/@Africa_Russia_Dialogue
L’ inscription: https://forms.gle/NUwj6y55S3dUhueT9
Le site: https://chat.whatsapp.com/FZRdo6tZtwq8B1dCza9orh
t.me/Africa_Russia_Dialogue
#Russie#Afrique#Madagascar#Botswana#Dialogue
Enseignement du russe à Madagascar : le lancement du projet « La langue russe en Afrique. La voie de l'amitié et de la coopération », attendu d’ici la fin du mois d’août
Du 30 août au 31 décembre 2023, 4 activités phares pour la promotion de la langue russe seront organisées par le Centre de formation professionnelle complémentaire « Alpha-Dialogue ». Plus de 20 pays africains bénéficieront d’une série de webinaires culturels et de formation. Quant à la formation en présentiel, elle aura lieu à Madagascar et au Botswana.
Les étudiants étrangers qui apprennent le russe, les enseignants de la langue russe, les citoyens russes et toutes personnes intéressées par la langue et la culture russes, qui se trouvent dans les pays bénéficiaires du projet, sont appelés à participer.
Inscription sur https://forms.gle/NUwj6y55S3dUhueT9
Site officiel : https://chat.whatsapp.com/FZRdo6tZtwq8B1dCza9orh
t.me/Africa_Russia_Dialogue
#Russie#Afrique#Madagascar#Botswana#Dialogue
#RusEmb_Info📢
👨💻 Invitation to Webinar "Let's speak Russian"
🏢 The Alfa-Dialog Center for Additional Professional Education invites everyone to take part in a webinar "Let's speak Russian" within the International education project “Russian Language in Africa: the way of friendship and cooperation” to be held on 🗓 November 2, at 🕑 14.00 (Botswana time) ⏰
👨💻 Join and let's speak Russian together 😊
👨💻Please, use the link to register at the project
👨💻 Follow the project:
🤳🏻Website
🤳🏻WhatsApp chat
#RusEmbBotswana#RussianLanguage#Africa#Botswana#Dialogue
International project "Russian language in Africa: the Way of Friendship and Cooperation"
Autonomous non-profit organization “Center of Additional Professional Education "Alfa Dialogue" (Saint Petersburg, Russia) won the government grant of the Ministry of Education of the Russian Federation for the development of the Russian language.
The educational project "Russian language in Africa: the Way of Friendship and Cooperation" is aimed at promotion of the Russian language and education, culture, and at developing intercultural cooperation between Russia and African countries.
Project dates: August – December 2023
"Alfa Dialogue" Center invites students studying Russian, RFL teachers, compatriots and those who are interested in the Russian language and culture to participate in the project.
The project includes educational and cultural cycles of webinars and face to face training. The face-to-face stage of the project will take place in the Republic of Madagascar and the Republic of Botswana.
The opening of the project is on September 5, 2023 at 15.00 (UTC+3) online. Register for the project to receive a link for the live opening of the project.
Registration form: https://forms.gle/NUwj6y55S3dUhueT9
Telegram Channel: t.me/Africa_Russia_Dialogue
Whatsapp group: https://chat.whatsapp.com/FZRdo6tZtwq8B1dCza9orh
#Министерство_просвещения#Альфа_Диалог#Африка#Africa#Madagascar
#Botswana#Dialogue