<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[paysafe-bulgaria - Medium]]></title>
        <description><![CDATA[Anything technical @ Paysafe Bulgaria - Medium]]></description>
        <link>https://medium.com/paysafe-bulgaria?source=rss----db09e34211aa---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>paysafe-bulgaria - Medium</title>
            <link>https://medium.com/paysafe-bulgaria?source=rss----db09e34211aa---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 01:22:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/paysafe-bulgaria" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SpringBoot DTO Validation — Good practices and breakdown]]></title>
            <link>https://medium.com/paysafe-bulgaria/springboot-dto-validation-good-practices-and-breakdown-fee69277b3b0?source=rss----db09e34211aa---4</link>
            <guid isPermaLink="false">https://medium.com/p/fee69277b3b0</guid>
            <category><![CDATA[dto]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[validation]]></category>
            <dc:creator><![CDATA[Zhivko M Georgiev]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 16:37:31 GMT</pubDate>
            <atom:updated>2024-02-05T16:37:31.184Z</atom:updated>
            <content:encoded><![CDATA[<h3>SpringBoot DTO Validation — Good practices and breakdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x0Taczje4fiWWYpT" /><figcaption>“Make it correct, make it clear, make it concise, make it fast. In that order.” — Wes Dyer</figcaption></figure><p>In this article we will take a look at:</p><ul><li>What is the actual problem we are dealing with</li><li>Java Bean Validation — JST 380/303 Overview</li><li>Annotations</li><li>Entity vs DTO or where to put the annotations</li><li>@Valid and @Validated</li><li>Custom Validators</li></ul><h4><strong>What is the actual problem we are dealing with</strong></h4><p>Most of todays applications receive, send and maintain enormous amounts of data that needs to be validated and error checked before being processed and later on persisted in a database. Not to mention the numerous API integrations our code can have, validation is the first thing that should be on out mind.</p><p>One way to perform this validation of our data is by using <strong>if/else</strong> tree logic. This leads to <strong>code clutter and makes the code harder to read and maintain</strong>, and typically this style of coding is <strong>not reusable</strong> across different parts of our applications or in different projects. Moreover, as our applications grow, so does the complexity of our validation logic, and managing complex validation rules in <strong>if/else</strong> statements can become challenging and error-prone.</p><h4><strong>Java Bean Validation — JSR 380/303 Overview</strong></h4><p>JSR 380 is a Java Specification Request that defines a standard way to declare and apply validation constraints to Java objects and it is introduced in Java EE 7. It is a specification of the Java API for bean validation and part of the Java EE(Enterprise Edition) and Jakarta EE(formerly Java EE) platform.</p><p>Starting with SpringBoot 2.3, we also need to explicitly add the spring-boot-starter-validation dependency. Examples for Maven and Gradle:</p><pre>&lt;dependency&gt;   <br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;  <br>  &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>implementation &#39;org.springframework.boot:spring-boot-starter-validation:&lt;vesion&gt;&#39;</pre><h4><strong>Annotations and example project</strong></h4><p>Let’s take a look at an example project to illustrate the benefits of annotations. The project is an university rest API, consisting of users, student urls and books. We shall focus only on the <em>User </em>side of logic, that is what we will be validating now.</p><p>The source code can be found on my <a href="https://github.com/Jivkomg/dto-validation-demo"><em>GitHub account</em></a><em>.</em></p><pre>@Entity<br>@Table(name=&quot;users&quot;)<br>public class User extends BaseEntity {<br><br>    private String name;<br><br>    private String email;<br><br>    private int age;<br><br>    private Degree degree;<br><br>    private StudentUrl studentUrl;<br><br>    private List&lt;Book&gt; books;<br><br>    //Standard getters and setters</pre><p>We have an entity representing the user with <em>name</em>, <em>email </em>and <em>age</em>. The degree is enum between <em>Bachelor</em>, <em>Master </em>and <em>Doctorate</em>. The <em>StudentUrl </em>is an entity consisting of <em>url </em>and <em>lastAccessed </em>date and books is a collection of <em>Book </em>entities assigned to the user, with title and author.</p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, String&gt; {<br>}</pre><p>A standard <em>UserRepository </em>extending <em>JpaRepository </em>for retrieving User information from the database.</p><pre>public class UserDto {<br>    private String id;<br><br>    private String name;<br><br>    private String email;<br><br>    private int age;<br><br>    private String degree;<br><br>    private String url;<br><br>    private List&lt;String&gt; bookTitles;</pre><p>A <em>UserDto </em>class, used for retreiving, updating and creating a <em>User </em>entity. In this DTO we only want the most basic information, for example we do not need the <em>lastAccess </em>property from the <em>url</em>, that is why we only have <em>String url</em>. Similarly, we do not need the book’s author and we are only dealing with the title. A custom Entity to DTO mapper is used for converting between the two.</p><pre>@RestController<br>public class UserController {<br><br>    private UserService userService;<br><br>    private ErrorMapper errorMapper;<br><br>    @Autowired<br>    public UserController(UserService userService, ErrorMapper errorMapper) {<br>        this.userService = userService;<br>        this.errorMapper = errorMapper;<br>    }<br><br>    @GetMapping(&quot;/users&quot;)<br>    public List&lt;UserDto&gt; getUsers() {<br>        return userService.getAllUsers();<br>    }<br><br>    @GetMapping(&quot;/users/{id}&quot;)<br>    public ResponseEntity getUser(<br>        @UserIdPathVariableExists<br>        @PathVariable String id<br>    ) {<br>        try {<br>            return new ResponseEntity&lt;&gt;(this.userService.getUserById(id), HttpStatus.OK);<br>        } catch (Exception e) {<br>            return new ResponseEntity&lt;&gt;(this.errorMapper.createErrorMap(e), HttpStatus.BAD_REQUEST);<br>        }<br>    }<br><br>    @PostMapping(&quot;/users&quot;)<br>    ResponseEntity createUser(<br>        @Valid<br>        @RequestBody UserDto userDto) {<br>        try {<br>            return new ResponseEntity&lt;&gt;(this.userService.createUser(userDto), HttpStatus.CREATED);<br>        } catch (Exception e) {<br>            return new ResponseEntity&lt;&gt;(this.errorMapper.createErrorMap(e), HttpStatus.BAD_REQUEST);<br>        }<br>    }<br><br>    @PutMapping(&quot;/users/{id}&quot;)<br>    ResponseEntity updateUser(<br>        @UserIdPathVariableExists<br>        @PathVariable String id,<br>        @RequestBody UserDto userDto<br>    ) {<br>        try {<br>            return new ResponseEntity&lt;&gt;(this.userService.updateUser(id, userDto), HttpStatus.OK);<br>        } catch (Exception e) {<br>            return new ResponseEntity&lt;&gt;(this.errorMapper.createErrorMap(e), HttpStatus.BAD_REQUEST);<br>        }<br>    }<br>}</pre><p>A simple <em>UserController </em>is used</p><pre><br>@Service<br>public class UserService {<br><br>    private UserRepository userRepository;<br><br>    private BookRepository bookRepository;<br><br>    private StudentUrlRepository studentUrlRepository;<br><br>    @Autowired<br>    public UserService(UserRepository userRepository, BookRepository bookRepository, StudentUrlRepository studentUrlRepository){<br>        this.userRepository = userRepository;<br>        this.bookRepository = bookRepository;<br>        this.studentUrlRepository = studentUrlRepository;<br>    }<br><br>    public UserDto createUser(UserDto userDto) {<br>        this.validateUserDto(userDto);<br><br>        User userDtoToBeCreated = EntityToDtoMapper.mapUserDtoToUser(userDto);<br><br>        this.setupAdditionalFields(userDto, userDtoToBeCreated);<br><br>        User savedUser =  userRepository.save(userDtoToBeCreated);<br><br>        return EntityToDtoMapper.mapUserToUserDto(savedUser);<br>    }<br><br>    public UserDto updateUser(String id, UserDto userDto) {<br>        this.validateUserDto(userDto);<br><br>        Optional&lt;User&gt; userOptional = userRepository.findById(id);<br><br>        if (userOptional.isEmpty()) {<br>            throw new RuntimeException(&quot;User with id &quot; + id + &quot; does not exist&quot;);<br>        }<br>        User dbUser = userOptional.get();<br><br>        this.checkValidDegreeChange(dbUser.getDegree(), userDto.getDegree());<br><br>        EntityToDtoMapper.mapUserDtoToUser(dbUser, userDto);<br><br>        this.setupAdditionalFields(userDto, dbUser);<br><br>        User savedUser =  userRepository.save(dbUser);<br><br>        return EntityToDtoMapper.mapUserToUserDto(savedUser);<br>    }<br>}</pre><p>When we are creating and updating a <em>User</em>, we need to validate the incoming input data. One way to this is by using a method to check through all the necessary fields and throw an exception. For example, let’s say we want the <em>name </em>and <em>mail </em>to be required fields. Furthermore, let’s add that the <em>age </em>should be between 18 and 100, the <em>url </em>to be less than 100 characters, the degree to be one of the possible values and if the degree is Doctorate the <em>url </em>should be mandatory.</p><pre>private void validateUserDto(UserDto userDto) {<br>    if (userDto.getName().isBlank() || null == userDto.getName()) {<br>        throw new RuntimeException(&quot;Name is required&quot;);<br>    }<br><br>    if (userDto.getEmail().isBlank() || null == userDto.getEmail()) {<br>        throw new RuntimeException(&quot;Email is required&quot;);<br>    }<br><br>    if (!userDto.getEmail().endsWith(&quot;@uni-sofia.com&quot;)) {<br>        throw new RuntimeException(&quot;Email must end with @uni-sofia.com&quot;);<br>    }<br><br>    if (userDto.getAge() &lt; 18) {<br>        throw new RuntimeException(&quot;User must be 18 or older&quot;);<br>    }<br><br>    if (userDto.getAge() &gt; 100) {<br>        throw new RuntimeException(&quot;User must be 100 or younger&quot;);<br>    }<br><br>    if (!userDto.getDegree().equals(Degree.BACHELOR.toString()) &amp;&amp; !userDto.getDegree().equals(Degree.MASTER.toString()) &amp;&amp; !userDto.getDegree().equals(Degree.DOCTORATE.toString())) {<br>        throw new RuntimeException(&quot;Degree must be BACHELOR, MASTER or DOCTORATE&quot;);<br>    }<br><br>    if (!userDto.getUrl().isBlank() &amp;&amp; userDto.getUrl().length() &gt; 100) {<br>        throw new RuntimeException(&quot;Url must be less than 100 characters&quot;);<br>    }<br><br>    if (userDto.getDegree().equals(Degree.DOCTORATE.toString()) &amp;&amp; userDto.getUrl().isEmpty()) {<br>        throw new RuntimeException(&quot;Url is required for DOCTORATE degree&quot;);<br>    }<br>}</pre><p>Let’s add validation only for creating a user. The user should not be able to change the degree from Doctorate.</p><pre>private void checkValidDegreeChange(Degree degree, String userDtoDegree) {<br>    if (degree.toString().equals(Degree.DOCTORATE.toString()) &amp;&amp; !userDtoDegree.equals(Degree.DOCTORATE.toString())) {<br>        throw new RuntimeException(&quot;Cannot change degree from DOCTORATE&quot;);<br>    }<br>}</pre><p>This absolutely gets the job done, but is this the best way to validate our DTOs? Rules and requirements change all the time, and most of the time the objects have complex relationships between their fields with complex requirements about them. When validation rules change or evolve, we need to manually update every <strong>if/else</strong> block that performs validation, which can lead to maintenance overhead. On the other hand, <strong>if/else</strong> statements rely on individual developers to implement validation, leading to inconsistencies and potential deviations from best practices Let’s see how our code will change if we extract this validation logic in annotations.</p><p><strong>Annotations</strong></p><p>Most common validation annotations:</p><ul><li><em>@NotNull </em>— validates that the annotated property value is not null</li><li><em>@Size — </em>validates that the annotated property value has a size between the attributes min and max; can be applied to String, Collection, Map, and array properties</li><li><em>@Min — </em>validates that the annotated property has a value no smaller than the value attribute</li><li><em>@Max — </em>validates that the annotated property has a value no larger than the value attribute</li><li><em>@Email — </em>validates that the annotated property is a valid email address</li><li><em>@NotBlank — </em>can be applied only to text values and validates that the property is not null or whitespace</li><li><em>@UniqueElements — </em>validates that every object in the provided Collection is unique</li></ul><pre>public class UserDto {<br>    private String id;<br><br>    @NotBlank(message = &quot;Name cannot be blank&quot;)<br>    private String name;<br><br>    @NotBlank(message = &quot;Email cannot be blank&quot;)<br>    @Email(message = &quot;Email should be valid&quot;, regexp = &quot;^[A-Za-z0-9+_.-]+@uni-sofia.com&quot;)<br>    private String email;<br><br>    @Min(value = 18, message = &quot;Age should be greater than 18&quot;)<br>    @Max(value = 100, message = &quot;Age should be less than 100&quot;)<br>    private int age;<br><br>    @Pattern(regexp = &quot;BACHELOR|MASTER|DOCTORATE&quot;, message = &quot;Degree should be BACHELOR, MASTER or DOCTORATE&quot;)<br>    private String degree;<br><br>    @Size(max = 100, message = &quot;Url should be up to 100 characters&quot;)<br>    private String url;<br><br>    @UniqueElements(message = &quot;Book titles should be unique&quot;)<br>    private List&lt;String&gt; bookTitles;</pre><pre>@PostMapping(&quot;/users&quot;)<br>ResponseEntity createUser(<br>    @Valid<br>    @RequestBody UserDto userDto) {<br>    try {<br>        return new ResponseEntity&lt;&gt;(this.userService.createUser(userDto), HttpStatus.CREATED);<br>    } catch (Exception e) {<br>        return new ResponseEntity&lt;&gt;(this.errorMapper.createErrorMap(e), HttpStatus.BAD_REQUEST);<br>    }<br>}</pre><p>We can remove the validate <em>UserDto </em>method from the <em>UserService </em>entirely. This makes the code much more readable, the requirements are in the DTO definition and we can instantly see the rules that the objects need to follow, and the error message it gives.</p><p>In order for the message to be retreived we can make a <em>GlobalExceptionHandler </em>class. The <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html"><em>@ExceptionHandler</em></a> annotation allows us to handle specified types of exceptions through one single method.</p><pre>@ExceptionHandler(MethodArgumentNotValidException.class)<br>public ResponseEntity&lt;Object&gt; handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {<br>    StringBuilder strBuilder = new StringBuilder();<br><br>    e.getBindingResult().getAllErrors().forEach((error) -&gt; {<br>        String fieldName;<br>        try {<br>            fieldName = ((FieldError) error).getField();<br><br>        } catch (ClassCastException ex) {<br>            fieldName = error.getObjectName();<br>        }<br>        String message = error.getDefaultMessage();<br>        strBuilder.append(String.format(&quot;%s: %s\n&quot;, fieldName, message));<br>    });<br><br>    return new ResponseEntity&lt;&gt;(errorMapper.createErrorMap(strBuilder.substring(0, strBuilder.length()-1)), HttpStatus.BAD_REQUEST);<br>}</pre><p>When Spring Boot finds an argument annotated with <em>@Valid</em>, it automatically bootstraps the default JSR 380 implementation — Hibernate Validator — and validates the argument. When the target argument fails to pass the validation, Spring Boot throws a <em>MethodArgumentNotValidException </em>exception.</p><h4><strong>Entity vs DTO or where to put the annotations</strong></h4><p>The question of where to perform validation often spur heated debate.</p><ol><li>DTO</li></ol><p>On the one hand DTOs are designed for data transport and presentation, whereas entities represent the data state within application. By placing validation logic on the DTO we enforce a clear separation of concerns. This helps the code to be more organized but that does not guarantee entity validity.</p><p>2. Entity</p><p>If we validate only on the entity, we will be safe from both incoming requests and on our service layer, however we may have a performance issue. Every time we load an entity from the database, Hibernate wastes memory and CPU to maintain the entity’s state on the persistence context, even if the entity is in “read only mode”. The process of encountering an error on an entity is: starting a transaction, loading the entity, changing the entity, flushing the persistence context and rolling back the transaction. Many of these operations can be expensive and we did it all just to throw it in the trash, when we could simply have never done anything if we had validated the properties earlier.</p><p>3. Both?</p><p>Look at the following example: Another service in our application modifies the <em>User</em> entity and then persists it with a blank name. If we validate only in the controller and the DTOs like our example we are safe against persisting an invalid entry, but only from incomming requests. And if we have a service that manipulates the entity it may persist it in an invalid state without us even noticing. The best way to perform validation is to perform it on all stages — DTOs, entities and finally in the database. It doesn’t matter if we have repeating logic, the most important thing is to have stored entities which are valid.</p><p>For the purpose of this demonstration we are focusing on the annotation validation on the DTO side.</p><h4>@Valid and @Validated</h4><p>The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation.</p><p>On the other hand, we can use @Validated for group validation, including the following partial validation. It is a Spring-specific annotation used for method-level validation.</p><pre>@Validated<br>@RestController<br>public class UserController<br><br>...<br><br>ResponseEntity updateUser( <br>  @Validated(Update.class)</pre><p>This way, we can group validation based on the operation by adding <em>(groups = Update.class) </em>to our annotation.</p><h4>Custom Validators</h4><p>Creating a custom validator entails rolling out our own annotation and using it in our model to enforce the validation rules.</p><pre>@Target({TYPE, ANNOTATION_TYPE})<br>@Retention(RUNTIME)<br>@Repeatable(NotBlankIfAnotherFieldHasValue.List.class)<br>@Constraint(validatedBy = NotBlankIfAnotherFieldHasValueValidator.class)<br>@Documented<br>public @interface NotBlankIfAnotherFieldHasValue {<br><br>    String fieldName();<br>    String fieldValue();<br>    String dependFieldName();<br><br>    String message() default &quot;{NotBlankIfAnotherFieldHasValue.message}&quot;;<br>    Class&lt;?&gt;[] groups() default {};<br>    Class&lt;? extends Payload&gt;[] payload() default {};<br><br>    @Target({TYPE, ANNOTATION_TYPE})<br>    @Retention(RUNTIME)<br>    @Documented<br>    @interface List {<br>        NotBlankIfAnotherFieldHasValue[] value();<br>    }<br>}</pre><pre>/**<br> * Implementation of {@link NotBlankIfAnotherFieldHasValue} validator.<br> **/<br>public class NotBlankIfAnotherFieldHasValueValidator<br>    implements ConstraintValidator&lt;NotBlankIfAnotherFieldHasValue, Object&gt; {<br><br>    private String fieldName;<br>    private String expectedFieldValue;<br>    private String dependFieldName;<br><br>    @Override<br>    public void initialize(NotBlankIfAnotherFieldHasValue annotation) {<br>        fieldName = annotation.fieldName();<br>        expectedFieldValue = annotation.fieldValue();<br>        dependFieldName = annotation.dependFieldName();<br>    }<br><br>    @Override<br>    public boolean isValid(Object value, ConstraintValidatorContext ctx) {<br>        if (ObjectUtils.isEmpty(value)) {<br>            return true;<br>        }<br><br>        BeanWrapperImpl wrapper = new BeanWrapperImpl(value);<br>        Object fieldValue = wrapper.getPropertyValue(fieldName);<br>        Object dependFieldValue = wrapper.getPropertyValue(dependFieldName);<br><br>        if (expectedFieldValue.equals(fieldValue) &amp;&amp; StringUtils.isEmpty(dependFieldValue)) {<br>            ctx.disableDefaultConstraintViolation();<br>            ctx.buildConstraintViolationWithTemplate(ctx.getDefaultConstraintMessageTemplate()).addConstraintViolation();<br>            return false;<br>        }<br><br>        return true;<br>    }<br>}</pre><pre>@NotBlankIfAnotherFieldHasValue(fieldName = &quot;degree&quot;, fieldValue = &quot;DOCTORATE&quot;, dependFieldName = &quot;url&quot;, message = &quot;Url cannot be blank for doctorate degree&quot;)</pre><p>With the <em>@Constraint</em> annotation, we defined the class that is going to validate our field. The <em>message()</em> is the error message that is showed in the user interface. Finally, the additional code is mostly boilerplate code to conform to the Spring standards.</p><p>The validation class implements the <em>ConstraintValidator </em>interface, and must also implement the <em>isValid </em>method; it’s in this method that we defined our validation rules.</p><p>The best thing about these custom validators that they are perfect for attributes dependency, can be reused and provide a nice abstraction to our code.</p><p>Validation is not just a mundane task but a crucial guardian of data integrity, security, and user experience. By validating our input data, we ensure that our applications remain resilient to external threats and provide users with a smooth, error-free experience.</p><h4>References</h4><ul><li>Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications by Anghel LeonardAnghel Leonard</li><li><a href="https://beanvalidation.org/2.0-jsr380/">https://beanvalidation.org/2.0-jsr380/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fee69277b3b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paysafe-bulgaria/springboot-dto-validation-good-practices-and-breakdown-fee69277b3b0">SpringBoot DTO Validation — Good practices and breakdown</a> was originally published in <a href="https://medium.com/paysafe-bulgaria">paysafe-bulgaria</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Мистерията Progressive Web App]]></title>
            <link>https://medium.com/paysafe-bulgaria/%D0%BC%D0%B8%D1%81%D1%82%D0%B5%D1%80%D0%B8%D1%8F%D1%82%D0%B0-progressive-web-app-8d1a5b0ecf5f?source=rss----db09e34211aa---4</link>
            <guid isPermaLink="false">https://medium.com/p/8d1a5b0ecf5f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Kaloyan Georgiev]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 13:29:33 GMT</pubDate>
            <atom:updated>2023-11-07T13:30:49.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8OiLAXoENK7Yi1-2yeQig.png" /></figure><h3>Въведение</h3><p>Progressive Web App (<strong>PWA</strong>) е вид application software, достъпен през мрежата и изграден с помощта на популярни уеб технологии като <strong>HTML</strong>, <strong>CSS</strong>, <strong>PHP</strong>, <strong>JavaScript</strong>, в това число и производния на JavaScript TypeScript. PWA е предназначен да работи на всички платформи, които използват браузър, отговарящ на стандартите (HTTP и HTTPS/HTML, XML и XHTML/Графични файлови формати/Cookie/JavaScript/public key и RSS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xxsEFnxY0F2BeGWKg-HuVA.png" /></figure><p>Като пионери в използването и популяризирането на PWA можем да посочим <strong><em>Twitter</em></strong>. По-късно в надпреварата се включват <em>Microsoft с Outlook,</em> <em>Google с Google Drive</em>, <em>NASA</em>, <em>Aliexpress, Financial Times</em> и много други.</p><h3>Характеристики</h3><p>Progressive Web App работи с всеки браузър и различните такива поддържат множество функционалности, характерни и за самия application software:</p><ul><li>Connection neutrality (offline support)</li><li>Home screen install</li><li>Push-notifications</li><li>URL app integration</li></ul><p>Наред с горепосочените <strong>PWA</strong>,<strong> </strong>чрез уеб браузъра, позволява и достъп до хардуера, което допринася за това приложението да изглежда като native, независимо дали е на мобилно или друго устройство (laptop, PC, tablet). Тъй като този application software е вид уеб страница, или в случая уеб приложение, инсталацията през <em>Apple App Store</em> или <em>Google Play</em> не е задължителна. Важно е да споменем и service-worker като най-значителната характеристика на Progressive Web App. Тази тема ще бъде засегната в следващата статия (какво прави и как работи).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*9WA1-kGayz20ZwnFoaNX6A.png" /></figure><p>От април 2018 г. споменатите по-горе функционалности се поддържат от всички основни уеб браузъри.</p><p>В хода на своята еволюция PWA използва така характерната за всички native apps <strong>Biometric Authentication, </strong>вече част и от <em>Internet Expolorer, Chrome, Safari.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*5c_OAQh6zZIPX3P6iTsI-A.png" /></figure><p><em>Специално внимание трябва да се обърне на последния, тъй като тази функционалност понастоящем е в графата </em><strong><em>experimental features.</em></strong></p><h3>Приложение на PWA</h3><p>Бизнес случаи при които използването на Progressive Web App носи голяма придадена стойност:</p><ul><li>Предоставяне на multiplatform решения на потребителите</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zedpCh2mahXee33Nc2qURg.png" /></figure><ul><li>Разработване на уеб базирани продукти с ограничен бюджет</li><li>Своевременна реакция и адаптация на продукта според постоянно изменящите се нужди на клиента</li><li>Високо качество на продукта</li><li>Съкращаване на <strong>release lifecycle</strong></li></ul><h3>Интеграция</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/24/1*82hUTxczhDXSQIDIKSpXJw.png" /><figcaption>Angular</figcaption></figure><p>ng add @angular/pwa --project *project-name*<br>С тази команда се получава най-важното dependency към <strong>service-worker</strong>, включва го, импортва го и го регистрира в app module. Също така променя и index.htmlконфигурацията, добавя manifest.json,ngsw-config.jsonи, разбира се, основните лого изображения във всички поддъжани резолюции. След това потребителите с лекота ще могат да инсталират приложението на всички платформи.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/24/1*yRz_NVt_VHOABQuCeU4AQA.jpeg" /><figcaption>WordPress</figcaption></figure><p>Използва се Add-On, наречен <em>SuperPWA</em>. Лесен за използване и цялата конфигурация е показана в полета и генерирането на основните PWA файлове се случва точно след инсталацията на добавката.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/24/1*0L8cZcoZUzAvya9y4RBQJg.jpeg" /><figcaption>React</figcaption></figure><p>npm install -g create-react-app<br>След инсталирането на create-react-app трябва да се изпълни командата create-react-app pushercoins генерира всички основни файлове за завършен Progressive Web App и вече трябва да бъде конфигурирано според нуждите на проекта.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/24/1*OyvHaiikDd7a8LR5xnS1ew.jpeg" /><figcaption>Static Web Pages (html, js and css)</figcaption></figure><p>Всичко в статичните страници без framework трябва да се направи ръчно и да се добавят основните файлове както и service-worker частта.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/28/1*BNRdPBOunkmS2vvTw7kFNg.png" /><figcaption>ASP.net</figcaption></figure><p>От Microsoft направиха това възможно края на март 2020г. Официалният release не е обявен още. Обаче може да се направят PWA проекти чрез използването на <strong>Blazor WebAssembly </strong>и командата:<br>dotnet new blazorwasm -o MyNewProject --pwa</p><h3>Cross-Reference Conclusion</h3><p>В тази статия разгледахме PWA технологията, как и къде е приложима. В следващата статия ще погледнем в дълбочина Progressive Web App, Hybrid App(web+native) и изцяло Native App.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d1a5b0ecf5f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paysafe-bulgaria/%D0%BC%D0%B8%D1%81%D1%82%D0%B5%D1%80%D0%B8%D1%8F%D1%82%D0%B0-progressive-web-app-8d1a5b0ecf5f">Мистерията Progressive Web App</a> was originally published in <a href="https://medium.com/paysafe-bulgaria">paysafe-bulgaria</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PWA — технология за всички платформи]]></title>
            <link>https://medium.com/paysafe-bulgaria/pwa-%D1%82%D0%B5%D1%85%D0%BD%D0%BE%D0%BB%D0%BE%D0%B3%D0%B8%D1%8F-%D0%B7%D0%B0-%D0%B2%D1%81%D0%B8%D1%87%D0%BA%D0%B8-%D0%BF%D0%BB%D0%B0%D1%82%D1%84%D0%BE%D1%80%D0%BC%D0%B8-2c5e24bffc84?source=rss----db09e34211aa---4</link>
            <guid isPermaLink="false">https://medium.com/p/2c5e24bffc84</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[pwa-development]]></category>
            <dc:creator><![CDATA[Kaloyan Georgiev]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 13:26:29 GMT</pubDate>
            <atom:updated>2023-11-07T13:26:29.802Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>PWA — технология за всички платформи</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*v79Cp4MS87fz08LOAIailA.png" /></figure><p>Progressive Web App (<strong>PWA</strong>) е технологията, която ще промени начина на работа на уеб базираните услуги. Стъпвайки върху функционалностите на уеб браузърите, тази технология отваря достъпа до съответния ресурс на клиенти от всички платформи. Популярните магазини за приложения (Мicrosoft Store, Apple App Store и Google Play Store) вече отвориха врати за подобен тип приложения.</p><p>Популяризирането на технологията се осъществява след като Twitter решават да експериментират с въвеждането ѝ за мобилните си потребители. Днес PWA е част от повечето продукти, предоставяни и от основни имена като Google и Microsoft.</p><h3>Функционалности</h3><p>Необременени от специфичен уеб framework и програмен език, функционалностите, които PWA предоставя, се доближават до native приложенията, благодарение на развитието на следните браузър функции:</p><ul><li>Offline support — посредством service-worker кешира и запазва всички необходими файлове за работа в offline режим</li><li>Home screen install — директна инсталация през браузъра, не през някой от магазините за приложения</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*cyimf2B64y4jadHSmPnptA.png" /></figure><ul><li>Push Notifications — абониране на потребителите за онлайн известия</li><li>Biometric Authentication — с развитието на браузърите и достъпа им до Biometric API на всички устройства този feature е вече част и от PWA</li><li>URL PWA Integration — при вече инсталиран PWA връзката ще бъде отворена в приложението</li><li>Navigation Bar Color — с добавянето на manifest.json файла и theme_color пропъртито задаваме фона на navigation bar компонента в браузъра</li></ul><h3><strong>Технологията от близо</strong></h3><h4>manifest.json</h4><p>Описващ с пропъртита всичко необходимо за вашето приложение. В този файл може да се намери име на приложението (short_nameи name) и описание (description), икони, появяващи се във всички платформи (icons object) и start_url — тук важно е страницата да е статична и да може да работи offline. Наред с гореизброените присъсъва и пропърти за цветовете в приложението (background_color, theme_color), както и scope — индикира дали сайтът е напълно под PWA или от определена част от нея.</p><pre>{<br>  &quot;short_name&quot;: &quot;Weather&quot;,<br>  &quot;name&quot;: &quot;Weather: Do I need an umbrella?&quot;,<br>  &quot;description&quot;: &quot;Weather forecast information&quot;,<br>  &quot;icons&quot;: [<br>    {<br>      &quot;src&quot;: &quot;/images/icons-192.png&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;sizes&quot;: &quot;192x192&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;/images/icons-512.png&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;sizes&quot;: &quot;512x512&quot;<br>    }<br>  ],<br>  &quot;start_url&quot;: &quot;/?source=pwa&quot;,<br>  &quot;background_color&quot;: &quot;#3367D6&quot;,<br>  &quot;display&quot;: &quot;standalone&quot;,<br>  &quot;scope&quot;: &quot;/&quot;,<br>  &quot;theme_color&quot;: &quot;#3367D6&quot;<br>}</pre><h4>service worker</h4><blockquote>Скрипт, който бразърът стартира на заден план, отделно от уеб страницата, обхождайки всичко в зададения scope, за да може приложението да работи бързо, ефективно и, най-важното, offline. В момента service-woker поддържа push notifications и background sync. В бъдеще се очаква функционалността му да се разшири с периодична синхронизация и location ограничения. <br>Важно е да знаем: <br> * Това е JavaScript Worker<br> * Програмируемо proxy, коeто позволява контрол на мрежовите заявки<br> * При неизползване се терминира автономно<br> * При нужда се рестартира самостоятелно</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*ofOHedNahIoZnCrApwhCVA.png" /></figure><h4>ngsw-config.json</h4><p>Конфигурация, описваща файловете, които service worker обхожда и кешира, както и метода на зареждане.</p><pre>{<br>  &quot;index&quot;: &quot;/index.html&quot;,<br>  &quot;assetGroups&quot;: [<br>    {<br>      &quot;name&quot;: &quot;app&quot;,<br>      &quot;installMode&quot;: &quot;prefetch&quot;,<br>      &quot;resources&quot;: {<br>        &quot;files&quot;: [<br>          &quot;/favicon.ico&quot;,<br>          &quot;/index.html&quot;,<br>          &quot;/*.css&quot;,<br>          &quot;/*.js&quot;<br>        ]<br>      }<br>    }, {<br>      &quot;name&quot;: &quot;assets&quot;,<br>      &quot;installMode&quot;: &quot;lazy&quot;,<br>      &quot;updateMode&quot;: &quot;prefetch&quot;,<br>      &quot;resources&quot;: {<br>        &quot;files&quot;: [<br>          &quot;/assets/**&quot;,<br>          &quot;/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)&quot;<br>        ]<br>      }<br>    }<br>  ]<br>}</pre><h3>Предимства на PWA</h3><ul><li>Бърз и лесен за интеграция във всички уеб приложения</li><li>Използва всички иновации, добавяни в уеб браузърите</li><li>Работа offline</li><li>Доближаващ се все повече до core функционалностите на native apps</li><li>Съкратен release cycle — всичко в едно.</li><li>Без нужда от update в магазините за приложения</li><li>Сигурността, която уеб базираната услуга предоставя, бива пренесена в своята цялост и на мобилното приложение</li><li>Високо качество на продукта</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c5e24bffc84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paysafe-bulgaria/pwa-%D1%82%D0%B5%D1%85%D0%BD%D0%BE%D0%BB%D0%BE%D0%B3%D0%B8%D1%8F-%D0%B7%D0%B0-%D0%B2%D1%81%D0%B8%D1%87%D0%BA%D0%B8-%D0%BF%D0%BB%D0%B0%D1%82%D1%84%D0%BE%D1%80%D0%BC%D0%B8-2c5e24bffc84">PWA — технология за всички платформи</a> was originally published in <a href="https://medium.com/paysafe-bulgaria">paysafe-bulgaria</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient development — Avoiding the chores of programming]]></title>
            <link>https://medium.com/paysafe-bulgaria/efficient-development-avoiding-the-chores-of-programming-fe76c0c3152b?source=rss----db09e34211aa---4</link>
            <guid isPermaLink="false">https://medium.com/p/fe76c0c3152b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[intellij]]></category>
            <dc:creator><![CDATA[Tsvetan Dimitrov]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 16:56:08 GMT</pubDate>
            <atom:updated>2023-01-25T16:56:08.532Z</atom:updated>
            <content:encoded><![CDATA[<h3>Efficient development — Avoiding the chores of programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfwRSNsPlR7NO2XMktH1PA.jpeg" /><figcaption>Programming chores are just like the ones in life, once you get used to solving them you don’t even notice doing it</figcaption></figure><h3>What are “chores” in programming?</h3><p>When you look up the definition for a “chore” you can see it classified as</p><blockquote>a routine task, a tedious but necessary task</blockquote><p>In life that would be doing the laundry or throwing the trash. In programming it would be building your app before you run it or setting up an environment. Doing these kinds of things is never fun or painless. You could be doing anything but you’re stuck in this tedious process until you finish it because it <strong>has</strong> to be done.</p><p>As programmers we have the ability to rise above those chores though. But we rarely do. You’d be surprised at how many people still keep doing the same command sequence over and over and they refuse to automate it because they “can’t find the time”. You won’t find the time on the street though, in life, and especially in a professional setting, time is often <strong><em>made</em></strong>, it’s not <strong><em>found</em></strong>.</p><p>There is however an overlooked subset of chores that we frequently avoid improving simply because they seem too small to have any room for improvement. I’d like to zoom in on these so called “micro chores” and show you a few tips and tricks to get better and faster at dealing with them. The term micro chore is something I thought best describes these really tiny tasks that we face every day. A micro chore is something so small that you’d think it has a negligible impact but will in fact build up over time to end up as a mountain of wasted time.</p><p>In real life a micro chore is something like cutting your apple before you eat it. It makes it easier to eat and saves you a mess but that requires you to spend some time to de-core and slice the apple. However, it would be faster with one of these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*5iwngboaVs5ymWVKHHgs9A.png" /><figcaption>Using a specialized tool to slice an apple</figcaption></figure><p>You’ve just solved a micro chore. You can now slice apples many times faster and all it took was a specialized tool.</p><p>In general that’s what we humans do when we need to automate or improve some tedious process — we create specialized tools. That’s the same approach we use in programming. In programming micro chores are things like <strong>preparing a query or test data</strong>, <strong>refactoring parts of the code</strong>, <strong>navigating a project structure</strong>, etc. Lots of small things that build up with time. In the next few paragraphs I’m going to show you how to considerably increase the speed at which you perform these tasks.</p><h3>Boosting your coding speed by eliminating micro chores</h3><p>An important asset for increasing coding speed are <strong>shortcuts</strong>. Don’t be intimidated by the sheer amount of shortcuts you have at your disposal though. The way to learn those is slow and steady as you incorporate them in your daily coding little by little.</p><p>A very cool thing about them is that they are usually grouped by operation. For an example when you add/remove the modifier keys Ctrl and Shift to a combination something changes on a different dimension. Use Home and most editors will send you to the beginning of the current line. Combine that with Ctrl to get Ctrl+Home and you’re getting to the beginning of the file. Combine that with a Shift to get Ctrl+Shift+Home and you will not only go to the beginning of the file but you will also select everything between the current position of the cursor and the beginning. Pretty neat, huh?</p><p>For the example parts of the article I will be using IntelliJ as an example, but don’t let that discourage you! Most of the techniques below are perfectly capable with just about any modern browser. As long as it’s regularly updated with new features and has widespread support, you can probably find your IDEs equivalent with a simple Google search.</p><h3>Navigation</h3><p>This is probably the most commonly done micro chore we do as programmers daily. The thing that all of us do most when writing code in a project is navigate it. I often catch people using the mouse when navigating through an editor and that’s perfectly fine but most of the time there’s a shortcut that will save you the trip to the mouse and will often be much more effective. IntelliJ has a convenient menu item called Navigation that houses all those neat navigations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*LISaj4sKxRC4x3i44a52Nw.png" /><figcaption>Navigation menu in IntelliJ</figcaption></figure><p>That’s just another way to use your mouse though. Most of the actions there have shortcuts assigned by default. I’m going to go over the navigations that I most often use during the day and share the shortcuts that I use them through. Navigation can be separated in a few categories depending on the context. Here’s what we have going from more global to more localized contexts:</p><ul><li>Project navigation — the context is the whole project opened in the editor</li><li>Intra-file navigation — the context is the currently opened file</li><li>Function/method navigation — the context being the method/function</li><li>Line navigation — the context is the current line. Yes, we can actually go this low (and even lower but that’s just nitpicking).</li></ul><h3>Project navigation</h3><p>Navigating your project is something that you do very often. Most applications nowadays have numerous modules/packages and getting through those efficiently is imperative to developing fast. Project navigation is pretty much the same no matter what programming language you’re using. The most important and commonly used actions are the following:</p><h4>Navigate to class/file</h4><p>Going to a class or file is important because when you’re familiar with a project you know where the functionalities you need are and going to that specific class can be a hassle if you don’t use the shortcuts. For an example using the Project View is a pretty inefficient approach. Not only do you have to traverse the folders, you’d also need to know them by heart which is rarely the case. Learning the file names though comes pretty easily, especially if you’re the one that came up with them or if you use them often enough.</p><p>IntelliJ provides several ways to do this. You could <strong>go to class</strong>(Ctrl+N) or <strong>go to file</strong>(Ctrl+Shift+N). The difference being that one file could have more than one class of course and sometimes you can’t exactly remember one or the other. You could also use the <strong>go to symbol</strong>(Ctrl+Alt+Shift+N) but it has the same problem as knowing the full project tree — you have to remember the name of the symbol for it to be useful which is rarely the case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*ttGg_-H0yhib5_dUpMyoYQ.gif" /><figcaption>Go to class with IntelliJ</figcaption></figure><h4>Navigate back/forward</h4><p>Another useful feature is the go back and go forward functionality that IntelliJ provides. It’s pretty much the same as what you have in browsers that enable you to go back and forth between pages. I’ve used this in VScode as well and almost every editor I’ve tried. You use Ctrl+Alt+Left Arrow and Ctrl+Alt+Right Arrow to use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*9571Nf9Igh93I6lqcsl6kg.gif" /><figcaption>Navigate back/forward with IntelliJ</figcaption></figure><h4>Navigate to declaration/implementation/type…</h4><p>Navigating to the building blocks of your language is a great feature that the more specialized editors provide. IntelliJ is pretty great in that respect as it allows many such navigations. The most common denominator of these is that the “easy” shortcut is always hover with the mouse and hold Ctrl and left click. That usually does the trick to get you to declaration, implementations are a bit trickier of course. Personally I’ve learned the following:</p><ul><li>Go to declaration — I use that pretty often to go to a class field and look at the context or change something in/around it. If it’s a method/class I’m targeting I can also check the context and what the API has to offer. Ctrl+B should be the default for IntelliJ.</li><li>Go to implementation — this one’s really useful when you need to check out the inner workings of some class/method while reading code. Invaluable when reading more abstract code as the navigation to the declaration wouldn’t do you much good if you want to see implementation specifics, which is almost always the case when you’re going over some flow. Ctrl+Alt+B should be the default for IntelliJ.</li><li>Go to type declaration — this one’s a bit more peculiar than the others but it’s been such a great help over the years that I had to include it here. It allows you to go to the type of the variable that you’re currently hovering. Ctrl+Shift+B should be the default for IntelliJ.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*YnGzwW9JYRMeQupgg_pYcw.gif" /><figcaption>Go to type definition in IntelliJ</figcaption></figure><h3>Intra-file navigation</h3><p>Navigation inside the files is another thing that we do a lot every day. Efficient file navigation makes sure you spend less time moving around and more time thinking or writing code. There are a few key positions that I’ve noticed that I often navigate to.</p><h4>Previous/Next method</h4><p>This one’s really good when you need to go up to maybe change a parameter. Note that using this for checking out the signature is a bit wasteful, you’d be better off using Alt+Q which “peeks” at the method signature</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*5bh4APVg6XxBH1JZ6yt1UQ.gif" /><figcaption>Go to Prev/Next method in IntelliJ</figcaption></figure><h4>Next error/warning</h4><p>Another very useful feature I use daily is going to the next error/warning in a file. When I change something and take a look at the breadcrumb on the side and notice an unforeseen error from my change I want to go directly to it so that I can see it in context. Now you could just scroll there or click the breadcrumb but that would require you to switch from keyboard to mouse again and spend some time searching. IntelliJ has this hotkey on F2 by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*CphnQKu7PDiGIGhBd5ko4A.gif" /><figcaption>Go to next error in IntelliJ</figcaption></figure><h4>Go to the beginning/end of file</h4><p>I sometimes need to do this when I need to look at the class/file comment for an example or if I need to reposition and walk over the methods from top to bottom or the other way around. Usually good practices would have your code be sorted in a particular way — public first, private last or something similar depending on the type of your project and your language of use. Going to one of the extremes would let you to quickly and efficiently walk over the code scanning for inconsistencies or some spot in the code that you know by general position.</p><p>The shortcut for this has been the same on pretty much every editor I’ve tried sans the really odd ones and it’s always been Ctrl+Home/Ctrl+End respectively for beginning/end of the file.</p><h3>Function/method navigation</h3><p>Function navigation can also be broken down into some smaller chunks. You can of course use the above file-oriented navigations to navigate throughout the method but there are some more localized ones that would help you cruise through the method as if it’s its own isolated block of code.</p><h4>Opening/Closing curly brace</h4><p>I often use this to traverse the beginning and ends of code blocks like methods, classes, static blocks, etc. It’s most useful to me for function navigation as it allows me to easily scan the beginning and the end of the method for specific markers like parameter count and names, although a “peek declaration” operation would be better suited for that purpose. “Move Caret to Code Block Start/End” is the name in IntelliJ and is usually set to Ctrl + [ and Ctrl + ] for open and closing curly brace respectively</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*2jHv-mxEJL3ATr4JXgUdwA.gif" /><figcaption>Go to curly brace in IntelliJ</figcaption></figure><h4>Opening/Closing bracket</h4><p>I do this often when I have some pretty big multi-lined and multi-bracketed statements. Those are pretty rare and are a code smell but it happens. Also I guess lisp programmers would like that one. I’ve had to manually set my shortcut for this in IntelliJ so just look up “Move Caret to Matching Brace”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*e4MSmljeYjbaQd3Me8t1Cw.gif" /><figcaption>Go to bracket in IntelliJ</figcaption></figure><h4>Peeking</h4><p>This one is more of an annotation functionality but it still lets you pseudo-navigate to the beginning of the method/function. Using this would allow you to peek at the definition/comment of a particular object. The most useful ones I’ve used are the <strong>Context Info</strong>(Alt+Q in IntelliJ) and the <strong>Quick documentation</strong>(Ctrl+Q in IntelliJ) annotations. I most commonly use the context info to check the current method’s signature and above. If you press more than once you get one level above, for an example — current method signature comes first and then the enclosing object and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OXlbtFsYTs98MSNkDIpHig.gif" /><figcaption>Context info in IntelliJ</figcaption></figure><p>The quick documentation one is useful when you don’t want to open a type and pore through the documentation manually. It will open a floating popup that won’t interrupt your flow or make you have to close your current file in order to read it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*cuDHv13Wx4ZkueEpnCewwQ.gif" /><figcaption>Quick documentation in IntelliJ</figcaption></figure><h3>Line navigation</h3><p>Line navigation is a pretty low grained task but it is surprisingly multifaceted. You have a bunch of things you can traverse inside a line: characters, words, symbols, etc. The most commonly used shortcuts when navigating a line are combination of the arrow keys with some modulating keys like Ctrl and Shift. Here’s the ones I think are the most useful:</p><h4>Jumping over words</h4><p>This enables you to skip a word when traversing a line. The words are usually different symbols in the code — variables, classes, types, etc. This allows for a speedy navigation to a specific point in the line instead of having to use the mouse. It’s important to note that sometimes the line is so irregularly typed that you might as well use your mouse. Most times though the keyboard combined with the Ctrl modifier allows better or similar performance. Jumping over words for an example is done with Ctrl+Left/Right</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*_uYM9COzKXsZVtMr0r3pHg.gif" /><figcaption>Jumping over words in IntelliJ</figcaption></figure><p>Note: combining this with a Shift and turning it into Ctrl+Shift+Left/Right will result in the skipped over character to become selected as well (just like they would if you didn’t hold the Ctrl at all, but batched by word).</p><h4>Going to beginning/end of line</h4><p>The beginning and the end of a line are important markers in most languages. That’s where names, semicolons, brackets and other important building blocks reside. Getting there fast is always helpful. If you remember the Ctrl+Home/End combination from the section on file navigation you wouldn’t be surprised that if you exclude the modifier Ctrl key you’d go to the beginning/end of the current line.</p><h3>Carets</h3><p>A simple but incredibly powerful feature of pretty much every modern editor are <strong>carets </strong>or also called<strong> multiple cursors</strong>. They enable you to have multiple cursors(duh) active at once therefore modifying a few lines at once. Really efficient for data modification. The best part about it? You can use most of the above tips I explained about line navigation and do them for multiple lines at the same time. This results in a powerful tool for data modification as you can see in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*_tfLz6w8XQc6ZMZzIy_PsQ.gif" /><figcaption>Carets example in Sublime Text 3</figcaption></figure><p>I’m using sublime here just to showcase how even with a simple IDE you can have a whole bunch of powerful plugins and functionalities like the “Increment selection” plugin and the prepackaged lower case commands that exist in pretty much every modern browser.</p><h3>Regex and multi selections using it</h3><p>Many modern IDEs give you the ability to find and select multiple found matches that generates the carets I showed you above. That helps when your data is not neatly ordered one per line with every piece starting at the start of the line. You can use the find functionality for those cases. And the best way to do it is to combine it with Regex as well as it’s incredibly powerful for finding similar blocks of text. Check out the below example to see how much easier using regex was.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*_KzgB72kbS0ptpN2ZX3oAQ.gif" /><figcaption>Regex search and extract example in Sublime Text 3</figcaption></figure><p>In this example I extracted all the JSON fields that have a “name” inside of them. For that purpose I used the +”\w*?name\w*?” regex string. It found all fields that contain “name” in their key. I then used the Alt+Enter combination in Sublime to select all results in the search and then the Shift+End combination to move the currently selected carets to the end of their line which resulted in me getting a whole selected line. Then I moved the selected data to a new tab for better viewing which enables you to analyze the specified names.</p><p>I could have used some overly complex combination of the other techniques I showed you but it’s much simpler with regex once you learn the most basic of its syntax. The above might look like an overwhelming string of gibberish but it’s really not as hard as it looks. I’m not going to go into the specifics, you can check out any number of great regex guides out there to show you the ropes but I just wanted to show you one application here. Another good application is validations and data modification with the Find and Replace function so there’s a lot of overlap with the usual developer tasks.</p><h3>Complex chores</h3><p>The complex chores are probably what you expected to see most in this article, which is why I’d rather keep this part more theoretical, than show you examples that you’ve probably already seen. Complex tasks include the introduction of things like build scripts, data transformation/manipulation scripts and test environment setup scripts. Yep, all those things you avoid creating for your local environment. Another motivation of this part of the article is to give you a reason to want to create those scripts you’ve been putting off.</p><h4>Why should I write build/env setup automation scripts?</h4><p>I prefer moving most of the build sequences I do locally to scripts for several important reasons.</p><h4>Automation</h4><p>The main reason. It just saves so much time. Having to run the builds manually, then deploying them on your local server, maybe busting a few caches, whoops you forgot the in-memory database config, gotta go back and start over. You probably get where I’m going and some of you’ve probably been there before and have hopefully rectified their mistakes. Automating the boring, menial tasks is something that every developer should be able to do effortlessly. It’s what keeps our jobs from becoming too mundane and making us burn ourselves out.</p><h4>Documentation</h4><p>If a picture’s worth a thousand words, then an environment setup script is worth a few pages of documentation.</p><p>There’s this concept called “self-documenting code”. It’s a really great idea that basically states that if your code is written simple enough, you wouldn’t need to document most of it but only the important or necessarily quirky(e.g. external dependency constraints) parts of it. A build/environment setup script doesn’t just automate your job but it also serves as a documentation on what building parts you need for the application to run. Avoiding all the hassle to sometimes re-learn what it was required for a project to run locally is a great side effect from having those scripts.</p><p>We all know all the different environments (integration/stage/prod…etc) are almost always very different than our local ones. Whether it’s resources, mocking or timing constraints it’s just not efficient to run a project locally the same way you’d run it on other environments. Because of this though the scripts on the agents are different than what the ones on our local machines have to look like and that’s why a lot of people just don’t do it. They set them up once and forget them resulting in a huge hassle to relearn everything when they have to change something or something just breaks out of nowhere. All those flying environment variables and compile arguments spread around tons of files and configurations. A thoroughly unpleasant task that could be saved by spending an hour or two extra setting stuff up.</p><h4>Transferability</h4><p>Being able to share your script with a colleague will more than double the time saved to set up a new project locally. Sharing with another one would increase that even further. With the added bonuses I mentioned above comes the easier to understand steps that can save you some onboarding time for new people.</p><h4>Language choice considerations</h4><p>I don’t want to go and explore a bunch of language specifics and introduce pointless noise so here’s some things to consider when choosing your language.</p><p>The scripting language for your scripts greatly depends on what you’re trying to achieve and the project you’re dealing with. If the build steps include a lot of OS specific stuff like file movement and maybe some environment variables set up then you’d probably be better off using what’s best suited for your OS. The shells are usually a great choice as an all around solution. zsh, bash, just sh or something a bit more exotic like fish, depending on your system, needs and preferences, are often a great and minimal way to set up an environment.</p><figure><a href="https://www.gnu.org/software/bash/"><img alt="" src="https://cdn-images-1.medium.com/max/447/1*Ls63n-ZBQzXC_567Rgp8pQ.png" /></a></figure><figure><a href="https://fishshell.com/"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*uRF2TCzZ1KsCcpgQR4Wk4Q.png" /></a></figure><figure><a href="https://www.zsh.org/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJIpEFJ2DT3rg9wqjEi3wg.png" /></a><figcaption>Some famous shells, from left to right — bash, fish, zsh</figcaption></figure><p>If you’d rather do more complex tasks you might want to choose a different language that is easier to write than the shell ones. The syntax there is clunky and not at all user friendly so something like python would make your life considerably easier when writing more logic intensive scripts.</p><figure><a href="https://www.python.org/"><img alt="" src="https://cdn-images-1.medium.com/max/601/1*wigcg2cOMdiqq3y2Qrgk2w.png" /></a><figcaption>Python is great at more application logic intensive scripts and has a friendly syntax</figcaption></figure><h4>Aliases</h4><p>Build scripts usually include build tools and their respective configurations like for an example java most of the time makes use of Gradle or Maven. Sometimes Ant makes an appearance. They also have a lot of file movement but that’s mostly wrapped by the build tools. If you want to setup a project locally chances are you already have it chosen for you. There’s a trick to improving your experience with them though and that is through using aliases.</p><p>Aliases are a great way to add an extra layer of automation to some short commands that you do often during development. Using the build scripts and the tools as an example — sometimes you want to run the build tool with different inputs depending on the type of build you want to achieve. If you’re going for speed and want a running project ASAP you’d want to skip all documentation generation, tests, test compilation, etc. Anything that is not important to get the project running. If you’re pushing to the remote though you probably want most of those skipped tasks to be enabled. Aliases are a shell concept that allow you to turn a command like ./gradlew clean build -x test into something like gradle-no-tests.</p><h4>Conclusion</h4><p>I’ll be stopping here as we could go for hundreds of pages describing efficient practices and we’d still have not covered even a fraction of what we’ve learned as developers over the short span that our profession has existed. I hope this article serves as a different perspective and makes you consider some of the stuff on the smaller spectrum that you’ve never considered could be done better. Or that it sparked you into action and finally writing that one script you’ve been putting off forever.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe76c0c3152b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paysafe-bulgaria/efficient-development-avoiding-the-chores-of-programming-fe76c0c3152b">Efficient development — Avoiding the chores of programming</a> was originally published in <a href="https://medium.com/paysafe-bulgaria">paysafe-bulgaria</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Microservice Resilience with Resilience4J]]></title>
            <link>https://medium.com/paysafe-bulgaria/improving-microservice-resilience-with-resilience4j-ceda379505ff?source=rss----db09e34211aa---4</link>
            <guid isPermaLink="false">https://medium.com/p/ceda379505ff</guid>
            <dc:creator><![CDATA[Penyo Atanasov]]></dc:creator>
            <pubDate>Fri, 15 Jul 2022 09:50:46 GMT</pubDate>
            <atom:updated>2022-07-15T09:50:46.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBBrX_qJoinqCjoQCsKNYw.jpeg" /><figcaption>Taken from <a href="https://pixabay.com/illustrations/network-steering-computer-science-4430786/">https://pixabay.com/illustrations/network-steering-computer-science-4430786/</a></figcaption></figure><blockquote>“A list is only as strong as its weakest link.” — Donald Knuth</blockquote><h3><strong>Some terminology</strong></h3><p>A variety of definitions of the terms used here have been circulating around, so before we begin I would like to define some of them more formally for the sake of this writing.</p><p><strong><em>microservice</em></strong><em> — an independent service managed by an individual or a group. It may differ between organizations, their team sizes, business processes etc. It is also referred to as </em><strong><em>service</em></strong><em>.</em></p><p><strong><em>microservice architecture — </em></strong><em>a collection of micro-services that structures an application. Sometimes this is also referred to as </em><strong><em>microservices</em></strong><em>.</em></p><p><strong><em>upstream service — </em></strong><em>the microservice we are receiving requests from.</em></p><p><strong><em>downstream service — </em></strong><em>the microservice we are making requests to.</em></p><p><strong><em>SLA</em></strong><em> — service level agreement. This is the agreement between service and client about measurable metrics e.g. availability, throughput, response time etc.</em></p><h3><strong>The problem</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPzaxAebqUUrajXZ6TSkxw.png" /></figure><p>Imagine you have hundreds of teams, developing and maintaining hundreds of microservices. Imagine also that the system is handling thousands of requests per second and has strong SLAs. This forms a huge service call graph and a lot of performance and failure implications which have to be thought about in advance.</p><h3><strong>What is microservice resilience ?</strong></h3><p>Resilience means “the capacity to recover quickly from difficulties”. A resilient microservice should be able to self-heal and recover after some reasonable time and this implies recovering from both software and hardware failures.</p><p>In order to have resilience some prerequisites have to be met. First of all we need well defined <strong>SLAs</strong>. These define the contract on a variety of metrics and agreements between the parties in the system. Next we need to have all the <strong>use cases</strong> in our microservice. We should be able to quickly identify and document the possible <strong>failure points</strong> which is difficult without the use cases. And last but not least we must have <strong>observability</strong>. This includes health and deep checks, application metrics, logging, dashboards etc. Not only would this help us identify eventual failures but would give us a view on how to improve the system.</p><blockquote>“You can’t improve what you don’t measure.” — Jacob Drucker</blockquote><p>Therefore to have a resilient microservice it must be observable, self-healing and fault tolerant in the microservice environment it lives. The latter is what we will dive into until the end of this writing.</p><h3>Fault tolerance patterns and Resilence4j</h3><p>Fault tolerance is the ability of a system to continue functioning in the event of a failure although the overall performance may suffer. There are a number of well known fault tolerance patterns we will dive into and describe here.</p><blockquote><strong>“Resilience4j</strong> is a lightweight, easy-to-use fault tolerance library inspired by Netflix Hystrix, but designed for Java 8 and functional programming… <br>It provides higher-order functions (decorators) to enhance any functional interface, lambda expression or method reference…<br>You can stack more than one decorator on any functional interface, lambda expression or method reference…<br>With Resilience4j you don’t have to go all-in, you can pick what you need.”<br> — <a href="https://resilience4j.readme.io/docs">https://resilience4j.readme.io/docs</a></blockquote><p>Most of the modules in Resilience4j have blocking and non-blocking APIs and have common configuration to ignore or accept specific exceptions and decide on a failure.</p><p><strong>Retry</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*49dLsiGpERLXJ_UfcuMHYg.png" /></figure><p>As its name suggests the Retry pattern refers to retrying the logic on designated operations. A typical example is a request being retried until successful. However there are some pitfalls. A larger amount of retries can make things even worse or even prevent the service or the downstream service from recovering. A request retry in a distributed system can trigger multiple other requests or retries and start a cascading effect in other applications.</p><blockquote>Imagine receiving a request from an upstream service which triggers 20 requests in our downstream services, then retrying 1 request a 1000 times would trigger 20000 requests in the downstream services.</blockquote><p>Although retrying looks like an easy approach it usually has to be implemented using a carefully chosen backoff strategy. A common approach is to use an exponentially increasing wait time up until a maximum retry count has been reached.</p><p><strong><em>Resilience4J — Retry</em></strong></p><pre>RetryConfig config = RetryConfig.<em>custom</em>()<br>    .failAfterMaxAttempts(true)<br>    .waitDuration(Duration.<em>ofSeconds</em>(1))<br>    .intervalFunction(integer -&gt; 2L * integer)<br>    .maxAttempts(3)<br>    .build();</pre><pre>Retry retry = RetryRegistry.<em>of</em>(config).retry(&quot;downstream:/api/foo&quot;);</pre><pre>retry.executeRunnable(() -&gt; {<br>  // retry logic here<br>});</pre><p>In this example we have defined a retry logic with 3 attempts doubling the wait duration after each failure starting with a wait duration of 1 second.</p><blockquote>For more configuration properties of the Retry see: <a href="https://resilience4j.readme.io/docs/retry">https://resilience4j.readme.io/docs/retry</a></blockquote><p><strong>Timeout</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*EnxR8UekzuViMXaOVqgVYA.png" /></figure><p>A timeout is another commonly used pattern and it is already supported by most clients (tcp, http, database etc). Although it seems trivial there are a number of decisions to be made when configuring timeout. First of all we want our timeouts to be high enough to allow slower requests to succeed but low enough to stop waiting for a request that is never going to succeed. Secondly we should avoid unbounded waiting times for responses and thus treating every request as failed when no response was received within the timeout. And last but not least we need to have a fallback mechanism for when the request timed out in the client but was successful on the server.</p><p><strong><em>Resilience4j — Timelimiter</em></strong></p><p>The module of Resilience4j that deals with timeouts is called Timelimiter. The only configuration is has is the timeout duration.</p><pre>TimeLimiterConfig config = TimeLimiterConfig.<em>custom</em>()<br>    .timeoutDuration(Duration.<em>ofSeconds</em>(1))<br>    .build();<br><br>TimeLimiter timeLimiter = TimeLimiterRegistry.<em>of</em>(config)<br>    .timeLimiter(&quot;slow-response-timeouts&quot;);<br><br>timeLimiter.executeFutureSupplier(<br>    () -&gt; CompletableFuture.<em>supplyAsync</em>(() -&gt; &quot;Hello world!&quot;));</pre><blockquote>More about Timelimiter here: <a href="https://resilience4j.readme.io/docs/retry">https://resilience4j.readme.io/docs/retry</a></blockquote><p><strong>Rate Limiter</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9z-4KYy5I3KgS9txYbn0w.png" /></figure><p>Rate Limiter helps us protect the server from over loading by limiting the number of calls we could make/process in a specific window. It could also protect our downstream services from overloading with requests. In case we limit the number of requests in our service we later need to do either of the following:</p><ul><li>retry at a later time the “limited” requests</li><li>go with some default/cached values for the responses</li><li>just throw away requests and do not return successful responses</li></ul><p>Very often rate limiters are used to flatten the curve and smooth out bursts of request during traffic peaks.</p><blockquote>Imagine there is a service responsible for fetching 100 stock prices which talks to a 3rd party service. Stock prices are updated once in every 5 seconds and we get 100 req/s per stock price. Should we really make those calls to the 3rd party service?</blockquote><p><strong><em>Resilience4j — Ratelimiter</em></strong></p><p>The ratelimiter module of Resilience4j is highly configurable and at the same time — easy to use.</p><pre>RateLimiterConfig config = RateLimiterConfig.<em>custom</em>()<br>    .timeoutDuration(Duration.<em>ofMillis</em>(5L))<br>    .limitRefreshPeriod(Duration.<em>ofSeconds</em>(1))<br>    .limitForPeriod(200)<br>    .build();<br><br>RateLimiter rateLimiter = RateLimiterRegistry.<em>of</em>(config)<br>    .rateLimiter(&quot;peak-traffic-limiter&quot;);<br><br>rateLimiter.executeCallable(() -&gt; &quot;Hello world!&quot;);</pre><p>The configuration properties in the above example are:</p><ul><li>timeout duration — the default wait for permission duration after which the execution fails.</li><li>limit for period — the number of executions representing the actual rate of the rate limiter.</li><li>limit refresh period — represents a period when the rate limiter sets its permissions count to limitForPeriod value.</li></ul><p>In the example above we have a rate limiter configuration with a maximum of 200 operations per second waiting 5 milliseconds until one fails.</p><blockquote>For more information see: <a href="https://resilience4j.readme.io/docs/ratelimiter">https://resilience4j.readme.io/docs/ratelimiter</a></blockquote><p><strong>Circuit Breaker</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*65_VntFitMebXCrwr5jiqA.png" /></figure><p>As the name suggests it acts just as an electrical circuit breaker. When the number of consecutive failures crosses a threshold, the circuit breaker opens, and for the duration of a timeout period all attempts to invoke the remote service will fail immediately.</p><blockquote>“In electronics, a circuit breaker is a switch that protects your components from damage through overload. In software, a circuit breaker protects your services from being spammed while already being partly unavailable due to high load.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*tUc5TKudCAWmLV7j4FhnPA.png" /></figure><p>An interesting property of the circuit breaker is that it has three states — Closed, Open, Half-open.</p><ul><li>Closed — requests can flow freely</li><li>Open — requests are rejected without being submitted to the remote resource</li><li>Half-open — one probe request is allowed to decide whether to close the circuit again</li></ul><p><strong><em>Resilience4j — Circuitbreaker</em></strong></p><p>There could be much more configurations, so we will not go into too much details.</p><pre>CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig<br>    .custom()<br>    .slidingWindowType(<em>COUNT_BASED</em>)<br>    .slidingWindowSize(10)<br>    .failureRateThreshold(75.0f)<br>    .waitDurationInOpenState(Duration.<em>ofSeconds</em>(3))<br>    .permittedNumberOfCallsInHalfOpenState(2)<br>    .build();<br><br>CircuitBreaker circuitBreaker = CircuitBreaker.<em>of</em>(<br>    &quot;too-many-failures-breaker&quot;, <br>    circuitBreakerConfig<br>);</pre><pre>circuitBreaker.transitionToClosedState();<br><br>circuitBreaker.decorateSupplier(() -&gt; &quot;Hello world!&quot;).get();</pre><p>The configuration above defines a count based circuit breaker (as opposed to a time based one) with a sliding window of 10 requests and a failure rate threshold of 75%. The circuit breaker will open if 75% of the requests start to fail of the sliding window of 10 requests — 8 failures in this case. If we used a TIME_BASED window size then the sliding window is in seconds.</p><blockquote>For more information see: <a href="https://resilience4j.readme.io/docs/circuitbreaker">https://resilience4j.readme.io/docs/circuitbreaker</a></blockquote><p><strong>Rate Limiter VS Circuit Breaker</strong></p><p>Although these two look very similar they are semantically different.</p><ul><li>A Rate Limiter prevents ourselves from overloading by controlling throughput.</li><li>A Circuit Breaker prevents the downstream service from overloading in case it starts failing or becomes unresponsive.</li></ul><p><strong>Bulkhead</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*Tu4emqGQXC_ycw4zyP125w.png" /></figure><p>The bulkhead pattern helps us avoid faults in one part of the system to take the entire system down. The name comes from ships where a bulkhead is a wall within the hull of a ship which prevents the entire ship from sinking if that partition is flooded.</p><blockquote>The name comes from ships where a bulkhead is a wall within the hull of a ship which prevents the entire ship from sinking if that partition is flooded. Failure in one service or a group of services should not bring down the whole application.</blockquote><p>The bulkhead pattern helps us allocate limit on the resources which can be used for specific services so that resource exhaustion can be reduced. For example it could be used to separate downstream service calls, database calls etc. in which case if one downstream service fails that would not affect our service from calling the others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjGt2KbcBNJ1HCDAmbgm3w.png" /></figure><p><strong><em>Resilience4j — Bulkhead</em></strong></p><p>The bulkhead implementation in Resilience4j supports a semaphore and a thread pool based bulkhead.</p><p><em>Semaphore based</em></p><pre>BulkheadConfig config = BulkheadConfig.<em>custom</em>()<br>    .fairCallHandlingStrategyEnabled(true)<br>    .maxConcurrentCalls(10)<br>    .maxWaitDuration(Duration.<em>ofMillis</em>(100L))<br>    .build();<br><br>Bulkhead bulkhead = BulkheadRegistry.<em>ofDefaults</em>().bulkhead(&quot;semaphore-based&quot;, config);<br><br>bulkhead.executeCallable(() -&gt; &quot;Hello world!&quot;);</pre><ul><li>maxConcurrentCalls — amount of parallel executions allowed by the bulkhead.</li><li>maxWaitDuration — amount of time a thread should be blocked for when attempting to enter a saturated bulkhead.</li></ul><p><em>ThreadPool based</em></p><pre>ThreadPoolBulkheadConfig config = ThreadPoolBulkheadConfig.<em>custom</em>()<br>    .maxThreadPoolSize(10)<br>    .coreThreadPoolSize(5)<br>    .queueCapacity(100)<br>    .keepAliveDuration(Duration.<em>ofSeconds</em>(1))<br>    .build();<br><br>ThreadPoolBulkhead bulkhead = ThreadPoolBulkheadRegistry.<em>of</em>(config).bulkhead(&quot;thread-based&quot;);<br><br>bulkhead.executeCallable(() -&gt; &quot;Hello world!&quot;);</pre><ul><li>maxThreadPoolSize , coreThreadPoolSize, queueCapacity — these are pretty self explanatory and define the properties of the underlying thread pool.</li><li>keepAliveDuration — maximum time that excess idle threads will wait for new tasks before terminating.</li></ul><p>Maintaining a number of bulkheads gives us the opportunity to divide executions.</p><blockquote>For more see: <a href="https://resilience4j.readme.io/docs/bulkhead">https://resilience4j.readme.io/docs/bulkhead</a></blockquote><p><strong>Cache</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*FZOwhxyR_quFZANF0pIasA.png" /></figure><p>Caching is another fault tolerance pattern which is widely used. It’s a huge topic and is here for the sake of completeness. The idea is to save the data that comes from remote services to a local or remote cache and reuse the cached data as a response during downstream service failure.</p><p>We’ll briefly summarise that there are lot of decisions to be made when designing a cache:</p><ul><li>type of cache (in-memory, local storage, distributed etc.) — the choice depends on the use case and cache size wanted.</li><li>caching strategies — write-through and cache-aside.</li><li>write policies — pre-caching or on-demand caching.</li><li>replacement strategies — usually based on a predefined cache size although sometimes caches could be unlimited.</li><li>cache invalidation strategy — based on time or freshness or activity.</li></ul><blockquote>“There are only two hard things in Computer Science: cache invalidation and naming things.” — Phil Karlton</blockquote><p><strong><em>Resilience4j — Cache</em></strong></p><p>It uses the Java Temporary Caching API which supports a variety of caches — Ehcache, Caffeine, Redisson, Hazelcast, Ignite.</p><pre>CacheManager cacheManager = Caching.<em>getCachingProvider</em>().getCacheManager();<br><br>Cache&lt;String, String&gt; cache = Cache.<em>of</em>(cacheManager.createCache(&quot;my-cache&quot;, new MutableConfiguration&lt;&gt;()));<br><br>Cache.<em>decorateSupplier</em>(cache, () -&gt; &quot;Hello world!&quot;).apply(&quot;hello-key&quot;);</pre><blockquote>For more details see: <a href="https://resilience4j.readme.io/docs/cache">https://resilience4j.readme.io/docs/cache</a> and <a href="https://jcp.org/aboutJava/communityprocess/implementations/jsr107/index.html">https://jcp.org/aboutJava/communityprocess/implementations/jsr107/index.html</a></blockquote><p><strong>Asynchronous Processing</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*cypP7iG7ND6q_sfn5yNnGw.png" /></figure><p>When we talk about fault tolerance we should also mention the asynchronous processing. Again, this is huge and is here for entirety. The idea is that any message can be sent independently of the availability of the receiver meaning that the messages will get delivered as soon as the service becomes available. Therefore this also provides natural redelivery and retry mechanisms. Just like a rate limiter it helps smooth out traffic bursts and the downstream service cloud process the messages an approximately average rate. However it could be quite difficult to implement if we want to mimic an HTTP call. HTTP uses a request-response paradigm which makes it duplex. When using queues we have to consider an inbound and an outbound queue in case we need the responses. If we have multiple APIs in a service, this could easily lead to unbearable complexity.</p><p>Implementing asynchronous processing can be achieved using:</p><ul><li>Client/Server in-memory queues</li><li>Distributed messaging brokers e.g. RabbitMQ, Kafka etc.</li></ul><p>In its nature Resilience4j is asynchronous and provides in-memory queueing mechanisms in most of its modules. A more robust approach however would be to use an external distributed messaging broker.</p><h3><strong>Some key points</strong></h3><ul><li>If a service SLA is 100rps and is now degraded to 50rps it won’t do 100rps no matter how hard we brute force it, so if we have an ill service let if self-heal.</li><li>A degradation in one service could cause partial failures in other services which could cascade to a full system failure.</li><li>Setting up a distributed system for fault tolerance is not a trivial task and consists of the following steps:<br>- Define service SLAs<br>- Tweak microservice calls with fault tolerance in mind<br>- Observe the system<br>- Go back to redefining the SLAs</li></ul><blockquote>References:<a href="https://www.infoq.com/presentations/uber-microservices-distributed-tracing/"><br>https://resilience4j.readme.io/docs<br>https://www.infoq.com/presentations/uber-microservices-distributed-tracing/</a><br><a href="https://liashenko.github.io/fault-tolerance">https://liashenko.github.io/fault-tolerance</a><br><a href="https://oribi.io/tech-blog/handle-failures-in-complex-microservices-architecture">https://oribi.io/tech-blog/handle-failures-in-complex-microservices-architecture</a><br><a href="https://www.vinsguru.com/rate-limiter-pattern/">https://www.vinsguru.com/rate-limiter-pattern/#:~:text=Rate%20Limiter%20Pattern%20helps%20us,might%20simply%20reject%20the%20call</a><br><a href="https://eximia.co/caching-basics-why-when-what-where-writing-replacement-and-invalidation-strategies/">https://eximia.co/caching-basics-why-when-what-where-writing-replacement-and-invalidation-strategies/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceda379505ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paysafe-bulgaria/improving-microservice-resilience-with-resilience4j-ceda379505ff">Improving Microservice Resilience with Resilience4J</a> was originally published in <a href="https://medium.com/paysafe-bulgaria">paysafe-bulgaria</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Tips for cleaner code]]></title>
            <link>https://medium.com/paysafe-bulgaria/5-tips-for-cleaner-code-9f35992b7502?source=rss----db09e34211aa---4</link>
            <guid isPermaLink="false">https://medium.com/p/9f35992b7502</guid>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Radoslav Radenkov]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 15:53:53 GMT</pubDate>
            <atom:updated>2022-02-17T15:53:53.282Z</atom:updated>
            <content:encoded><![CDATA[<h3>5 Tips for Cleaner Code</h3><figure><img alt="eyeglasses in front of monitor where different tabs with codes are opened" src="https://cdn-images-1.medium.com/max/1024/1*kQbEwU32AR5aV_dXPkIjYw.jpeg" /></figure><p>“It is not enough for code to work.”<br> ― <strong>Robert C. Martin</strong></p><p>The code should be clean, readable, and optimized. Had you ever experienced the feeling of trying to read a code with messy syntaxes, smashed-together huge blocks of codes or just some randomly dropped functions? Yep, we had all been there. When a team is working simultaneously on a code, this is probably an everyday problem. There are some hacks that will literally ease your life by learning how to write a clean code.</p><p>In this post I will share some good practices that I’ve learned in my software engineering career that can make you code “cleaner”.</p><h4>What is clean code?</h4><p>First let’s start with what is clean code. When you hear clean code what is the first thing that comes to your mind? There certainly isn’t one definition what makes code cleaner. Everyone has something in their head, so I’ve asked several people what their definition is. Here is the gist of what I got:</p><p>Easy to understand and change — code is written in such manner that tries not to confuse the reader and there are no hidden gotchas;<br> Simple and direct — like previous one said in different words;<br> Written with care — some say that writing code is a craft. And as any other craft putting care into it gives better results;<br> Efficient — uses proper algorithms in an optimal way;<br> Tested — has sufficient test coverage. Making it safer to change and easier to reason about its intent;<br> Avoids duplication — There isn’t much more to say that duplicated code is bad code and can lead to lots of problems.</p><p>In this post I will focus on the first two, writing code that is easy to understand and change. Even though we write our code to run on computers, it will also be read by humans. Computers understand all code if it compiles. But for humans we need to put a bit more effort. Writing simple and direct code will help others that read it and will help you when have to change something one year from now. And as a bonus you will very likely start to receive more favorable code reviews 😉</p><h4>Naming things</h4><p>Naming is major part of writing code. You need to come up with lots of names. Names for variables, functions, function arguments, classes, directories and on and on. Sometimes there are defined rules which help, for example when naming a micro-service or repository for your company, but often there aren’t, and we are left to our own imagination. Which sometimes fails us. There are only two hard things in Computer Science: cache invalidation and naming things.</p><blockquote>Phil Karlton<br>https://www.karlton.org/2017/12/naming-things-hard/</blockquote><p>So, can we make things easier? Following certain rules is a good start. Each programming language has its own conventions, what should be capitalized, what shouldn’t. Whether to use camelCase, snake_case, kebab-case, or something else. <br> Then there are the rules that come from Object Oriented Programming. Classes are <strong>nouns</strong> because they represent objects, methods are <strong>verbs</strong> since they do things. But with interfaces thing get tricky. There are different conventions for interfaces. Some prefix them with <strong>I</strong><em> </em>— <em>IList</em>, other suggest suffixing them with <strong>-able</strong> or <strong>-ing — </strong><em>Equatable</em>, <em>ProgresReporting</em>. My first suggestion about this is to follow the conventions in the code base you are working on. If you have an option to choose then I will suggest dropping any “I” prefixes or any “Protocol” or “Interface” suffixes and name them as you would name any type. The idea of interfaces is to hide the implementation, so implementing type should come up with a good name.<br> Apart from conventions something that will help a lot is to use names in English with correct spelling. Most programming languages support Unicode characters, with some even allowing you to use emojis for variables and functions. So might look cool and tempting to define log function like this:</p><pre>Log.⚠️(&quot;Warning&quot;)<br>// instead of<br>Log.warning(&quot;Warning&quot;)</pre><p>But in the long run you will see that is not very practical. IDEs auto complete will be harder to use. Searching through you code will also get harder. Modern IDEs have spell checking so just enable it, everyone will be grateful next time when trying to find something code about <em>accounts</em> (and not accounts 😁)</p><blockquote>Tip 1: Get familiar with naming conventions and follow them</blockquote><p>In addition to conventions there are a few other advice I can offer.<br> Don’t encode type information into the name. There were times, names were length constrained and IDEs weren’t providing so much context and things like Hungarian notation were good practices. But now they are not needed. Name like <em>accountList</em> doesn’t give any additional information that you can’t see on first glance. Simply <em>accounts</em> is shorter and gives enough context — a collection of Account. When you need to use it, IDE will show what is its actual type and offer appropriate methods. <br> Don’t rely on comments to explain a name. Try to come up with a better name instead. We will go into that topic in the next section.<br> Take context into consideration. “State” can mean one thing in context of address, state in a country like USA or India, or completely different thing is the context of object state.</p><p>And the most important advice I can give about names is that they should reveal intention. What is this thing intended to be used for or do? Which I know sounds easier that actually is. It takes more time to come up with such names or may require several iterations of renaming something. But start following it and you will see that the result is worth is. Reading the code will start to make more sense.</p><blockquote>Tip 2: Names should reveal intention</blockquote><h4>Comments</h4><p>We have all seen comments like this:</p><pre>// Get primary accounts with non zero balance</pre><pre>accounts.stream()<br>    .filter(account -&gt; account.isPrimary() &amp;&amp; !BigDecimal.<em>ZERO</em>.equals(account.getBalance()))<br>    .collect(Collectors.<em>toList</em>());</pre><p>What information do they give us? Nothing more from what you can learn from reading the code. Some of you might say — when I see such comment, I won’t read the code because it says what it does. But will you trust the comment. For sure I won’t. I’ve seen more than enough examples where code was changed, and comment wasn’t. All it does is to bring more noise and in the worst case can even propagate misinformation and confusion. So, comments can actually make code worse.</p><p>We shouldn’t use comments to explain bad code. If you feel you need a comment, then consider rewriting your code with better names and shorter functions.</p><p>Don’t comment out sections of your code and live them like that. Just delete them. We have version control systems like GIT and SVN if you need to see previous versions. Also be mindful of TODO comments. Not everything can be implemented at once, but also leaving a TODO doesn’t mean you’ve done your job and is some else responsibility to finish it.</p><p>What you should use comments for, is to explain your intent. Why something is written, not what is written. The former is clear from the code.</p><blockquote>Tip 3: Comments shouldn’t explain what the code does, but why it does it</blockquote><h4>Functions</h4><p>We all have been lost in reading 100 lines long function. In the middle you forget what was going on 20 lines above. Or there were so many nested if-else statements, you no longer know which one ends in particular closing brace. Modern IDEs help a lot, they highlight brace pairs and allow collapsing whole statements. But this is not an excuse to write such code.</p><p>The one most important advice you can follow about functions is to keep them small. If you look around the internet, most people will stay that it shouldn’t take you longer than a minute or two to understand what function does. Splitting long functions into shorter ones helps a lot with readability and understandability of your code. And if you’ve heard about deep call stacks and worry about performance penalty, you shouldn’t. If you have such constraints, you will know it :) For the rest of you, just try to keep functions short and in best case do one thing. Or said in <a href="https://simple.wikipedia.org/wiki/SOLID_%28object-oriented_design%29">SOLID</a> terms, have single responsibility. Following this advice will also make naming easier. Because if you function does one thing, coming up with a good name won’t be that hard.</p><p>The second advice I can give about functions is to avoid side effects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/359460e36c89906514d5ca0a0251bec4/href">https://medium.com/media/359460e36c89906514d5ca0a0251bec4/href</a></iframe><p>Side effects are like broken promises. Your function tells that will do one thing, but also does something else. It has a hidden secret. And if you are not careful when reading it, you might not notice it. Or maybe you can add a comment explaining that secret? No, you shouldn’t do that. Comments don’t make up for bad code. Rewrite your functions so they don’t have side effects and do what they promise.</p><blockquote>Tip 4: Keep functions short and without side effects</blockquote><p>My last advice will be a bit more general. It is about helping you code base stay in good shape. You can do this by following not only naming conventions, but also good coding practices and design patterns. I really hope there are such already in your code and if not, you can discuss it with your peers and introduce them. Try to keep things simple and reduce complexity. And lastly, you have probably heard about the boy scout rule. Always leave the code you change in better shape than it was before that.</p><blockquote>Tip 5: Be a good citizen or boy scout ;)</blockquote><p>These were my top 5 tips on how to write clean code that is easy to understand by others and your future you. I hope you agree with some or all of them. Or maybe you already follow them. I will be happy to hear your thoughts in the comments.</p><blockquote>References:<br>Robert C. Martin — Clean Code: A handbook of agile software craftsmanship <br>Swift API design guidelines — <a href="https://www.swift.org/documentation/api-design-guidelines/">https://www.swift.org/documentation/api-design-guidelines/</a><br>Quote: <a href="https://www.goodreads.com/work/quotes/3779106-clean-code-a-handbook-of-agile-software-craftsmanship-robert-c-martin">https://www.goodreads.com/work/quotes/3779106-clean-code-a-handbook-of-agile-software-craftsmanship-robert-c-martin</a><br>Featured Image Credentials: <a href="https://www.pexels.com/@kevin-ku-92347">https://www.pexels.com/@kevin-ku-92347</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f35992b7502" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paysafe-bulgaria/5-tips-for-cleaner-code-9f35992b7502">5 Tips for cleaner code</a> was originally published in <a href="https://medium.com/paysafe-bulgaria">paysafe-bulgaria</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ускоряване на компилацията на проекта чрез използване на Gradle кеш — трета част]]></title>
            <link>https://medium.com/paysafe-bulgaria/%D1%83%D1%81%D0%BA%D0%BE%D1%80%D1%8F%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-%D0%BA%D0%BE%D0%BC%D0%BF%D0%B8%D0%BB%D0%B0%D1%86%D0%B8%D1%8F%D1%82%D0%B0-%D0%BD%D0%B0-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0-%D1%87%D1%80%D0%B5%D0%B7-%D0%B8%D0%B7%D0%BF%D0%BE%D0%BB%D0%B7%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-gradle-%D0%BA%D0%B5%D1%88-%D1%82%D1%80%D0%B5%D1%82%D0%B0-%D1%87%D0%B0%D1%81%D1%82-9698d3b66638?source=rss----db09e34211aa---4</link>
            <guid isPermaLink="false">https://medium.com/p/9698d3b66638</guid>
            <category><![CDATA[продуктивност]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[производителност]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[кеш]]></category>
            <dc:creator><![CDATA[Radoslav Yordanov]]></dc:creator>
            <pubDate>Fri, 04 Jun 2021 13:17:27 GMT</pubDate>
            <atom:updated>2021-06-04T13:17:27.115Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ускоряване на компилацията на проекта чрез използване на Gradle кеш — трета част</h3><p><em>В предишната серия на поредицата разгледахме как кешът влияе върху проекти с повече от един модул. Освен това, показахме как да пуснем локален и отдалечен build кеш. В тази серия ще разгледаме как да конфигурираме правилно Gradle кеша и също така ще разгледаме gradle кеш сървъра.</em></p><p><strong>Конфигурации на Gradle кеш</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*4yIiBgsPz_s5ZXgvOfLJzw.png" /></figure><p>На фигурата е показан препоръчителният начин, по който може да конфигурираме Gradle кеша. При тази конфигурация програмистът може да взима и записва данни в локалния кеш. Също така той може да взима данни и от отдалечения кеш, но там не може да записва данни. Единствено CI сървърът може да записва данни на отдалечения кеш. Така ако имаме програмист, който работи по feature A, когато компилира проекта, данните ще бъдат взети от локалния кеш. След като програмистът пусне Pull Request и го мърджне в develop branch-a, тогава CI сървърът ще компилира проекта и ще запише данните в отдалечения кеш. По-късно, когато някой програмист вземе най-новите промени от develop, при компилиране на проекта, данните ще бъдат взети от отдалечения кеш, спестявайки му време за компилиране на проекта локално.</p><p>За да постигнем този примерен подход трябва да дефинираме environment variable на нашата CI машина. В случая environment variable-а, който сме дефинирали е <em>„CI”</em>. След като сме направили това, трябва да създадем локална променлива — <em>isCiServer</em>, която да проверява дали съществува тази environment variable на машината, от която се изпълнява компилацията. Така, когато компилация върви на CI машината, променливата <em>isCiServer</em> ще бъде <em>true</em>, a когато компилацията върви на машината на някой програмист — ще бъде <em>false</em>. Последното нещо, което остава да направим, е към конфигурацията да добавим свойството <em>push</em> и неговата стойност да бъде <em>isCiServer</em>. Това свойство определя дали можем да записваме данни на отдалечения кеш. Можете да погледнете на кода по-долу как сме постигнали желания ефект:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4D_Gq1P9-tyL08ueqNiM_Q.png" /></figure><p><strong>Gradle кеш сървър</strong></p><p>Досега си говорихме за локален и отдалечен кеш. Обаче за да използваме отдалечен кеш, то ние трябва да имаме първо кеш сървър към който да се свържем. Затова трябва да използваме Gradle кеш сървър. Той ни позволява да се свържем към него използвайки HTTP протокола. Кеш сървърът се дистрибутира като изпълним JAR файл или docker image. Също така има безплатна и платена версия. Безплатната версия има доста ограничения, докато платената версия ни позволява да използваме повече от един node и да ги синхронизираме. Така че, ако имаме два екипа, които работят по един и същ проект, в Канада и България, то ние можем да се възползваме от това да имаме два node-a. По този начин всеки node ще бъде близко до всеки екип и скоростта на сваляне от кеша ще бъде по-добра. Също така платената версия предлага инструменти за анализиране на задачите за кеширане и целия процес на компилиране на проекта.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPxxn3YBZew8-oXeqFYrRA.png" /></figure><p>Кеш сървърът разполага с уеб интерфейс. През него може да конфигурираме големината на кеша, както и големината на единичен запис. Също така може да контролираме и достъпа до него. Може да добавяме потребители и да задаваме какъв достъп да имат — четене и запис или само четене.</p><p><strong>Полезни връзки:</strong><br>Gradle кеш: <br><a href="https://docs.gradle.org/current/userguide/build_cache.html">https://docs.gradle.org/current/userguide/build_cache.html</a></p><p>Gradle build cache node: <br><a href="https://docs.gradle.com/build-cache-node/">https://docs.gradle.com/build-cache-node/</a></p><p>Top Android build issues: <br><a href="https://gradle.com/blog/top-android-build-issues/">https://gradle.com/blog/top-android-build-issues/</a></p><p>Accelerate clean builds with the build cache: <br><a href="https://developer.android.com/studio/build/build-cache">https://developer.android.com/studio/build/build-cache</a></p><blockquote><em>Надявам се с тази поредица от серии да сте добили представа защо ни е необходим Gradle кеш, как да го пуснете и конфигурирате във вашите проекти, какви са ползите от него и как влияе върху проекти с повече от един модул.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9698d3b66638" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paysafe-bulgaria/%D1%83%D1%81%D0%BA%D0%BE%D1%80%D1%8F%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-%D0%BA%D0%BE%D0%BC%D0%BF%D0%B8%D0%BB%D0%B0%D1%86%D0%B8%D1%8F%D1%82%D0%B0-%D0%BD%D0%B0-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0-%D1%87%D1%80%D0%B5%D0%B7-%D0%B8%D0%B7%D0%BF%D0%BE%D0%BB%D0%B7%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-gradle-%D0%BA%D0%B5%D1%88-%D1%82%D1%80%D0%B5%D1%82%D0%B0-%D1%87%D0%B0%D1%81%D1%82-9698d3b66638">Ускоряване на компилацията на проекта чрез използване на Gradle кеш — трета част</a> was originally published in <a href="https://medium.com/paysafe-bulgaria">paysafe-bulgaria</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ускоряване на компилацията на проекта чрез използване на Gradle кеш — втора част]]></title>
            <link>https://medium.com/paysafe-bulgaria/%D1%83%D1%81%D0%BA%D0%BE%D1%80%D1%8F%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-%D0%BA%D0%BE%D0%BC%D0%BF%D0%B8%D0%BB%D0%B0%D1%86%D0%B8%D1%8F%D1%82%D0%B0-%D0%BD%D0%B0-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0-%D1%87%D1%80%D0%B5%D0%B7-%D0%B8%D0%B7%D0%BF%D0%BE%D0%BB%D0%B7%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-gradle-%D0%BA%D0%B5%D1%88-%D0%B2%D1%82%D0%BE%D1%80%D0%B0-%D1%87%D0%B0%D1%81%D1%82-8e508732bce3?source=rss----db09e34211aa---4</link>
            <guid isPermaLink="false">https://medium.com/p/8e508732bce3</guid>
            <category><![CDATA[кеш]]></category>
            <category><![CDATA[продуктивност]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[производителност]]></category>
            <dc:creator><![CDATA[Radoslav Yordanov]]></dc:creator>
            <pubDate>Wed, 12 May 2021 06:50:08 GMT</pubDate>
            <atom:updated>2021-05-12T06:50:08.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ускоряване на компилацията на проекта чрез използване на Gradle кеш — втора част</h3><p><em>В предишната серия на поредицата разгледахме защо е необходимо кодът да се компилира по-бързо, обяснихме какво е Gradle кеш и разгледахме как работи. В тази серия ще разгледаме как кешът влияе върху проекти с повече от един модул. Също така ще покажем как да пуснем локален и отдалечен кеш.</em></p><p><strong>Как кешът влияе върху проекти с повече от един модул?</strong>Keширането е най-ефективно, когато проектът ни се състои от повече от един модул. Проекти с един модул ще имат по-малка полза. Колкото повече модули има един проект, толкова по-добри резултати бихме постигнали.</p><p>Нека да разгледаме следния пример: имаме проект, който се състои от пет модула. В случая имаме промени само в пети модул, като останалите модули не зависят от този модул. При компилиране на проекта, ще компилираме само модул пет и другите модули ще бъдат взети от кеша:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVf0gfnWYEbccFkkkEckTw.png" /><figcaption>Червените задачи ще се изпълнят<br>Зелените задачи няма да се изпълнят и ще бъдат взети от кеша</figcaption></figure><p>Ако пък имахме промени само по тестовете в пети модул, то при компилиране, само тестовете на този модул ще се компилират и всичко останало ще бъде взето от кеша. Ето как би изглеждало това:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiUMPd5B4JGAxaidZk-ilw.png" /></figure><p>Нека да разгледаме и друг пример: правим промяна в първи модул, само че всички останали модули зависят от този модул. Тук почти всичко ще бъде компилирано наново:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncNX1LPQhGCww3b5qi10ow.png" /></figure><blockquote>От разгледаните примери досега се вижда ясно, че когато имаме промяна в модул, който е самостоятелен, при компилация се компилира само този модул, а всичко останало се взима от кеша. Когато обаче имаме промяна в модул и всички останали модули зависят от него, то когато компилираме нашия проект, всичко ще бъде компилирано наново и няма да можем да се възползваме от кеша.</blockquote><p><strong>Пускане на локалния build кеш</strong></p><p>Както вече казахме, build кешът не е пуснат по подразбиране. Има два начина, по които може да го пуснем. Първият начин е да добавим <em>-build-cache</em> опцията, когато стартираме компилацията на проекта през терминала. Така Gradle ще използва build кеша само за тази компилация. Другият начин, по който може да пуснем кеша, е да добавим <em>org.gradle.caching=true</em> в нашия <em>gradle.properties</em> файл. Gradle ще използва повторно изходните данни от предишните компилации за всички бъдещи компилации, освен ако изрично не спрете кеша с <em>–no-build-cache</em>.<br>Когато кешът е пуснат, той ще съхранява всички изходни данни от компилациите в Gradle home директорията на потребителя (<em>/home/user/.gradle/caches</em>). Тази директория може да се промени. Gradle периодично ще изчиства кеш директорията, като премахва записи на изходни данни, които не са били използвани наскоро, за да спести свободно място. Както може да видите, на снимката, по-долу сме дефинирали нашия кеш да се пази в папка “build-cache” и неизползваните изходни данни от кеша да се изтрият след 30 дни.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*fCu0iDR1q8Tf4lqcapQsYA.png" /></figure><p>Направихме тестов Java проект и го компилирахме с пуснат кеш:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*QwahuZPetmTRMEwv-QEcWQ.png" /></figure><p>Както виждате, всичко е нормално и компилацията е успешна. След това пуснахме <em>gradle clean</em>, за да изчистим изходните данни от build папката и направихме нова компилация:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*NCHdzaaq7r1w_jxn4gmUPQ.png" /></figure><p>Ще забележите, че <em>compileJava</em> задачата беше взета от кеша. Разбира се, за такъв елементарен Java проект няма да забележите полза, но ако нашият проект е голям, ще има значително подобрение във времето за компилация, както показахме на примера преди малко.</p><p><strong>Отдалечен кеш</strong></p><p>Gradle има вградена поддръжка за свързване към отдалечен Gradle кеш сървър през HTTP. За да се свържем към отдалечен кеш сървър, трябва да опишем url-a на сървъра, както и потребителското име и парола, ако има такива, в <em>settings.gradle</em> файла:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RfIPmw8WJEuO9SJ-XeJKQ.png" /></figure><p>По този начин, когато компилираме нашия проект, Gradle ще се свърже с отдалечения кеш сървър и ще се опита да използва повторно данните от предишни компилации. В случай, че не бъдат намерени такива, то резултата от тази компилация ще бъде записан в отдалечения кеш сървър.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*U1WXk9E8cHf9x2JjnvDF8g.png" /></figure><p><em>В следващия блог пост ще покажем как да конфигурираме Gradle кеша, когато имаме CI, както и пуснат локален и отдалечен кеш. Също така ще разгледаме и Gradle кеш сървъра, който е необходим, за да използваме отдалечения кеш.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e508732bce3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paysafe-bulgaria/%D1%83%D1%81%D0%BA%D0%BE%D1%80%D1%8F%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-%D0%BA%D0%BE%D0%BC%D0%BF%D0%B8%D0%BB%D0%B0%D1%86%D0%B8%D1%8F%D1%82%D0%B0-%D0%BD%D0%B0-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0-%D1%87%D1%80%D0%B5%D0%B7-%D0%B8%D0%B7%D0%BF%D0%BE%D0%BB%D0%B7%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-gradle-%D0%BA%D0%B5%D1%88-%D0%B2%D1%82%D0%BE%D1%80%D0%B0-%D1%87%D0%B0%D1%81%D1%82-8e508732bce3">Ускоряване на компилацията на проекта чрез използване на Gradle кеш — втора част</a> was originally published in <a href="https://medium.com/paysafe-bulgaria">paysafe-bulgaria</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ускоряване на компилацията на проектa чрез използване на Gradle кеш — първа част]]></title>
            <link>https://medium.com/paysafe-bulgaria/%D1%83%D1%81%D0%BA%D0%BE%D1%80%D1%8F%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-%D0%BA%D0%BE%D0%BC%D0%BF%D0%B8%D0%BB%D0%B0%D1%86%D0%B8%D1%8F%D1%82%D0%B0-%D0%BD%D0%B0-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82a-%D1%87%D1%80%D0%B5%D0%B7-%D0%B8%D0%B7%D0%BF%D0%BE%D0%BB%D0%B7%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-gradle-%D0%BA%D0%B5%D1%88-%D0%BF%D1%8A%D1%80%D0%B2%D0%B0-%D1%87%D0%B0%D1%81%D1%82-92e06968e194?source=rss----db09e34211aa---4</link>
            <guid isPermaLink="false">https://medium.com/p/92e06968e194</guid>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[производителност]]></category>
            <category><![CDATA[кеш]]></category>
            <category><![CDATA[продуктивност]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Radoslav Yordanov]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 07:18:52 GMT</pubDate>
            <atom:updated>2021-04-06T07:18:52.839Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ускоряване на компилацията на проекта чрез използване на Gradle кеш — първа част</h3><p><em>В тази поредица от няколко части ще обясним защо е необходимо кода да се компилира по-бързо и как това влияе на продуктивността на програмистите. Ще обясним какво е Gradle кеш и ще разгледаме как работи. Ще разгледаме как да ускорим компилацията на нашия проект, чрез използване на локален и отдалечен Gradle кеш.</em></p><p><strong>Защо е необходимо да компилираме кода по-бързо? </strong><br>Производителността при компилиране е критична за нашата продуктивност. Колкото повече време отнема една компилация, толкова по-вероятно е да загубим фокус и да се разсеем с нещо друго. На всичкото отгоре, тъй като компилираме код много пъти на ден, дори малки периоди на изчакване могат да доведат до значителни смущения. Същото важи и за компилирането на кода, който се изпълнява на CI средата: колкото по-бързо е то, толкова по-бързо можем да реагираме на нови проблеми. Например: ако един програмист чака 40 мин. за да получи резултат от CI средата, че нещо се е объркало, тогава програмистът трябва да остави задачата върху, която работи, да се върне обратно в branch-a, в който е работил, да направи commit с фикса и да изчака още 40 мин. за да получи резултат от CI средата. <em>Освен това по-бързото компилиране на кода намалява натоварването на CI средата.</em></p><p><strong>Как времето за компилация влияе върху продуктивността на програмистите?</strong><br>Съвсем нормално е дадена компилация да не се изпълни успешно ако сте направили грешка. Например, счупили сте някой тест и компилацията ще завърши неуспешно. Въз основа на проучване направено от Gradle, клиентите казват, че около 20% от опитите за компилиране код завършват с грешка поради такива проблеми и 5–10% от капацитета на екипа се изразходва в отстраняването на проблема.</p><blockquote>Да кажем, че вашият код се компилира за 60 сек. и правите това 50 пъти на ден — нещо съвсем нормално за Gradle проект. Също така нека предположим, че в екипа ви има 50 програмисти. Ако пресметнем общото време, което програмистите са загубили за компилиране, не мисля, че е трудно да се осъзнае, че това са 42 часа загубени на ден. Ако работите на 40 часова работна седмица, това означава, че губите по една работна седмица за един програмист и това време дори не включва загубения фокус.</blockquote><blockquote>Времето, за което се компилира вашия проект е технически дълг, който винаги се изплаща и е лесно да се оправдае работата по него, защото цифрите са много ясни. Колкото по-бързо се компилира вашия проект — толкова по-малко загубен фокус ще имат вашите програмисти.</blockquote><p><strong>Как да постигнем по-бързо време за компилация?</strong><br>В общи линии за да компилираме един проект по-бързо, трябва да избягваме нещата и стъпките, които не е необходимо да се правят. Това може да се постигне чрез повторно използване на резултатите от предишно компилиране на кода и има два начина за това. Единият от тях е чрез инкрементентален подход (incremental build), а другият е чрез използването на build кеш. Инкременталният подход за компилиране идва по подразбиране. Разработчикът не трябва да прави нищо, за да го използва. Build кешът от другата страна е функционалност, която не е включена по подразбиране. Но преди да навлезем в повече подробности, нека първо да обясним какво е кеширане.</p><blockquote>Noun, cache not repeating work already done.</blockquote><p>Това е значението на думата от английския речник и гласи, че когато казваме кеширане, имаме предвид как можем да избегнем повтарянето на вече свършената работа.</p><p><strong>Инкрементентален подход (incremental builds)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*A9vpzfdAgH62WL6qyxPfqQ.png" /></figure><p>Инкременталния подход на компилиране на код позволява на Gradle да използва повторно резултатите от последната компилация, което от своя страна му позволява да прескочи някои задачи (tasks). Нека вземем за пример задачата по подразбиране на Gradle — JavaCompile. JavaCompile декларира входове (source файлове) и изходи (class файлове). Gradle използва тази информация за да прецени дали дадена задача трябва да се изпълни или не. Така ако задачата е up-to-date, т.е. няма промяна по нейните входове и изходи, това означава, че тя ще бъде пропусната и Gradle ще използва повторно резултата от нейното последно изпълнение. Ако направите промяна на някой source файл и промените например коментар, пак ще трябва да изпълним отново задачата JavaCompile, защото знаем, че source файловете са променени, но получените class файлове ще бъдат абсолютно същите каквито бяха. Повечето задачи, предоставени от Gradle, участват в инкрементално компилиране, защото са дефинирани по този начин.</p><p><strong>Какво е Gradle build кеш?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*lrfrrKNRjp0R5aGFRMCXdA.png" /></figure><p>След като обяснихме как кодът се компилира инкрементално, сега можем да поговорим за Gradle build кеша. Gradle build кешът е въведен в Java света от Gradle през 2017г. с версия 4.0 и е механизъм за запазване на данни и тяхното повторно използване по-късно. Той цели да спести време чрез повторно използване на резултати от предишни компилации, за разлика от инкременталния build, който използва само резултата от последната компилация. Gradle build кешът работи като съхранява резултатите от предишни компилации локално или на отдалечен сървър. По този начин, при компилация на вашия код, може да се използват резултатите от кеша, ако входните данни не са били променени. Така ще спестите ресурси и време вместо да ги компилирате наново. <em>Например: ако компилираме branch A и след това отидем на branch B и го компилираме, то всички резултати от branch A ще бъдат загубени ако не използваме build кеша.</em></p><p>Важно е да уточним, че build кеша не може да работи с всякакви задачи. Задачи, които имат входно-изходни операции, като копиране на файл, не могат да се кешират.</p><p><strong>Как работи Gradle build кеша?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*9R4jJRByEWH0d5qA1rW_hA.png" /></figure><p>Най-общо казано Gradle build кеша използва стандартна имплементация на кеш. Тъй като една задача описва всички входове (java класове, binaries, 3th party libs) и изходи (class файлове), то Gradle може да изчисли build кеш ключа на база на входовете и да провери за изходите. Build кеш ключът се използва за да вземем предишни изходи от build кеша или да запазим нови изходи в build кеша. Ако изходите от предишни компилации са вече запазени в кеша от някой друг, например CI сървър или други програмисти, така можем да спестим изпълнението на тези задачи локално.</p><p><em>В следващия блог пост ще разгледаме как кешът влияе върху проекти с повече от един модул и как да пуснем локален и отдалечен Gradle кеш.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92e06968e194" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paysafe-bulgaria/%D1%83%D1%81%D0%BA%D0%BE%D1%80%D1%8F%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-%D0%BA%D0%BE%D0%BC%D0%BF%D0%B8%D0%BB%D0%B0%D1%86%D0%B8%D1%8F%D1%82%D0%B0-%D0%BD%D0%B0-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82a-%D1%87%D1%80%D0%B5%D0%B7-%D0%B8%D0%B7%D0%BF%D0%BE%D0%BB%D0%B7%D0%B2%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-gradle-%D0%BA%D0%B5%D1%88-%D0%BF%D1%8A%D1%80%D0%B2%D0%B0-%D1%87%D0%B0%D1%81%D1%82-92e06968e194">Ускоряване на компилацията на проектa чрез използване на Gradle кеш — първа част</a> was originally published in <a href="https://medium.com/paysafe-bulgaria">paysafe-bulgaria</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[git aliases — пътеводител на мързеливия програмист]]></title>
            <link>https://medium.com/paysafe-bulgaria/git-aliases-%D0%BF%D1%8A%D1%82%D0%B5%D0%B2%D0%BE%D0%B4%D0%B8%D1%82%D0%B5%D0%BB-%D0%BD%D0%B0-%D0%BC%D1%8A%D1%80%D0%B7%D0%B5%D0%BB%D0%B8%D0%B2%D0%B8%D1%8F-%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%B8%D1%81%D1%82-7fdc7b90824f?source=rss----db09e34211aa---4</link>
            <guid isPermaLink="false">https://medium.com/p/7fdc7b90824f</guid>
            <category><![CDATA[псевдоними]]></category>
            <category><![CDATA[git-config]]></category>
            <category><![CDATA[alias]]></category>
            <category><![CDATA[гит]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Viktor Penelski]]></dc:creator>
            <pubDate>Tue, 18 Dec 2018 12:18:30 GMT</pubDate>
            <atom:updated>2018-12-25T09:45:08.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>Git aliases — пътеводител на мързеливия програмист</h3><blockquote>Статията е написана с предположение, че сте работили с git. Ако не сте, препоръчвам първо да минете през някой базов tutorial (например <a href="http://rogerdudler.github.io/git-guide/"><strong>този</strong></a><strong> </strong>на Роджър Дъдлър)</blockquote><p>Годината е 2005-та, а <a href="https://www.gnu.org/philosophy/mcvoy.html"><strong>Лари Маквой</strong></a><em>,</em> бесен, че някой се е опитал да reverse-engineer-не неговата системата за контрол на версия на файлове — BitKeeper, спира безплатните лицензи на разработчиците на Линукс ядрото. След неуспешно търсене на заместител, Линус Торвалдс стига до заключението, че единственият вариант е да напише <a href="https://www.youtube.com/watch?v=4XpnKHJAok8"><strong>нова система</strong></a> — дистрибутирана, бърза и във всяко едно отношение — напълно обратна на най-популярната алтернатива CVS ( “ what would CVS never ever do” — Linus). Така се заражда git.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*IOgOOByqiBWPMCfuHBWdrA.png" /><figcaption>Дефиниция на акронима според оригиналния <a href="https://github.com/git/git/blob/e83c5163316f89bfbde7d9ab23ca2e25604af290/README">README файл</a></figcaption></figure><p>Git е изключително мощна система за контрол на версията на файлове, но както казва Волтер — “With great power comes great responsibility.” или за git — “… great complexity”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*q2ody-1Xt7kMgLNx6uuDdQ.jpeg" /><figcaption>git поддържа <strong>много </strong>функционалности — от <a href="https://git-scm.com/docs/git-send-email">изпращане на пачове по e-mail</a>, до конфигуриране и стартиране на <a href="https://git-scm.com/docs/gitweb">web-server от локално repository</a></figcaption></figure><p>Преди известно време реших, че за да разбера добре работния процес в git, най-удачният начин е да се науча да го използвам продуктивно през command line интерфейса. Мина известно време и както всеки мързелив програмист би направил — започнах да търся начини това да бъде по-удобно за мен (особено след поредния път, в който трябваше да търся <strong>“</strong><a href="https://www.google.bg/search?q=git+how+to+unstage+files"><strong>как се ънстейджват файлове</strong></a>”). Няма проблем, нищо, с което добрият стар .bashrc да не може да се справи.</p><pre><strong># .bashrc</strong></pre><pre><strong>alias unstage=&quot;git reset -q HEAD --&quot;</strong></pre><p>Дотук добре, но с добавянето на допълнителни alias-и (up, down, history) бързо започнаха да се появяват такива, които не е очевидно, че са свързани с git.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*6gJTSw-PQFnK0njMrihUjQ.png" /><figcaption>Това сега за <strong>git </strong>ли беше, за <strong>docker </strong>или за нещо друго 🤔</figcaption></figure><p>Този проблем може да бъде решен по множество начини — мога да променя alias-ите да ползват общ “prefix” (пр. gup, gdown, ghistory) или пък да направя функция, приемаща аргумент (пр. g $1)… но не може да няма и по-лесен начин…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*aXZCTJ1HKAknqGgSjUrVBA.png" /></figure><p>Ето къде се появяват <a href="https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases"><strong>git aliases</strong></a> — псевдоними, изолирани от общия “namespace”. Примерните alias-и, които документацията показва са:</p><pre>$ git config --global alias.co checkout<br>$ git config --global alias.br branch<br>$ git config --global alias.ci commit<br>$ git config --global alias.st status</pre><p>Супер! Дали не могат и да се конфигурират и с по-сложни команди?</p><p>Еквивалент на първият alias мога да добавя с:</p><pre><strong>git config --global alias.unstage &#39;reset -q HEAD --&#39;</strong></pre><p>Което ще се отрази като промяна на ~/.gitconfig файла, където всички git alias-и се пазят:</p><pre><strong>[alias]<br>    unstage = reset -q HEAD --</strong></pre><p>Git alias-и се ползват като всички останали команди в git, т.е. бих извикал горепосочения с git unstage и това ще “ънстейджне” всички добавени файлове. Може да бъде ползван и с аргументи — git unstage README.md, което би премахнало от staging само посочения файл.</p><p>Ето и още няколко от любимите ми git alias-и, които често спестяват време покрай финализирането на комит преди да напусне локалното репо:</p><pre><strong>[alias]<br>    amend = commit --amend --no-edit<br>    amsg = commit --amend -m            <br>    uncommit = reset HEAD~</strong></pre><ul><li>amendдобавя всички staged файлове към последния комит, запазвайки commit message-а.</li><li>amsg същото, но очаква съобщение като аргумент git amsg &quot;wohoo&quot; и променя commit message-a.</li><li>uncommit премахва последния комит, запазвайки файловете</li></ul><pre><strong>[alias]<br>    history = &quot;log --pretty=format:&quot;%C(yellow)%h%Cred%d\\%Creset%s%Cblue\\ [%cn]&quot; --decorate&quot;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*pMPX_pP021boKrTEvIT2CA.png" /></figure><p><a href="https://gist.github.com/viktorpenelski/9194d747b1f8993d6d5b8694647834e8"><strong>Това е конфигурацията</strong></a>, която ползвам, както на личната си машина, така и на служебната.</p><p>Git alias-ите са полезни от една страна за съкращаване на синтаксис (st -&gt; status), но от друга — значително по-важна за мен — за добавяне на допълнителни опции към командата (st -&gt; status -s) и по-логично наименование на “сложни” команди (unstage -&gt; reset -q HEAD). Единственият недостатък е, че лесно се свиква с удобно създадените alias-и. За това пазете.gitconfig -a си на удобно място😉</p><p>Приятно гитене! 🚀🚀🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fdc7b90824f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paysafe-bulgaria/git-aliases-%D0%BF%D1%8A%D1%82%D0%B5%D0%B2%D0%BE%D0%B4%D0%B8%D1%82%D0%B5%D0%BB-%D0%BD%D0%B0-%D0%BC%D1%8A%D1%80%D0%B7%D0%B5%D0%BB%D0%B8%D0%B2%D0%B8%D1%8F-%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%B8%D1%81%D1%82-7fdc7b90824f">git aliases — пътеводител на мързеливия програмист</a> was originally published in <a href="https://medium.com/paysafe-bulgaria">paysafe-bulgaria</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>