A better version can be found at https://app.box.com/s/8zuk8yd4x9m7rbvinkb0xztz17x6xoqj
This is the slide for a presentation at Golang Melbourne meetup.
Presented at DevWeek (25th March 2015)
These days, testing is considered a sexy topic for programmers. Who’d have thought it? But what makes for good unit tests (GUTs)? There’s more to effective unit testing than just knowing the assertion syntax of a testing framework.
Testing represents a form of communication and, as such, it offers multiple levels and forms of feedback, not just basic defect detection. Effective unit testing requires an understanding of what forms of feedback and communication are offered by tests, and what styles encourage or discourage such qualities.
What style of test partitioning is most common, and yet scales poorly and is ineffective at properly expressing the behaviour of a class or component? What styles, tricks and tips can be used to make tests more specification-like and can scale as the codebase grows?
This session will address these questions and outline exactly what makes a good unit test.
What We Talk About When We Talk About Unit TestingKevlin Henney
Presented at ACCU (23rd April 2015)
These days unit testing is considered sexy for programmers. Who'd have thought it? But there is a lot more to effective programmer testing than the fashionable donning of a unit-testing framework: writing Good Unit Tests (GUTs) involves (a lot) more than knowledge of assertion syntax.
Testing represents a form of communication and, as such, it offers multiple levels and forms of feedback, not just basic defect detection. Effective unit testing requires an understanding of what forms of feedback and communication are offered by tests, and what styles encourage or discourage such qualities.
What styles of test partitioning are common, and yet scale poorly, are uncohesive and are ineffective at properly expressing the behaviour of a class or component? What styles, tricks and tips can be used to make tests more specification-like and scalable to large codebases? How do we choose between scenario-based and property-based test cases?
Presented at ACCU Oxford (14th September 2015)
Functional C++? As opposed to what — dysfunctional? Well, kind of, yeah. Sure, in C++ the principal unit of composition is called a function, but that doesn't mean it's a functional language. And the idea of restricting mutability of state gets a nod with const, but it's a nod not a hug. And the STL shows influences of functional programming, although it falls short of being compositional. And, yes, sure, C++11 has lambdas, but then again, these days, who doesn't? Lambda calculus was invented in the 1930s.
This talk looks at how to express functional programming ideas in (post)modern C++ in a way that can be considered idiomatic to C++, rather than trying to use the power of overloading and meta-programming to pretend C++ is Haskell or Lisp. In short, immutability beyond const and into shared and persistent data structures, concurrency beyond threading and locks, and thinking about functions as transformations and units of composition rather than actions.
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
Один из лучших способов снизить количество багов в играх – это показывать программистам, как не стоит писать код. В своём докладе я соберу самые вкусные и необычные ошибки, которые удалось найти в C++ и C# коде таких игр, как VVVVVV, Space Engineers, Command & Conquer, osu! и даже Doom. Я уверен, что каждый из слушателей обязательно узнает для себя что-то новое. В конце концов, это просто приятно – лично увидеть ошибки из кода знакомой и любимой игры!
Our new blog post featuring some common python programming patterns and their C++ equivalents is now up!
Leave us a comment below and let us know what you'd like to see covered in our future posts!
█ Read More
Technical Insights: Introduction to GraphQL|goo.gl/d7PyXH
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Kevlin Henney
Presented at ACCU (24th April 2015)
It is all to easy to dismiss problematic codebases on some nebulous idea of bad practice or bad programmers. Poor code, however, is rarely arbitrary and random in its structure or formulation. Systems of code, well or poorly structured, emerge from systems of practice, whether effective or ineffective. To improve code quality, it makes more sense to pick apart the specific practices and see their interplay — the cause — than to simply focus on the code itself — the effect. This talk looks at how a handful of coding habits, design practices and assumptions can systematically balloon code and compound its accidental complexity.
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019corehard_by
LLVM содержит огромное количество оптимизаций и подходит в качестве бэкенда для многих языков программирования. Но все немного усложняется для Managed языков и JIT сценариев. В этом докладе Егор расскажет о трудностях, с которыми столкнулись в C# при реализации LLVM бэкенда.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
The document discusses parallel computing in modern C++. It introduces native threads, standard threads in C++11, thread pools, std::async, and examples of parallelizing real applications. It also covers potential issues like data races and tools for detecting them like Valgrind and ThreadSanitizer. Finally, it recommends using std::async, std::future and boost::thread for flexibility and OpenMP for ease of use.
Presented at DevWeek (25th March 2015)
These days, testing is considered a sexy topic for programmers. Who’d have thought it? But what makes for good unit tests (GUTs)? There’s more to effective unit testing than just knowing the assertion syntax of a testing framework.
Testing represents a form of communication and, as such, it offers multiple levels and forms of feedback, not just basic defect detection. Effective unit testing requires an understanding of what forms of feedback and communication are offered by tests, and what styles encourage or discourage such qualities.
What style of test partitioning is most common, and yet scales poorly and is ineffective at properly expressing the behaviour of a class or component? What styles, tricks and tips can be used to make tests more specification-like and can scale as the codebase grows?
This session will address these questions and outline exactly what makes a good unit test.
What We Talk About When We Talk About Unit TestingKevlin Henney
Presented at ACCU (23rd April 2015)
These days unit testing is considered sexy for programmers. Who'd have thought it? But there is a lot more to effective programmer testing than the fashionable donning of a unit-testing framework: writing Good Unit Tests (GUTs) involves (a lot) more than knowledge of assertion syntax.
Testing represents a form of communication and, as such, it offers multiple levels and forms of feedback, not just basic defect detection. Effective unit testing requires an understanding of what forms of feedback and communication are offered by tests, and what styles encourage or discourage such qualities.
What styles of test partitioning are common, and yet scale poorly, are uncohesive and are ineffective at properly expressing the behaviour of a class or component? What styles, tricks and tips can be used to make tests more specification-like and scalable to large codebases? How do we choose between scenario-based and property-based test cases?
Presented at ACCU Oxford (14th September 2015)
Functional C++? As opposed to what — dysfunctional? Well, kind of, yeah. Sure, in C++ the principal unit of composition is called a function, but that doesn't mean it's a functional language. And the idea of restricting mutability of state gets a nod with const, but it's a nod not a hug. And the STL shows influences of functional programming, although it falls short of being compositional. And, yes, sure, C++11 has lambdas, but then again, these days, who doesn't? Lambda calculus was invented in the 1930s.
This talk looks at how to express functional programming ideas in (post)modern C++ in a way that can be considered idiomatic to C++, rather than trying to use the power of overloading and meta-programming to pretend C++ is Haskell or Lisp. In short, immutability beyond const and into shared and persistent data structures, concurrency beyond threading and locks, and thinking about functions as transformations and units of composition rather than actions.
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
Один из лучших способов снизить количество багов в играх – это показывать программистам, как не стоит писать код. В своём докладе я соберу самые вкусные и необычные ошибки, которые удалось найти в C++ и C# коде таких игр, как VVVVVV, Space Engineers, Command & Conquer, osu! и даже Doom. Я уверен, что каждый из слушателей обязательно узнает для себя что-то новое. В конце концов, это просто приятно – лично увидеть ошибки из кода знакомой и любимой игры!
Our new blog post featuring some common python programming patterns and their C++ equivalents is now up!
Leave us a comment below and let us know what you'd like to see covered in our future posts!
█ Read More
Technical Insights: Introduction to GraphQL|goo.gl/d7PyXH
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Kevlin Henney
Presented at ACCU (24th April 2015)
It is all to easy to dismiss problematic codebases on some nebulous idea of bad practice or bad programmers. Poor code, however, is rarely arbitrary and random in its structure or formulation. Systems of code, well or poorly structured, emerge from systems of practice, whether effective or ineffective. To improve code quality, it makes more sense to pick apart the specific practices and see their interplay — the cause — than to simply focus on the code itself — the effect. This talk looks at how a handful of coding habits, design practices and assumptions can systematically balloon code and compound its accidental complexity.
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019corehard_by
LLVM содержит огромное количество оптимизаций и подходит в качестве бэкенда для многих языков программирования. Но все немного усложняется для Managed языков и JIT сценариев. В этом докладе Егор расскажет о трудностях, с которыми столкнулись в C# при реализации LLVM бэкенда.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
The document discusses parallel computing in modern C++. It introduces native threads, standard threads in C++11, thread pools, std::async, and examples of parallelizing real applications. It also covers potential issues like data races and tools for detecting them like Valgrind and ThreadSanitizer. Finally, it recommends using std::async, std::future and boost::thread for flexibility and OpenMP for ease of use.
This document discusses metaprogramming in C++ and describes an RPC framework implemented using C++ templates and metaprogramming. It defines an interface called calc_interface for a calculator RPC with functions like add and signals like expr_evaluated. It shows how to define the interface using meta_functions, and how a client can invoke functions on the server while handling serialization, transport, and response deserialization. Key aspects covered include defining the interface, invoking functions from the client, argument checking, and verifying functions exist in the interface.
Антон Бикинеев, Writing good std::future< C++ >Sergey Platonov
В докладе Антон расскажет о грядущих мажорных изменениях языка, которые, не войдя в Стандарт 17-го года и оставшись в Technical Specifications, будут ждать своего мержа в 20-м, а также быть уже реализованными в некоторых компиляторах. Осветятся также минорные, уже одобренные фичи следующего Стандарта, как языковые, так и библиотечные. Антон расскажет об их целях, покажет методы использования, а также осветит некоторые гайдлайны и трики.
This document provides step-by-step instructions for cloning and building a Flappy Bird clone using Swift. It begins with setting up the project structure and basic gameplay elements like the background, ground and bird. It then adds parallax scrolling, bird animation and physics. Pipes and collision detection are implemented along with scoring. The document details many Swift concepts like classes, protocols and physics bodies to recreate the classic mobile game.
The document discusses clang-tidy, which is a tool for statically analyzing C++ code and finding typical programming errors. It has over 200 built-in rules for checking adherence to coding guidelines and best practices. The document provides examples of running clang-tidy on sample code and detecting issues. It also discusses how to develop custom rules by traversing the AST and registering matchers. Overall, the document serves as an introduction to using clang-tidy for code reviews and improving code quality.
The Ring programming language version 1.5.3 book - Part 91 of 184Mahmoud Samir Fayed
The document discusses using a code generator to wrap C/C++ libraries for use in Ring applications. It describes the configuration file format used as input, including defining function prototypes, structures, constants, and code snippets. Running the code generator takes the configuration file and generates C header and source files that interface with the Ring API. Examples are provided wrapping Allegro functions. The generator handles type checking, conversions, and generates thorough wrapper code with little effort from the programmer.
Не так давно Гор Нишанов представил свой доклад: C++ Coroutines a negative overhead abstraction. В этом докладе Гор упомянул, что предложенный дизайн корутин позволяет их использовать практически в любых окружениях, в том числе и с "бедным" C++ рантаймом.
Я решил попробовать запустить корутины в следующих окружениях: обычное приложение, драйвер ОС Windows, EFI приложение. Только в одном из этих окружений есть полноценный C++ рантайм и поддержка исключений, в остальных ничего этого нет. Более того, EFI приложение вообще выполняется до старта ОС.
Я хочу рассказать о том, как мне удалось запустить корутины в этих окружениях, поговорим о том, какие проблемы существуют в асинхронном системном программировании и как их можно обойти.
PVS-Studio analyzes source code and finds various errors and code quality issues across multiple languages and frameworks. The document highlights 20 examples of issues found, including uninitialized variables, unreachable code, incorrect operations, security flaws, and typos. PVS-Studio is able to find these issues using techniques such as data-flow analysis, method annotation analysis, symbolic execution, type inference, and pattern-based analysis to precisely evaluate the code and pinpoint potential bugs or code smells.
The document discusses new C++11 features including:
1. Uniform initialization syntax using curly braces {} which can initialize objects in a clear and consistent way compared to parentheses () or equals =.
2. Initializer lists and how they allow initializing objects from a list of values. However, initializer lists may prefer certain constructors unintuitively.
3. How uniform initialization helps prevent narrowing conversions and most vexing parse issues that could occur in C++98 code.
Pro typescript.ch03.Object Orientation in TypeScriptSeok-joon Yun
The document discusses object-oriented programming concepts in TypeScript such as classes, inheritance, polymorphism, and mixins. It provides code examples of implementing interfaces and classes to demonstrate inheritance and composition. Mixins are discussed as a way to reuse behavior across class hierarchies by applying multiple base classes to a derived class using a mixin function. The examples show how to define mixin behaviors as classes and apply them to implementing classes to achieve multiple inheritance in TypeScript.
How Data Flow analysis works in a static code analyzerAndrey Karpov
Data flow analysis is a technology for source code analysis, widely used in various development tools: compilers, linters, IDE. We'll talk about it exemplifying with design of a static analyzer. The talk covers classification and various kinds of data flow analysis, neighbouring technologies supporting each other, obstacles arising during development, surprises from C++ language when one tries to analyze the code. In this talk, some errors, detected in real projects using this technology, are shown in detail.
ITGM #9 - Коварный CodeType, или от segfault'а к работающему кодуdelimitry
Доклад с ITGM #9 рассказывающий про реальный пример поиска и исправления Segmentation fault при генерации функции на Python в одном проекте
(Доклад вместе с http://www.slideshare.net/AndreyZakharevich)
The document discusses various decision making and flow control statements in C++ including if, if-else, nested if-else, switch, logical operators, the conditional operator, continue, and goto. It provides syntax examples and flow charts to illustrate the usage and flow of each statement type. Key points covered include single and multi-statement syntax, matching else clauses, break in switch, operator precedence, and using continue to skip the rest of the current loop iteration.
This document discusses dynamically creating functions in Python using metaprogramming techniques. It explores different approaches to programmatically defining functions with a variable number of arguments. The key challenges are correctly handling variable names, argument counts, closure variables, and memory allocation for the new function objects. After several attempts, the document arrives at a working solution that uses the types module to construct CodeType objects and FunctionType objects, ensuring all necessary function attributes like variable names and closure information are properly defined.
PVS-Studio is there to help CERN: analysis of Geant4 projectPVS-Studio
Geant4 project continues developing, so it's really interesting to recheck it with PVS-Studio static code analyzer. This time we'll do a check of version 10.2 (previously, we checked 10.0 beta-version)
The document describes a program to simulate the sliding window protocol for Go back n. It generates random numbers to determine the total number of frames and window size. Frames up to the window size are transmitted and acknowledgements are received. If an acknowledgement is not received, the frames are retransmitted. This continues until all frames are successfully transmitted.
This document discusses various types of constructors in C++ including default, parameterized, copy constructors, and destructors. It also covers initialization lists, static class members, constant objects, and summarizes their key purposes and behaviors. Default constructors initialize objects without parameters, parameterized constructors allow passing initialization values, and copy constructors copy data from one object to another. Destructors clean up object resources. Initialization lists assign member values, static members have a single instance shared among objects, and constant objects cannot be modified.
На протяжении всего существования C++ тема компайл-тайм рефлексии поднимается постоянно, но, к сожалению, до сих пор Стандарт языка не дает достаточных возможностей для извлечения и манипулирования компайл-тайм информацией. Большое количество библиотек и препроцессоров было придумано для того, чтобы решить эту проблему, начиная от простых макросов и заканчивая Qt-moc или ODB. В докладе Антон расскажет о том, как на эту проблему смотрит Комитет по Стандартизации: какие решения были предложены, и какое стало доминирующим.
The document discusses yield in Python and how it allows functions to act as generators by using the yield keyword instead of return, enabling generator functions to control execution by yielding values and resuming at the point after each yield. It explains how generators are created and how yield allows suspending and resuming execution of generator functions to implement features like coroutines, trampolines to avoid recursion limits, and the with statement in Python.
This document summarizes new features in Swift 2 including guard/defer statements for flow control, protocol extensions for default implementations, and error handling improvements like throwing and catching errors. It also mentions Swift becoming open source with its source code released under a permissive license and contributions accepted from the community, including ports for Linux. Nest is provided as an example open source Swift web framework project on GitHub.
This document discusses optimizing C# code for speed, maintainability, and flexibility. It provides tips for using profilers to optimize for speed, establishing coding standards to improve maintainability, and refactoring code. Exceptions, allocation in loops, string concatenation, and validating enum values are discussed as examples of code that could be optimized. Guidelines are provided around using exceptions, GC.Collect, and designing enums.
This document discusses using functional programming techniques in Java to improve KPIs like quality, performance, and developer productivity. It outlines issues with imperative Java like shared mutability and verbosity. Functional approaches can reduce bugs, duplicated code, and complexity. Techniques like immutable collections, streams, and lambdas improve performance by reducing memory usage and garbage collection. Functional Java allows writing more concise, testable code while leveraging the existing Java ecosystem.
This document discusses metaprogramming in C++ and describes an RPC framework implemented using C++ templates and metaprogramming. It defines an interface called calc_interface for a calculator RPC with functions like add and signals like expr_evaluated. It shows how to define the interface using meta_functions, and how a client can invoke functions on the server while handling serialization, transport, and response deserialization. Key aspects covered include defining the interface, invoking functions from the client, argument checking, and verifying functions exist in the interface.
Антон Бикинеев, Writing good std::future< C++ >Sergey Platonov
В докладе Антон расскажет о грядущих мажорных изменениях языка, которые, не войдя в Стандарт 17-го года и оставшись в Technical Specifications, будут ждать своего мержа в 20-м, а также быть уже реализованными в некоторых компиляторах. Осветятся также минорные, уже одобренные фичи следующего Стандарта, как языковые, так и библиотечные. Антон расскажет об их целях, покажет методы использования, а также осветит некоторые гайдлайны и трики.
This document provides step-by-step instructions for cloning and building a Flappy Bird clone using Swift. It begins with setting up the project structure and basic gameplay elements like the background, ground and bird. It then adds parallax scrolling, bird animation and physics. Pipes and collision detection are implemented along with scoring. The document details many Swift concepts like classes, protocols and physics bodies to recreate the classic mobile game.
The document discusses clang-tidy, which is a tool for statically analyzing C++ code and finding typical programming errors. It has over 200 built-in rules for checking adherence to coding guidelines and best practices. The document provides examples of running clang-tidy on sample code and detecting issues. It also discusses how to develop custom rules by traversing the AST and registering matchers. Overall, the document serves as an introduction to using clang-tidy for code reviews and improving code quality.
The Ring programming language version 1.5.3 book - Part 91 of 184Mahmoud Samir Fayed
The document discusses using a code generator to wrap C/C++ libraries for use in Ring applications. It describes the configuration file format used as input, including defining function prototypes, structures, constants, and code snippets. Running the code generator takes the configuration file and generates C header and source files that interface with the Ring API. Examples are provided wrapping Allegro functions. The generator handles type checking, conversions, and generates thorough wrapper code with little effort from the programmer.
Не так давно Гор Нишанов представил свой доклад: C++ Coroutines a negative overhead abstraction. В этом докладе Гор упомянул, что предложенный дизайн корутин позволяет их использовать практически в любых окружениях, в том числе и с "бедным" C++ рантаймом.
Я решил попробовать запустить корутины в следующих окружениях: обычное приложение, драйвер ОС Windows, EFI приложение. Только в одном из этих окружений есть полноценный C++ рантайм и поддержка исключений, в остальных ничего этого нет. Более того, EFI приложение вообще выполняется до старта ОС.
Я хочу рассказать о том, как мне удалось запустить корутины в этих окружениях, поговорим о том, какие проблемы существуют в асинхронном системном программировании и как их можно обойти.
PVS-Studio analyzes source code and finds various errors and code quality issues across multiple languages and frameworks. The document highlights 20 examples of issues found, including uninitialized variables, unreachable code, incorrect operations, security flaws, and typos. PVS-Studio is able to find these issues using techniques such as data-flow analysis, method annotation analysis, symbolic execution, type inference, and pattern-based analysis to precisely evaluate the code and pinpoint potential bugs or code smells.
The document discusses new C++11 features including:
1. Uniform initialization syntax using curly braces {} which can initialize objects in a clear and consistent way compared to parentheses () or equals =.
2. Initializer lists and how they allow initializing objects from a list of values. However, initializer lists may prefer certain constructors unintuitively.
3. How uniform initialization helps prevent narrowing conversions and most vexing parse issues that could occur in C++98 code.
Pro typescript.ch03.Object Orientation in TypeScriptSeok-joon Yun
The document discusses object-oriented programming concepts in TypeScript such as classes, inheritance, polymorphism, and mixins. It provides code examples of implementing interfaces and classes to demonstrate inheritance and composition. Mixins are discussed as a way to reuse behavior across class hierarchies by applying multiple base classes to a derived class using a mixin function. The examples show how to define mixin behaviors as classes and apply them to implementing classes to achieve multiple inheritance in TypeScript.
How Data Flow analysis works in a static code analyzerAndrey Karpov
Data flow analysis is a technology for source code analysis, widely used in various development tools: compilers, linters, IDE. We'll talk about it exemplifying with design of a static analyzer. The talk covers classification and various kinds of data flow analysis, neighbouring technologies supporting each other, obstacles arising during development, surprises from C++ language when one tries to analyze the code. In this talk, some errors, detected in real projects using this technology, are shown in detail.
ITGM #9 - Коварный CodeType, или от segfault'а к работающему кодуdelimitry
Доклад с ITGM #9 рассказывающий про реальный пример поиска и исправления Segmentation fault при генерации функции на Python в одном проекте
(Доклад вместе с http://www.slideshare.net/AndreyZakharevich)
The document discusses various decision making and flow control statements in C++ including if, if-else, nested if-else, switch, logical operators, the conditional operator, continue, and goto. It provides syntax examples and flow charts to illustrate the usage and flow of each statement type. Key points covered include single and multi-statement syntax, matching else clauses, break in switch, operator precedence, and using continue to skip the rest of the current loop iteration.
This document discusses dynamically creating functions in Python using metaprogramming techniques. It explores different approaches to programmatically defining functions with a variable number of arguments. The key challenges are correctly handling variable names, argument counts, closure variables, and memory allocation for the new function objects. After several attempts, the document arrives at a working solution that uses the types module to construct CodeType objects and FunctionType objects, ensuring all necessary function attributes like variable names and closure information are properly defined.
PVS-Studio is there to help CERN: analysis of Geant4 projectPVS-Studio
Geant4 project continues developing, so it's really interesting to recheck it with PVS-Studio static code analyzer. This time we'll do a check of version 10.2 (previously, we checked 10.0 beta-version)
The document describes a program to simulate the sliding window protocol for Go back n. It generates random numbers to determine the total number of frames and window size. Frames up to the window size are transmitted and acknowledgements are received. If an acknowledgement is not received, the frames are retransmitted. This continues until all frames are successfully transmitted.
This document discusses various types of constructors in C++ including default, parameterized, copy constructors, and destructors. It also covers initialization lists, static class members, constant objects, and summarizes their key purposes and behaviors. Default constructors initialize objects without parameters, parameterized constructors allow passing initialization values, and copy constructors copy data from one object to another. Destructors clean up object resources. Initialization lists assign member values, static members have a single instance shared among objects, and constant objects cannot be modified.
На протяжении всего существования C++ тема компайл-тайм рефлексии поднимается постоянно, но, к сожалению, до сих пор Стандарт языка не дает достаточных возможностей для извлечения и манипулирования компайл-тайм информацией. Большое количество библиотек и препроцессоров было придумано для того, чтобы решить эту проблему, начиная от простых макросов и заканчивая Qt-moc или ODB. В докладе Антон расскажет о том, как на эту проблему смотрит Комитет по Стандартизации: какие решения были предложены, и какое стало доминирующим.
The document discusses yield in Python and how it allows functions to act as generators by using the yield keyword instead of return, enabling generator functions to control execution by yielding values and resuming at the point after each yield. It explains how generators are created and how yield allows suspending and resuming execution of generator functions to implement features like coroutines, trampolines to avoid recursion limits, and the with statement in Python.
This document summarizes new features in Swift 2 including guard/defer statements for flow control, protocol extensions for default implementations, and error handling improvements like throwing and catching errors. It also mentions Swift becoming open source with its source code released under a permissive license and contributions accepted from the community, including ports for Linux. Nest is provided as an example open source Swift web framework project on GitHub.
This document discusses optimizing C# code for speed, maintainability, and flexibility. It provides tips for using profilers to optimize for speed, establishing coding standards to improve maintainability, and refactoring code. Exceptions, allocation in loops, string concatenation, and validating enum values are discussed as examples of code that could be optimized. Guidelines are provided around using exceptions, GC.Collect, and designing enums.
This document discusses using functional programming techniques in Java to improve KPIs like quality, performance, and developer productivity. It outlines issues with imperative Java like shared mutability and verbosity. Functional approaches can reduce bugs, duplicated code, and complexity. Techniques like immutable collections, streams, and lambdas improve performance by reducing memory usage and garbage collection. Functional Java allows writing more concise, testable code while leveraging the existing Java ecosystem.
Giordano Scalzo introduces himself as an iOS developer and provides a swift introduction to the Swift programming language. He demonstrates various Swift features through code examples, including functions, closures, classes, structs, enums, generics, and operator overloading. He also discusses unit testing support in Swift through XCTest and Quick. To conclude, he proposes coding a reverse polish notation calculator to demonstrate applying these Swift concepts.
Groovy is a dynamic language for the Java Virtual Machine that aims to provide a concise, readable syntax with features like closures, metaprogramming and domain-specific language support. Some key features include dynamic typing, operator overloading, builders for generating XML/Swing code and the ability to extend any class or category of objects with additional methods. Groovy aims to be fully interoperable with Java while allowing more compact representations of common patterns.
This talk aims to be a gentle introduction to Refinement types in Scala. The talk will also introduce many related topics in the subculture of Typelevel programming in FP like Type theory, Generics (Shapeless), Optics (Monocle) and Law-based testing.
Why refinement types?
When 'String' just doesn't cut it anymore. By encoding validation into a type at the edge-of-the-system layer of your application, you can build your core domain logic without having to worry much about type-safety.
Who is it for?
Ajay would be revisiting the necessary foundations at the beginning of the talk, so beginners are welcome. People who have worked on Scala before would be able to appreciate the power of refined types more.
JavaScript objects must implement certain standard properties and methods. Objects have a prototype property that is either an object or null, and prototype chains must have finite length. The typeof operator returns a string indicating the type of a variable or value. JavaScript supports basic types like undefined, null, boolean, number, string, and object. Functions are objects that can be called, and have properties like length and arguments. Variables declared with var have function scope, while variables assigned without var have global scope. Arrays, objects, and functions can be declared using various syntaxes. JavaScript uses prototypal inheritance rather than classes.
The document discusses Groovy concepts including types, operators, objects, structures, closures, control structures, and methods for strings, lists, and maps. It covers topics such as optional syntax, imports, type checking, numbers, strings, GStrings, lists, maps, enums, operators, date/time operations, and closure usage including delegation and implicit parameters. Groovy allows for optional syntax elements, dynamic typing, closures, and methods to operate on common data types like strings, lists, and maps.
The document introduces go-testdeep, a testing framework for Go that provides a custom comparison engine and operators to easily test nested structures, along with features like accurate error reports, table driven tests, and HTTP request testing. It explains how go-testdeep avoids boilerplate code through methods like Cmp() and shortcuts, allows powerful matching with 62 operators, and encapsulates the testing.T within a td.T instance for additional capabilities.
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
George Gribkov will present on errors found in the code of popular games like System Shock, Doom 3, and osu!. He will discuss how his tool searches for code errors, provide examples of bugs detected, and conclude his presentation. The examples will showcase issues like unused variables, incorrect increment variables in for loops, null pointer dereferences, and misunderstandings of operators like ??. Corrections will be proposed to address the bugs.
This document provides an introduction to using the Google Test framework for unit testing C++ code. It begins with an example of a simple test for a function called calc_isect. It then demonstrates how to add assertions to tests, use test fixtures to reduce duplicated setup code, and generate parameterized tests. The document also covers best practices for test organization, installing and using Google Test, and some key features like XML output and selecting subsets of tests. Overall, the document serves as a tutorial for getting started with the Google Test framework for writing and running unit tests in C++ projects.
Ever wonder what this "new" Kotlin thing is? Curious what the syntax looks like? Unsure how to implement this at your own company? Or do you just want to know what Nick and Cody's favorite things are about this language?
All that and (maybe) more are revealed in Privet Kotlin.
1. Swift includes features like subscripts, optional chaining, and error handling that improve safety and flexibility compared to earlier languages.
2. The document discusses Swift concepts like extensions, protocols, and generics that allow code reuse and abstraction. Protocols define requirements that types can conform to through extensions.
3. Generics allow algorithms to work with different types through type parameters like Stack<Element>, avoiding duplicate non-generic code. This makes code cleaner, safer, and more reusable.
Asynchronous operations are getting more and more popular. To the point that we are getting frameworks and environments revolving strictly around that concept. Boost.ASIO, Twisted and node.js are notable example. We will not explore that area. We will focus on techniques for making asynchronous more readable. We will present different currently used solutions. At the end we will introduce coroutines and explain the concept. We will show how these can be integrated with asynchronous code and what we benefit from using coroutines in asynchronous code.
The document summarizes new features in C# 4.0 including optional and named parameters, dynamic typing, tuples, complex numbers, parallel programming, and thread-safe data structures. It also mentions code contracts, memory-mapped files, and the Managed Extensibility Framework.
Kotlin is a JVM language developed by Jetbrains. Its version 1.0 (production ready) was released at the beginning of the year and made some buzz within the android community. This session proposes to discover this language, which takes up some aspects of groovy or scala, and that is very close to swift in syntax and concepts. We will see how Kotlin boosts the productivity of Java & Android application development and how well it accompanies reactive development.
The document summarizes several Java 5 features including generics, enhanced for loops, autoboxing/unboxing, typesafe enums, varargs, static imports, and annotations. It provides examples and explanations of each feature.
The final dream of every developer is creating his own programming language. Today it is possible to realize that dream with a reasonable effort. In addition to that is also possible to leverage the JVM to make a language that can reuse a huge amount of libraries. In this presentation we are going to see what elements do we need to build our own language, with a compiler for the JVM. This is not only a lot of fun but it can be also useful in practice, to build Domain Specific Languages that compiles to bytecode and can be used together with mainstream languages in larger applications.
Introducing Kotlin — JVM-based language made by JetBrains. Kotlin takes aim at the age and perceived uncoolness of the Java with fresh and popular language features. It can do anything the Java language can do and more, but often with a more concise and pleasant syntax.
Similar to How to not write a boring test in Golang (20)
Introduction of Cybersecurity with OSS at Code Europe 2024Hiroshi SHIBATA
I develop the Ruby programming language, RubyGems, and Bundler, which are package managers for Ruby. Today, I will introduce how to enhance the security of your application using open-source software (OSS) examples from Ruby and RubyGems.
The first topic is CVE (Common Vulnerabilities and Exposures). I have published CVEs many times. But what exactly is a CVE? I'll provide a basic understanding of CVEs and explain how to detect and handle vulnerabilities in OSS.
Next, let's discuss package managers. Package managers play a critical role in the OSS ecosystem. I'll explain how to manage library dependencies in your application.
I'll share insights into how the Ruby and RubyGems core team works to keep our ecosystem safe. By the end of this talk, you'll have a better understanding of how to safeguard your code.
Taking AI to the Next Level in Manufacturing.pdfssuserfac0301
Read Taking AI to the Next Level in Manufacturing to gain insights on AI adoption in the manufacturing industry, such as:
1. How quickly AI is being implemented in manufacturing.
2. Which barriers stand in the way of AI adoption.
3. How data quality and governance form the backbone of AI.
4. Organizational processes and structures that may inhibit effective AI adoption.
6. Ideas and approaches to help build your organization's AI strategy.
Monitoring and Managing Anomaly Detection on OpenShift.pdfTosin Akinosho
Monitoring and Managing Anomaly Detection on OpenShift
Overview
Dive into the world of anomaly detection on edge devices with our comprehensive hands-on tutorial. This SlideShare presentation will guide you through the entire process, from data collection and model training to edge deployment and real-time monitoring. Perfect for those looking to implement robust anomaly detection systems on resource-constrained IoT/edge devices.
Key Topics Covered
1. Introduction to Anomaly Detection
- Understand the fundamentals of anomaly detection and its importance in identifying unusual behavior or failures in systems.
2. Understanding Edge (IoT)
- Learn about edge computing and IoT, and how they enable real-time data processing and decision-making at the source.
3. What is ArgoCD?
- Discover ArgoCD, a declarative, GitOps continuous delivery tool for Kubernetes, and its role in deploying applications on edge devices.
4. Deployment Using ArgoCD for Edge Devices
- Step-by-step guide on deploying anomaly detection models on edge devices using ArgoCD.
5. Introduction to Apache Kafka and S3
- Explore Apache Kafka for real-time data streaming and Amazon S3 for scalable storage solutions.
6. Viewing Kafka Messages in the Data Lake
- Learn how to view and analyze Kafka messages stored in a data lake for better insights.
7. What is Prometheus?
- Get to know Prometheus, an open-source monitoring and alerting toolkit, and its application in monitoring edge devices.
8. Monitoring Application Metrics with Prometheus
- Detailed instructions on setting up Prometheus to monitor the performance and health of your anomaly detection system.
9. What is Camel K?
- Introduction to Camel K, a lightweight integration framework built on Apache Camel, designed for Kubernetes.
10. Configuring Camel K Integrations for Data Pipelines
- Learn how to configure Camel K for seamless data pipeline integrations in your anomaly detection workflow.
11. What is a Jupyter Notebook?
- Overview of Jupyter Notebooks, an open-source web application for creating and sharing documents with live code, equations, visualizations, and narrative text.
12. Jupyter Notebooks with Code Examples
- Hands-on examples and code snippets in Jupyter Notebooks to help you implement and test anomaly detection models.
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframePrecisely
Inconsistent user experience and siloed data, high costs, and changing customer expectations – Citizens Bank was experiencing these challenges while it was attempting to deliver a superior digital banking experience for its clients. Its core banking applications run on the mainframe and Citizens was using legacy utilities to get the critical mainframe data to feed customer-facing channels, like call centers, web, and mobile. Ultimately, this led to higher operating costs (MIPS), delayed response times, and longer time to market.
Ever-changing customer expectations demand more modern digital experiences, and the bank needed to find a solution that could provide real-time data to its customer channels with low latency and operating costs. Join this session to learn how Citizens is leveraging Precisely to replicate mainframe data to its customer channels and deliver on their “modern digital bank” experiences.
A Comprehensive Guide to DeFi Development Services in 2024Intelisync
DeFi represents a paradigm shift in the financial industry. Instead of relying on traditional, centralized institutions like banks, DeFi leverages blockchain technology to create a decentralized network of financial services. This means that financial transactions can occur directly between parties, without intermediaries, using smart contracts on platforms like Ethereum.
In 2024, we are witnessing an explosion of new DeFi projects and protocols, each pushing the boundaries of what’s possible in finance.
In summary, DeFi in 2024 is not just a trend; it’s a revolution that democratizes finance, enhances security and transparency, and fosters continuous innovation. As we proceed through this presentation, we'll explore the various components and services of DeFi in detail, shedding light on how they are transforming the financial landscape.
At Intelisync, we specialize in providing comprehensive DeFi development services tailored to meet the unique needs of our clients. From smart contract development to dApp creation and security audits, we ensure that your DeFi project is built with innovation, security, and scalability in mind. Trust Intelisync to guide you through the intricate landscape of decentralized finance and unlock the full potential of blockchain technology.
Ready to take your DeFi project to the next level? Partner with Intelisync for expert DeFi development services today!
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...Alex Pruden
Folding is a recent technique for building efficient recursive SNARKs. Several elegant folding protocols have been proposed, such as Nova, Supernova, Hypernova, Protostar, and others. However, all of them rely on an additively homomorphic commitment scheme based on discrete log, and are therefore not post-quantum secure. In this work we present LatticeFold, the first lattice-based folding protocol based on the Module SIS problem. This folding protocol naturally leads to an efficient recursive lattice-based SNARK and an efficient PCD scheme. LatticeFold supports folding low-degree relations, such as R1CS, as well as high-degree relations, such as CCS. The key challenge is to construct a secure folding protocol that works with the Ajtai commitment scheme. The difficulty, is ensuring that extracted witnesses are low norm through many rounds of folding. We present a novel technique using the sumcheck protocol to ensure that extracted witnesses are always low norm no matter how many rounds of folding are used. Our evaluation of the final proof system suggests that it is as performant as Hypernova, while providing post-quantum security.
Paper Link: https://eprint.iacr.org/2024/257
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
Main news related to the CCS TSI 2023 (2023/1695)Jakub Marek
An English 🇬🇧 translation of a presentation to the speech I gave about the main changes brought by CCS TSI 2023 at the biggest Czech conference on Communications and signalling systems on Railways, which was held in Clarion Hotel Olomouc from 7th to 9th November 2023 (konferenceszt.cz). Attended by around 500 participants and 200 on-line followers.
The original Czech 🇨🇿 version of the presentation can be found here: https://www.slideshare.net/slideshow/hlavni-novinky-souvisejici-s-ccs-tsi-2023-2023-1695/269688092 .
The videorecording (in Czech) from the presentation is available here: https://youtu.be/WzjJWm4IyPk?si=SImb06tuXGb30BEH .
Skybuffer SAM4U tool for SAP license adoptionTatiana Kojar
Manage and optimize your license adoption and consumption with SAM4U, an SAP free customer software asset management tool.
SAM4U, an SAP complimentary software asset management tool for customers, delivers a detailed and well-structured overview of license inventory and usage with a user-friendly interface. We offer a hosted, cost-effective, and performance-optimized SAM4U setup in the Skybuffer Cloud environment. You retain ownership of the system and data, while we manage the ABAP 7.58 infrastructure, ensuring fixed Total Cost of Ownership (TCO) and exceptional services through the SAP Fiori interface.
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3Data Hops
Free A4 downloadable and printable Cyber Security, Social Engineering Safety and security Training Posters . Promote security awareness in the home or workplace. Lock them Out From training providers datahops.com
5th LF Energy Power Grid Model Meet-up SlidesDanBrown980551
5th Power Grid Model Meet-up
It is with great pleasure that we extend to you an invitation to the 5th Power Grid Model Meet-up, scheduled for 6th June 2024. This event will adopt a hybrid format, allowing participants to join us either through an online Mircosoft Teams session or in person at TU/e located at Den Dolech 2, Eindhoven, Netherlands. The meet-up will be hosted by Eindhoven University of Technology (TU/e), a research university specializing in engineering science & technology.
Power Grid Model
The global energy transition is placing new and unprecedented demands on Distribution System Operators (DSOs). Alongside upgrades to grid capacity, processes such as digitization, capacity optimization, and congestion management are becoming vital for delivering reliable services.
Power Grid Model is an open source project from Linux Foundation Energy and provides a calculation engine that is increasingly essential for DSOs. It offers a standards-based foundation enabling real-time power systems analysis, simulations of electrical power grids, and sophisticated what-if analysis. In addition, it enables in-depth studies and analysis of the electrical power grid’s behavior and performance. This comprehensive model incorporates essential factors such as power generation capacity, electrical losses, voltage levels, power flows, and system stability.
Power Grid Model is currently being applied in a wide variety of use cases, including grid planning, expansion, reliability, and congestion studies. It can also help in analyzing the impact of renewable energy integration, assessing the effects of disturbances or faults, and developing strategies for grid control and optimization.
What to expect
For the upcoming meetup we are organizing, we have an exciting lineup of activities planned:
-Insightful presentations covering two practical applications of the Power Grid Model.
-An update on the latest advancements in Power Grid -Model technology during the first and second quarters of 2024.
-An interactive brainstorming session to discuss and propose new feature requests.
-An opportunity to connect with fellow Power Grid Model enthusiasts and users.
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
3. Test Driven DevelopmentTest Driven DevelopmentTest Driven Development
Write testWrite testWrite test
Write codeWrite codeWrite code 333
4. Unit testingUnit testingUnit testing
Table-driven testTable-driven testTable-driven test
StubStubStub
MockingMockingMocking 444
5. Table-driven testTable-driven testTable-driven test
// Gcd returns the greatest common divisor of 2 numbers.// Gcd returns the greatest common divisor of 2 numbers.// Gcd returns the greatest common divisor of 2 numbers.
func Gcd(a, b int) int {func Gcd(a, b int) int {func Gcd(a, b int) int {
if a%2 == 0 {if a%2 == 0 {if a%2 == 0 {
if b%2 == 0 {if b%2 == 0 {if b%2 == 0 {
return 2 * Gcd(a/2, b/2)return 2 * Gcd(a/2, b/2)return 2 * Gcd(a/2, b/2)
}}}
return Gcd(a/2, b)return Gcd(a/2, b)return Gcd(a/2, b)
}}}
if b%2 == 0 {if b%2 == 0 {if b%2 == 0 {
return Gcd(a, b/2)return Gcd(a, b/2)return Gcd(a, b/2)
}}}
if a == b {if a == b {if a == b {
return areturn areturn a
}}}
if a > b {if a > b {if a > b {
return Gcd(a-b, b)return Gcd(a-b, b)return Gcd(a-b, b)
}}}
return Gcd(b-a, a)return Gcd(b-a, a)return Gcd(b-a, a)
}}} Run
555
6. Table-driven test (2)Table-driven test (2)Table-driven test (2)
func TestGcd(t *testing.T) {func TestGcd(t *testing.T) {func TestGcd(t *testing.T) {
tests := []struct {tests := []struct {tests := []struct {
name stringname stringname string
args argsargs argsargs args
want intwant intwant int
}{}{}{
{{{
"Test two different numbers","Test two different numbers","Test two different numbers",
args{a: 4, b: 6},args{a: 4, b: 6},args{a: 4, b: 6},
2,2,2,
},},},
{{{
"Test two identical numbers","Test two identical numbers","Test two identical numbers",
args{a: 5, b: 5},args{a: 5, b: 5},args{a: 5, b: 5},
5,5,5,
},},},
}}}
for _, tt := range tests {for _, tt := range tests {for _, tt := range tests {
tt := tttt := tttt := tt
t.Run(tt.name, func(t *testing.T) {t.Run(tt.name, func(t *testing.T) {t.Run(tt.name, func(t *testing.T) {
if got := Gcd(tt.args.a, tt.args.b); got != tt.want {if got := Gcd(tt.args.a, tt.args.b); got != tt.want {if got := Gcd(tt.args.a, tt.args.b); got != tt.want {
t.Errorf("Gcd() = %v, want %v", got, tt.want)t.Errorf("Gcd() = %v, want %v", got, tt.want)t.Errorf("Gcd() = %v, want %v", got, tt.want)
}}}
})})})
}}}
}}} Run
9. Stub (1)Stub (1)Stub (1)
Create an implementation which has the same set of functions as the mainCreate an implementation which has the same set of functions as the mainCreate an implementation which has the same set of functions as the main
object/class.object/class.object/class.
type stubClient struct{}type stubClient struct{}type stubClient struct{}
// GetBalance ...// GetBalance ...// GetBalance ...
func (c *stubClient) GetBalance(customerID string, currency string) (int64, error) {func (c *stubClient) GetBalance(customerID string, currency string) (int64, error) {func (c *stubClient) GetBalance(customerID string, currency string) (int64, error) {
return 100, nilreturn 100, nilreturn 100, nil
}}}
// Charge ...// Charge ...// Charge ...
func (c *stubClient) Charge(customerID string, amount int64, currency string, desc string) errorfunc (c *stubClient) Charge(customerID string, amount int64, currency string, desc string) errorfunc (c *stubClient) Charge(customerID string, amount int64, currency string, desc string) error
return nilreturn nilreturn nil
}}}
// TestGetBalanceHappyPath// TestGetBalanceHappyPath// TestGetBalanceHappyPath Run
888
11. Generate mockGenerate mockGenerate mock
Using mockery: go get github.com/vektra/mockery/...Using mockery: go get github.com/vektra/mockery/...Using mockery: go get github.com/vektra/mockery/...
mockery -name=Client -case=underscoremockery -name=Client -case=underscoremockery -name=Client -case=underscore
In test leIn test leIn test le
m := mocks.Client{}m := mocks.Client{}m := mocks.Client{}
m.On("GetBalance", mock.AnythingOfType("string"), mock.AnythingOfType("string")).m.On("GetBalance", mock.AnythingOfType("string"), mock.AnythingOfType("string")).m.On("GetBalance", mock.AnythingOfType("string"), mock.AnythingOfType("string")).
Return(int64(100), nil).Once()Return(int64(100), nil).Once()Return(int64(100), nil).Once()
101010
16. Cucumber for golangCucumber for golangCucumber for golang
Feature: get versionFeature: get versionFeature: get version
In order to know godog versionIn order to know godog versionIn order to know godog version
As an API userAs an API userAs an API user
I need to be able to request versionI need to be able to request versionI need to be able to request version
Scenario: does not allow POST methodScenario: does not allow POST methodScenario: does not allow POST method
When I send "POST" request to "/version"When I send "POST" request to "/version"When I send "POST" request to "/version"
Then the response code should be 405Then the response code should be 405Then the response code should be 405
And the response should match json:And the response should match json:And the response should match json:
"""""""""
{{{
"error": "Method not allowed""error": "Method not allowed""error": "Method not allowed"
}}}
"""""""""
Scenario: should get version numberScenario: should get version numberScenario: should get version number
When I send "GET" request to "/version"When I send "GET" request to "/version"When I send "GET" request to "/version"
Then the response code should be 200Then the response code should be 200Then the response code should be 200
And the response should match json:And the response should match json:And the response should match json:
"""""""""
{{{
"version": "v0.7.13""version": "v0.7.13""version": "v0.7.13"
}}}
""""""""" Run
151515
17. Cucumber style - GodogCucumber style - GodogCucumber style - Godog
func FeatureContext(s *godog.Suite) {func FeatureContext(s *godog.Suite) {func FeatureContext(s *godog.Suite) {
api := &apiFeature{}api := &apiFeature{}api := &apiFeature{}
s.BeforeScenario(api.resetResponse)s.BeforeScenario(api.resetResponse)s.BeforeScenario(api.resetResponse)
s.Step(`^I send "(GET|POST|PUT|DELETE)" request to "([^"]*)"$`, api.iSendrequestTo)s.Step(`^I send "(GET|POST|PUT|DELETE)" request to "([^"]*)"$`, api.iSendrequestTo)s.Step(`^I send "(GET|POST|PUT|DELETE)" request to "([^"]*)"$`, api.iSendrequestTo)
s.Step(`^the response code should be (d+)$`, api.theResponseCodeShouldBe)s.Step(`^the response code should be (d+)$`, api.theResponseCodeShouldBe)s.Step(`^the response code should be (d+)$`, api.theResponseCodeShouldBe)
s.Step(`^the response should match json:$`, api.theResponseShouldMatchJSON)s.Step(`^the response should match json:$`, api.theResponseShouldMatchJSON)s.Step(`^the response should match json:$`, api.theResponseShouldMatchJSON)
}}} Run
161616
18. Other TipsOther TipsOther Tips
Make a habit: de ne a package with interface and mockMake a habit: de ne a package with interface and mockMake a habit: de ne a package with interface and mock
What I should test: functions or behaviours. Write happy path case rst.What I should test: functions or behaviours. Write happy path case rst.What I should test: functions or behaviours. Write happy path case rst.
Consider writting tests for public funcs than private func.Consider writting tests for public funcs than private func.Consider writting tests for public funcs than private func.
Create di erent build tag for unit and integration testsCreate di erent build tag for unit and integration testsCreate di erent build tag for unit and integration tests
// +build unit// +build unit// +build unit
// +build integration// +build integration// +build integration
Disabling cache with count=1Disabling cache with count=1Disabling cache with count=1 171717
19. Test coverageTest coverageTest coverage
go test -covermode=count -coverprofile=count.outgo test -covermode=count -coverprofile=count.outgo test -covermode=count -coverprofile=count.out
go tool cover -func=count.outgo tool cover -func=count.outgo tool cover -func=count.out
181818
20. Using git pre-commit hookUsing git pre-commit hookUsing git pre-commit hook
Edit local changes in .git/hooks/pre-commitEdit local changes in .git/hooks/pre-commitEdit local changes in .git/hooks/pre-commit
Trigger go lint/test before every commitTrigger go lint/test before every commitTrigger go lint/test before every commit
#!/bin/sh#!/bin/sh#!/bin/sh
# run go lint# run go lint# run go lint
# run unit tests# run unit tests# run unit tests
go test -count=1 -short ./...go test -count=1 -short ./...go test -count=1 -short ./...
if [[ $? == 1 ]]; thenif [[ $? == 1 ]]; thenif [[ $? == 1 ]]; then
printf "unit test failed"printf "unit test failed"printf "unit test failed"
exit 1exit 1exit 1
fififi
# run integration tests# run integration tests# run integration tests
# go test --tags=integration ./...# go test --tags=integration ./...# go test --tags=integration ./...
exit 0exit 0exit 0 Run
191919
21. ResourcesResourcesResources
Demo code:Demo code:Demo code: gitlab.com/aladine/testing-demogitlab.com/aladine/testing-demogitlab.com/aladine/testing-demo(https://gitlab.com/aladine/testing-demo)(https://gitlab.com/aladine/testing-demo)(https://gitlab.com/aladine/testing-demo)
Hands-On Dependency Injection in Go, Corey Scott:Hands-On Dependency Injection in Go, Corey Scott:Hands-On Dependency Injection in Go, Corey Scott: EbookEbookEbook
(https://subscription.packtpub.com/book/application_development/9781789132762)(https://subscription.packtpub.com/book/application_development/9781789132762)(https://subscription.packtpub.com/book/application_development/9781789132762)
https://github.com/DATA-DOG/godoghttps://github.com/DATA-DOG/godoghttps://github.com/DATA-DOG/godog
Arts icon byArts icon byArts icon by twitter.com/deniseyu21twitter.com/deniseyu21twitter.com/deniseyu21(https://twitter.com/deniseyu21)(https://twitter.com/deniseyu21)(https://twitter.com/deniseyu21)
202020
22. Hiring - OpenSimSimHiring - OpenSimSimHiring - OpenSimSim
We are hiring golang developers and devops engineers.We are hiring golang developers and devops engineers.We are hiring golang developers and devops engineers. 212121
23. Thank youThank youThank you
Dan TranDan TranDan Tran
@trongdan_tran@trongdan_tran@trongdan_tran(http://twitter.com/trongdan_tran)(http://twitter.com/trongdan_tran)(http://twitter.com/trongdan_tran)
Senior Software Developer atSenior Software Developer atSenior Software Developer at OpensimsimOpensimsimOpensimsim(https://opensimsim.com/)(https://opensimsim.com/)(https://opensimsim.com/)