<?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[Stories by Sknurhassan on Medium]]></title>
        <description><![CDATA[Stories by Sknurhassan on Medium]]></description>
        <link>https://medium.com/@sknurhassan04?source=rss-c4fbf57e41b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cSvNeqmrxj5Zw3PN</url>
            <title>Stories by Sknurhassan on Medium</title>
            <link>https://medium.com/@sknurhassan04?source=rss-c4fbf57e41b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:59:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sknurhassan04/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Trip Through Spring Security]]></title>
            <link>https://medium.com/@sknurhassan04/a-trip-through-spring-security-de2ee60e4226?source=rss-c4fbf57e41b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/de2ee60e4226</guid>
            <category><![CDATA[spring-boot-security]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sknurhassan]]></dc:creator>
            <pubDate>Sun, 02 Oct 2022 15:52:35 GMT</pubDate>
            <atom:updated>2022-10-02T15:52:35.157Z</atom:updated>
            <content:encoded><![CDATA[<h3>What can Spring do to help me secure my application?</h3><p>Adding a security layer to Spring projects</p><h3>Audience</h3><p>This article is aimed at developers with a solid understanding of the basics of Spring and web security. It marries up the two concepts, concluding with a worked example of using Spring Security with Spring Boot.</p><h3>Argument</h3><p>Spring Security is centred round two core concepts:</p><ol><li><strong>Authentication: </strong>Verifying you are who you say you are.</li><li><strong>Authorisation: </strong>Once we know who you are, what are you allowed to do?</li></ol><h3>Authentication</h3><p>Authentication is handled by the AuthenticationManager interface:</p><pre>public interface AuthenticationManager {  Authentication authenticate(Authentication authentication)<br>    throws AuthenticationException;<br>}</pre><p>This can be implemented differently depending on how we intend to authenticate. In our later example we will be authenticating using API Keys, but we may well use a database of user credentials.</p><p>From the method signature we can see that the authenticate method has three behaviours:</p><ol><li>Return an Authentication , usually using a true authenticated flag if it the provided input represents a valid <strong>Principal. </strong>A principal essentially refers to the current client.</li><li>Throw a runtime AuthenticationException. Note, we will need to implement a way of dealing with this, but without an explicit try/ catch block.</li><li>Return null if no decision is made.</li></ol><p>We have our authentication <em>interface</em>, but what about the <em>implementation</em>? The most common solution is a ProviderManager, which delegates to a chain of AuthenticationProviders. We can see how this would be useful in the case where we had multiple different methods of authenticating.</p><p>The AuthenticationProvider has a method boolean supports(Class&lt;?&gt; authentication), which is used to check if we support the current authentication instance type.</p><pre>public interface AuthenticationProvider {  Authentication authenticate(Authentication authentication)<br>			throws AuthenticationException;  boolean supports(Class&lt;?&gt; authentication);<br>}</pre><p>To clarify, let’s think about a customAuthenticationProvider that uses a username and password to check if a user should be allowed into our application:</p><pre>@Component <br>public class <strong>UsernamePasswordAuthenticationProvider</strong> implements <strong>AuthenticationProvider</strong> {  // Method for authentication<br>  @Override<br>  public Authentication <strong>authenticate</strong>(Authentication authentication) throws AuthenticationException {    String username = authentication.getName();<br>    String password = authentication.getCredentials().toString();    if (shouldAuthenticateUsernamePassword()) { <br>      // Do authentication work<br>   <br>      return new UsernamePasswordAuthenticationToken(<br>        username, <br>        password, <br>        new ArrayList&lt;&gt;()<br>      );         <br>    } else {<br>      return null;<br>    }}  // Checking the type of authentication is appropriate<br>  @Override     <br>  public boolean <strong>supports</strong>(Class&lt;?&gt; authentication) {<br>    return authentication.equals(UsernamePasswordAuthenticationToken.class);<br>  } <br>}</pre><p>The use of tokens will be covered in more detail in the example, so don’t worry about it too much for the time being. As long as you get the gist it’s OK!</p><p>A ProviderManager has an optional parent, which it can fall back to if all providers return null. Let’s use another example to clarify.</p><p>Say we have an application, where by default we would like all of our endpoints secured using a username and password. However, for some endpoints we are happy just using an API key, and for others we want to use a completely different authentication again!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*j1jURyx62odLugEY.png" /></figure><p>An example of provider managers and authentication providers</p><p>The top ProviderManager is our global default, and this insists we use the username and password authentication (amongst others). On the lower left we see a ProviderManager that uses an API Key. However, if none of the AuthenticationProvider s in the chain offers a valid authentication, it will fall back to the parent and use the username and password!</p><p>To ease the process of building AuthenticationManager s Spring provides some helper functionality, including the AuthenticationManagerBuilder.</p><pre>@Configuration<br>public class ApplicationSecurity extends WebSecurityConfigurerAdapter {  @Autowired<br>  public void initialize(AuthenticationManagerBuilder builder, DataSource dataSource) {<br>  ... configure builder here<br>}</pre><p>Don’t worry too much about the Configuration this sits in, again we will expand on it in the example.</p><p>An important point to note is how we configure a global default authentication manager (like the one with username and password authentication) vs. how we configure any others.</p><p>By using the Autowired annotation we are creating a Spring bean, which will act as the global default. If instead we used Override we would create another AuthenticationManager . Spring Boot provides a secure, single user, default global AuthenticationManager unless you provide your own.</p><h3>Authorisation</h3><p>We have now covered how Spring Security <em>authenticates </em>a user. So once we know they are who they say they are, how do we decide what they’re allowed to do?</p><p>This uses theAccessDecisionManager, which delegate to a chain of AccessDecisionVoters, which look at an Authentication as passed from the authentication layer and decides if a user (principal) can access a resource (with a web resource or a Java class method being the two most common).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/0*M15_y5dnnGKBEjcF.png" /></figure><p>An Access Decision Manager calling each of the Access Decision Voters to determine Authorisation</p><p>The resource is represented by a secure Object, which has been decorated with ConfigAttributes.</p><p>A ConfigAttribute is an interface, with a single method returning a string. A typical ConfigAttribute is the name of a user role, often having given formats (like the ROLE_ prefix) or representing Spring Expression Language expressions that need to be evaluated.</p><p>Let’s look at an example class:</p><pre>public class <strong>UserVoter</strong> implements <strong>AccessDecisionVoter</strong> {  @Override<br>  public int <strong>vote(<br>    </strong>Authentication authentication,<br>    Object object, <br>    Collection collection) {<br>      return authentication.getAuthorities()<br>               .stream()<br>               .map(GrantedAuthority::getAuthority)<br>               .filter(r -&gt; &quot;ROLE_USER&quot;.equals(r))<br>               .findAny()       <br>               .map(s -&gt; ACCESS_GRANTED)<br>               .orElseGet(() -&gt; ACCESS_DENIED); <br>  }  @Override <br>  public boolean <strong>supports</strong>(ConfigAttribute attribute) { <br>    return true; <br>  }  @Override <br>  public boolean <strong>supports</strong>(Class clazz) {<br>    return true; <br>  }<br>}</pre><p>In the above example we have three methods:</p><ol><li><strong>Vote:</strong> This accepts an Authentication, an Object we are looking to check access for, and a list of ConfigAttributes. It can return three values defined statically by Spring, ACCESS_GRANTED, ACCESS_DENIED, and ACCESS_ABSTAIN. The final value is used when we don’t want to make a authorisation decision.</li><li><strong>Supports </strong><strong>ConfigAttribute: </strong>This is used to see if the particular voter can be used in conjunction with a particular ConfigAttribute.</li><li><strong>Supports </strong><strong>Class: </strong>The same as above, but with a given class, representing the class of the argument for the vote method.</li></ol><p>We can see that we are granting access to any user. Both our supports methods are returning true , as we essentially ignore the incoming Object and ConfigAttributes.</p><p>In the final part of this section we will look at how Spring implements Web Security.</p><p>When a request from a client comes into an application it must first go through a number of filters before it reaches the servlet. Spring Security has a concrete type of FilterChainProxy, which can replace a single filter in the chain, as demonstrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/0*H4jEXd2pZI1Q6o6B.png" /></figure><p>How filters interact with a client request, including Spring Security</p><p>This diagram shows a single filter chain in Spring Security, however there can be multiple. In practice this means that we match a request format to a filter chain, and so can use separate security measures for separate requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/0*Luk5Jyw2c9TgxCOO.png" /></figure><p>Examples of routing to different filter chains depending on requests</p><p>In the above we see we can route to different filter chains depending if the request goes to path /a/** , /b/** and /**. The final chain is the default, and catches all requests that have not been matched otherwise.</p><h3>An Example</h3><p>The full code can be found in the repository <a href="https://github.com/JamesCollerton/Spring-Security">here</a>. We first use the Spring Initializr to generate a project with the required dependencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kXfZxcgU_T3l-eBE.png" /></figure><p>Generating a Spring project for use with Spring Security</p><p>From here we import the project into IntelliJ and set up the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*z4h96FGrl6IHHJ8c.png" /></figure><p>An example class structure</p><p>Some of these classes should look familiar:</p><ol><li><strong>SecurityConfig:</strong> This contains the Spring configuration to enable and set up security.</li><li><strong>ApiKeyAuthenticationFilter: </strong>This is the filter we will put in the filter chain.</li><li><strong>ApiKeyAuthenticationToken: </strong>This is the authentication token we will be passing, representing the access of the client.</li><li><strong>ApiKeyAuthenticationProvider: </strong>This is the provider we will be using to authenticate the endpoint.</li><li><strong>Order: </strong>This is the object we will be returning from the controller.</li><li><strong>OrderController: </strong>This is the endpoint we will secure using an API key.</li></ol><p>Now let’s deep dive into each class.</p><h3>SecurityConfig</h3><pre>@Configuration<br>@EnableWebSecurity<br><strong>public class </strong>SecurityConfig <strong>extends </strong>WebSecurityConfigurerAdapter {</pre><pre>  @Autowired <strong>private </strong>ApiKeyAuthenticationProvider <strong>apiKeyAuthenticationProvider</strong>;</pre><pre>  @Override<br>  <strong>protected void </strong>configure(HttpSecurity httpSecurity) <strong>throws </strong>Exception {<br>    httpSecurity<br>        .authorizeRequests()<br>        .anyRequest()<br>        .authenticated()<br>        .and()<br>        .addFilterBefore(<br>            <strong>new </strong>ApiKeyAuthenticationFilter(authenticationManager()),<br>            AnonymousAuthenticationFilter.<strong>class</strong>);<br>  }</pre><pre>  @Bean<br>  <strong>public </strong>AuthenticationManager authenticationManager() {<br>    <strong>return new </strong>ProviderManager(Collections.<em>singletonList</em>(<strong>apiKeyAuthenticationProvider</strong>));<br>  }<br>}</pre><p>The first thing to notice is the configure method. This is used to set up our Spring Security layer to make sure all requests are authenticated. You can see we’re adding our API Key authentication filter into the filter chain at a certain point.</p><p>Additionally, we’re setting up our authentication manager with a single provider, the API Key Authentication provider. So far this is all looking quite familiar!</p><p><strong>ApiKeyAuthenticationFilter</strong></p><pre><strong>public class </strong>ApiKeyAuthenticationFilter <strong>extends </strong>AbstractAuthenticationProcessingFilter {</pre><pre>  <strong>public </strong>ApiKeyAuthenticationFilter(AuthenticationManager authenticationManager) {<br>    <strong>super</strong>(<strong>&quot;/**&quot;</strong>);<br>    <strong>this</strong>.setAuthenticationManager(authenticationManager);<br>  }</pre><pre>  @Override<br>  <strong>public </strong>Authentication attemptAuthentication(<br>      HttpServletRequest request, HttpServletResponse response) {</pre><pre>    Optional&lt;String&gt; apiKeyOptional = Optional.<em>ofNullable</em>(request.getHeader(<strong>&quot;x-api-key&quot;</strong>));</pre><pre>    ApiKeyAuthenticationToken token =<br>        apiKeyOptional.map(ApiKeyAuthenticationToken::<strong>new</strong>).orElse(<strong>new </strong>ApiKeyAuthenticationToken());</pre><pre>    <strong>return </strong>getAuthenticationManager().authenticate(token);<br>  }</pre><pre>  @Override<br>  <strong>protected void </strong>successfulAuthentication(<br>      HttpServletRequest request,<br>      HttpServletResponse response,<br>      FilterChain chain,<br>      Authentication authResult)<br>      <strong>throws </strong>IOException, ServletException {</pre><pre>      SecurityContextHolder.<em>getContext</em>().setAuthentication(authResult);<br>    chain.doFilter(request, response);<br>  }<br>}</pre><p>This is the filter we add to the chain. Notice how we create the object using the authentication manager, then later retrieve the API Key and use the authentication manager to authenticate the request.</p><p><strong>ApiKeyAuthenticationToken</strong></p><pre>@Transient<br><strong>public class </strong>ApiKeyAuthenticationToken <strong>extends </strong>AbstractAuthenticationToken {</pre><pre>  <strong>private </strong>String <strong>apiKey</strong>;<br>  <br>  <strong>public </strong>ApiKeyAuthenticationToken(String apiKey, <strong>boolean </strong>authenticated) {<br>    <strong>super</strong>(AuthorityUtils.<strong><em>NO_AUTHORITIES</em></strong>);<br>    <strong>this</strong>.<strong>apiKey </strong>= apiKey;<br>    setAuthenticated(authenticated);<br>  }</pre><pre>  <strong>public </strong>ApiKeyAuthenticationToken(String apiKey) {<br>    <strong>super</strong>(AuthorityUtils.<strong><em>NO_AUTHORITIES</em></strong>);<br>    <strong>this</strong>.<strong>apiKey </strong>= apiKey;<br>    setAuthenticated(<strong>false</strong>);<br>  }</pre><pre>  <strong>public </strong>ApiKeyAuthenticationToken() {<br>    <strong>super</strong>(AuthorityUtils.<strong><em>NO_AUTHORITIES</em></strong>);<br>    setAuthenticated(<strong>false</strong>);<br>  }</pre><pre>  @Override<br>  <strong>public </strong>Object getCredentials() {<br>    <strong>return null</strong>;<br>  }<br>  <br>  @Override<br>  <strong>public </strong>Object getPrincipal() {<br>    <strong>return apiKey</strong>;<br>  }<br>}</pre><p>This is the token used across requests. Points to note:</p><ul><li>In the constructor we are passing AuthorityUtils.NO_AUTHORITIES . This is referring to Granted Authorities, which are essentially permissions. We can use this to pass rights around with a token once a client has been authenticated. In our case we have no need to do this.</li><li>The principal is the identity of the principal being authenticated. In our case it is the API Key.</li></ul><p><strong>ApiKeyAuthenticationProvider</strong></p><pre>@Component<br><strong>public class </strong>ApiKeyAuthenticationProvider <strong>implements </strong>AuthenticationProvider {</pre><pre>  @Override<br>  <strong>public </strong>Authentication authenticate(Authentication authentication) <strong>throws </strong>AuthenticationException {<br>    String apiKey = (String) authentication.getPrincipal();</pre><pre>    <strong>if </strong>(ObjectUtils.<em>isEmpty</em>(apiKey)) {<br>      <strong>throw new </strong>InsufficientAuthenticationException(<strong>&quot;No API key in request&quot;</strong>);<br>    } <strong>else </strong>{<br>      <strong>if </strong>(<strong>&quot;ValidApiKey&quot;</strong>.equals(apiKey)) {<br>        <strong>return new </strong>ApiKeyAuthenticationToken(apiKey, <strong>true</strong>);<br>      }<br>      <strong>throw new </strong>BadCredentialsException(<strong>&quot;API Key is invalid&quot;</strong>);<br>    }<br>  }</pre><pre>  @Override<br>  <strong>public boolean </strong>supports(Class&lt;?&gt; authentication) {<br>    <strong>return </strong>ApiKeyAuthenticationToken.<strong>class</strong>.isAssignableFrom(authentication);<br>  }<br>}</pre><p>This is the authentication provider. We see here we authenticate the request using the API key. We also need to tell the authentication manager which authentications we support, hence the support method.</p><p><strong>Order and OrderController</strong></p><pre>@Controller<br><strong>public class </strong>OrderController {</pre><pre>  @GetMapping(<strong>&quot;/order&quot;</strong>)<br>  <strong>public </strong>ResponseEntity&lt;Order&gt; getOrder() {</pre><pre>    Order order = Order.<em>builder</em>().name(<strong>&quot;Order One&quot;</strong>).description(<strong>&quot;Order One Description&quot;</strong>).build();</pre><pre>    <strong>return </strong>ResponseEntity.<em>ok</em>(order);<br>  }<br>}</pre><p>This is a regular controller class, used only to demonstrate how they can be secured.</p><pre>@Builder<br>@Data<br><strong>public class </strong>Order {<br>    <strong>private </strong>String <strong>name</strong>;<br>    <strong>private </strong>String <strong>description</strong>;<br>}</pre><p>Similarly, this small model class is returned in order to demonstrate a working endpoint.</p><p>In Postman we can see that by making a request without a valid x-api-key header, we receive a 401. With a correctly implemented API Key we can access our order!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b5o5qtjM5wkJZClU.png" /></figure><p>A successfully authenticated request!</p><h3>Conclusion</h3><p>In conclusion, application security can be reduced to: authentication (are you who you say you are?) and authorization (what can you do?). Spring Security implements both of these within the Spring framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de2ee60e4226" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A quick intro to Dependency Injection: what it is, and when to use it]]></title>
            <link>https://medium.com/@sknurhassan04/a-quick-intro-to-dependency-injection-what-it-is-and-when-to-use-it-1c734be06406?source=rss-c4fbf57e41b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c734be06406</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sknurhassan]]></dc:creator>
            <pubDate>Sun, 18 Sep 2022 18:55:37 GMT</pubDate>
            <atom:updated>2022-09-18T18:55:37.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*nh5yFqaG0j1lCAUN.jpeg" /></figure><p>Photo by <a href="https://unsplash.com/photos/UFCVxUC-PqM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">rawpixel</a> on <a href="https://unsplash.com/search/photos/team?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p><h3>Introduction</h3><blockquote><em>In </em><a href="https://en.wikipedia.org/wiki/Software_engineering"><em>software engineering</em></a><em>, </em><strong><em>dependency injection</em></strong><em> is a technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a </em><a href="https://en.wikipedia.org/wiki/Service_(systems_architecture)"><em>service</em></a><em>).</em></blockquote><p>That’s the Wikipedia definition but still, but it’s not particularly easy to understand. So let’s understand it better.</p><p>Before understanding what it means in programming, let’s first see what it means in general as it will help us understand the concept better.</p><p>Dependency or dependent means relying on something for support. Like if I say we are relying too much on mobile phones than it means we are dependent on them.</p><p>So before getting to <a href="https://en.wikipedia.org/wiki/Dependency_injection"><strong>dependency injections</strong></a>, first let’s understand what a dependency in programming means.</p><p>When class A uses some functionality of class B, then its said that class A has a dependency of class B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*tXPMjOLhyyjhnJ-O.jpeg" /></figure><p>Showing dependencies between classes</p><p>In Java, before we can use methods of other classes, we first need to create the object of that class (i.e. class A needs to create an instance of class B).</p><p><strong>So, transferring the task of creating the object to someone else and directly using the dependency is called dependency injection.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*YnBgWS3seRBJJLoB.png" /></figure><p>What if code could speak?</p><h3>Why should I use dependency injection?</h3><p>Let’s say we have a car class which contains various objects such as wheels, engine, etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa30687a3ce0ef9362e1c7ee81cc3ec1/href">https://medium.com/media/aa30687a3ce0ef9362e1c7ee81cc3ec1/href</a></iframe><p>Without dependency injection(DI)</p><p>Here the car class is responsible for creating all the dependency objects. Now, what if we decide to ditch <strong>MRFWheels </strong>in the future and want to use <strong>Yokohama</strong> Wheels?</p><p>We will need to recreate the car object with a new Yokohama dependency. But when using dependency injection (DI), we can change the Wheels at runtime (because dependencies can be injected at runtime rather than at compile time).</p><p>You can think of DI as the middleman in our code who does all the work of creating the preferred wheels object and providing it to the Car class.</p><p>It makes our Car class independent from creating the objects of Wheels, Battery, etc.</p><h3>There are basically three types of dependency injection:</h3><ol><li><strong>constructor injection:</strong> the dependencies are provided through a class constructor.</li><li><strong>setter injection:</strong> the client exposes a setter method that the injector uses to inject the dependency.</li><li><strong>interface injection:</strong> the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a <a href="https://en.wikipedia.org/wiki/Setter_method">setter method</a> that accepts the dependency.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48a5ee90e94f630cdc9f5321c1feac81/href">https://medium.com/media/48a5ee90e94f630cdc9f5321c1feac81/href</a></iframe><p><strong>So now its the dependency injection’s responsibility to:</strong></p><ol><li>Create the objects</li><li>Know which classes require those objects</li><li>And provide them all those objects</li></ol><p>If there is any change in objects, then DI looks into it and it should not concern the class using those objects. This way if the objects change in the future, then its DI’s responsibility to provide the appropriate objects to the class.</p><h3>Inversion of control — the concept behind DI</h3><p>This states that a class should not configure its dependencies statically but should be configured by some other class from outside.</p><p>It is the fifth principle of <strong>S.O.L.I.D</strong> — the<strong> </strong>five basic principles of object-oriented programming and design by <a href="https://en.wikipedia.org/wiki/Robert_C._Martin"><strong>Uncle Bob</strong></a> — which states that a class should depend on abstraction and not upon concretions (in simple terms, hard-coded).</p><p>According to the principles, a class should concentrate on fulfilling its responsibilities and not on creating objects that it requires to fulfill those responsibilities. And that’s where <strong>dependency injection</strong> comes into play: it provides the class with the required objects.</p><p><em>Note: If you want to learn about </em><strong><em>SOLID </em></strong><em>principles by Uncle Bob then you can head to this </em><a href="https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design#toc-single-responsibility-principle"><em>link</em></a><em>.</em></p><h3>Benefits of using DI</h3><ol><li>Helps in Unit testing.</li><li>Boiler plate code is reduced, as initializing of dependencies is done by the injector component.</li><li>Extending the application becomes easier.</li><li>Helps to enable loose coupling, which is important in application programming.</li></ol><h3>Disadvantages of DI</h3><ol><li>It’s a bit complex to learn, and if overused can lead to management issues and other problems.</li><li>Many compile time errors are pushed to run-time.</li><li>Dependency injection frameworks are implemented with reflection or dynamic programming. This can hinder use of IDE automation, such as “find references”, “show call hierarchy” and safe refactoring.</li></ol><p>You can implement dependency injection on your own (Pure Vanilla) or use third-party libraries or frameworks.</p><h3>Libraries and Frameworks that implement DI</h3><ul><li><a href="https://www.tutorialspoint.com/spring/spring_dependency_injection.htm">Spring </a>(Java)</li><li><a href="https://github.com/google/guice">Google Guice</a> (Java)</li><li><a href="http://square.github.io/dagger/">Dagger </a>(Java and Android)</li><li><a href="https://github.com/castleproject/Windsor">Castle Windsor</a> (.NET)</li><li><a href="https://www.microsoft.com/en-us/download/details.aspx?id=39944">Unity</a>(.NET)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c734be06406" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IoC container in spring framework]]></title>
            <link>https://medium.com/@sknurhassan04/ioc-container-in-spring-framework-aac229effdfc?source=rss-c4fbf57e41b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/aac229effdfc</guid>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[ioc]]></category>
            <dc:creator><![CDATA[Sknurhassan]]></dc:creator>
            <pubDate>Sun, 11 Sep 2022 18:32:08 GMT</pubDate>
            <atom:updated>2022-09-11T18:32:08.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W5OH5fFgg5uJNntb.png" /></figure><h3>Introduction</h3><p>Today we will talk about one of the most popular frameworks in the world which is Spring, but we will focus mainly on the IoC container of this framework. In the Spring framework, the IoC container is considered as the heart of the whole framework because it’s responsible for the creation of the object, wiring the object together, configuring these objects, and handling the entire life cycle of these objects from their creation until they are completely destroyed.<br>So in the next sections, we will clarify more how the container does all those works.</p><h3>Inversion of control (IoC)</h3><p>After diving into other principles or notion we need first to understand what the IoC stands for.<br>IoC or inversion of control is a principle in software engineering by which the control of the object is transferred from the programmer into the framework especially a container, in our case the IoC container.</p><p>To understand this more, we will illustrate this principle by this example:<br>Imagine you are a programmer, and you want to write a code to solve a problem, after diving into coding you make calls to a library to work with. However, by IoC, the flow is inverted because the inversion of control enables the framework to take control of the flow of a program and make calls to your code.</p><p>Some advantages of IoC:</p><ul><li>Greater modularity of the program</li><li>Easy testing of code</li></ul><p>Spring framework implements the inversion of control through different mechanisms such as:</p><ul><li>DI (dependency injection)</li><li>Service locator pattern</li><li>Strategy design pattern</li><li>Factory pattern</li></ul><blockquote>I will talk about these mechanisms in future blogs</blockquote><h3>How does the IoC container work?</h3><p>The Spring container doesn’t know how to instantiate our object alone so to make that we need to specify a configuration metadata to our container, this configuration can be specified through the XML file, Java code, Java annotations, then the spring container uses our POJO class as well as the configuration, and he can create the beans.</p><blockquote><strong>Bean</strong>: an object that is instantiated and managed by the Spring IoC container</blockquote><p>Below, the diagram that illustrates how the container works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/0*nT89hgrWvfLInH5w.PNG" /></figure><h3>Configuration of the IoC container</h3><p>Configuration metadata represent how you, as an application developer, tell the Spring container to instantiate, configure, assemble the objects in your application.</p><p>This configuration metadata is nothing but bean definition, as we mentioned above, the metadata can be represented as:</p><ul><li><strong>XML file</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a91db0190c0e893e74788a568dd2bed/href">https://medium.com/media/0a91db0190c0e893e74788a568dd2bed/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f42b2b8e5f5712c287bf89ca8e9527f/href">https://medium.com/media/3f42b2b8e5f5712c287bf89ca8e9527f/href</a></iframe><p>In the example above, we tell the Spring container to create a Bean of the class HelloWorld and instantiate the field “message” with the value “Hello World”</p><ul><li><strong>JAVA code</strong></li></ul><p>Same things we will do but now with the java-based configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57275de60d96bd969fbd4512c274e594/href">https://medium.com/media/57275de60d96bd969fbd4512c274e594/href</a></iframe><ul><li><strong>JAVA annotations</strong></li></ul><p>Starting from Spring 2.5 it became possible to configure our class using annotations. So instead of using the XML to describe the configuration, you can move the bean configuration to the class itself by using annotations(@Component, @Autowired…)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e0cacd0d83efcff26a8a6209ead0115/href">https://medium.com/media/3e0cacd0d83efcff26a8a6209ead0115/href</a></iframe><h3>Type of containers in the spring framework</h3><p>There are two types of containers present in the Spring Framework.</p><h3>1. Spring BeanFactory Container:</h3><p>It is the simplest container present in the Spring framework which provides the basic support for DI (Dependency Injection). We use the following interface to work with this container.<br>org.springframework.beans.factory.BeanFactory</p><p>We will illustrate the implementation of this interface using the example above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3750ec6105dcd5d18b3c04c3817df802/href">https://medium.com/media/3750ec6105dcd5d18b3c04c3817df802/href</a></iframe><h3>2. Spring ApplicationContext Container:</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/597d50e08c460785b7cc3daec2cab370/href">https://medium.com/media/597d50e08c460785b7cc3daec2cab370/href</a></iframe><p>This is another container present in the spring container which adds extra enterprise-specific functionality. These functionalities include the capability to resolve textual messages from a properties file and publishing application events to the attentive event listeners. We use the following interface to work with this container.<br>org.springframework.context.ApplicationContext</p><p>if we will run these two programs, the result will be the same for both implementations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*PawXnPRyBXcCQkbk.PNG" /></figure><h3>4. BeanFactory vs ApplicationContext Container:</h3><p>The ApplicationContext container is the superset of the BeanFactory container. It means that all functionality of the BeanFactory container is present in the ApplicationContext container. Therefore, ApplicationContext container is often preferred over BeanFactory container. BeanFactory is often used to build lightweight applications such as mobile devices, applet-based applications, etc. where data volume as well as speed is important. Below are the most commonly used ApplicationContext implementations.</p><p>• FileSystemXmlApplicationContext – Here, we have to provide the full path of the XML bean configuration file to the constructor in order to load the metadata of the beans from an XML file.<br>• ClassPathXmlApplicationContext – Here, we need to set CLASSPATH of the bean configuration XML file in order to load the metadata of the beans from an XML file.<br>• WebXmlApplicationContext – Here, the container loads the XML file within a web application which has metadata of all beans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/0*X8QLaNBw6-xiaOsJ.jpg" /></figure><h3>Conclusion</h3><p>That was all for this blog, I hope you enjoy it and you understood all the points that we have touched on, if you have questions don’t hesitate to ask me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aac229effdfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSP and Servlet in Java]]></title>
            <link>https://medium.com/@sknurhassan04/jsp-and-servlet-in-java-d9a804fa7cc9?source=rss-c4fbf57e41b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9a804fa7cc9</guid>
            <category><![CDATA[servlet]]></category>
            <category><![CDATA[jsp]]></category>
            <dc:creator><![CDATA[Sknurhassan]]></dc:creator>
            <pubDate>Sun, 04 Sep 2022 18:45:55 GMT</pubDate>
            <atom:updated>2022-09-04T18:45:55.234Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In this article, we will learn about JSP and Servlet</em></p><h3>Client-Server Architecture</h3><p>When a client computer submits a data request to the server over the internet, the server accepts the request and returns the digital data required to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*62YWp6N9O7UrTjde.png" /></figure><p><strong>Client:</strong> A client is a person or an organisation that uses a specific service. A client is a computer in the digital world, capable of receiving information or using a specific service from the service providers.</p><p><strong>Server: </strong>Similarly, the term “server” refers to a person or medium who serves something. In the digital world, a server is a remote computer that provides data or access to specific services.</p><h3>Servlet</h3><p>A Java programme that runs on a Web server is known as a Servlet. They act as a link between a web browser’s request and the server’s response.</p><p>A servlet’s life cycle consists of three primary methods.</p><ol><li>The init() method</li><li>The service() method</li><li>The destroy() method</li></ol><p><strong>The init() method:</strong> There is only one call to the init method. It’s only called once when the servlet is created, and it’s never called again. It’s used for one-time initializations.</p><p><strong>The service() method:</strong> The main method for performing the actual task is the service() method. To handle requests from browsers and return responses to them, the servlet container invokes the service() method.</p><ol><li><strong>doGet(): T</strong>his method is called by servlet service method to handle the GET request from the client.</li><li><strong>doPost():</strong> This method is called by servlet service method to handle the POST request from the client.</li></ol><p><strong>The destroy() method:</strong> At the end of a servlet’s life cycle, the destroy() function is only invoked once. This method allows your servlet to conduct cleaning tasks like closing database connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*0M5Zjxv3jMt-_pWo.png" /></figure><p>Servlet Life Cycle</p><p>For example, two numbers are provided by the client and he wants to perform the addition of that two numbers. Let us see how it works internally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*oGkv9veiLgxCbu0W.png" /></figure><p>index.html</p><p>It is the interface that is provided to the client to give two number for addition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GE4QrHyh7MPSguVX.png" /></figure><p>web.xml</p><p>As soon as the client clicks on submit button, it will find which servlet is specified for this request and this will is done in the web.xml file. After that servlet will be called and the processing of the request will start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*eP_iX200Ukl4klUM.png" /></figure><p>AddServlet.java</p><p>After this client will receive a response on his/her browser.</p><h3>JSP (Java Server Pages)</h3><p>JSP stands for JavaServer Pages, and it’s a technology for creating dynamic Web pages. This allows developers to embed java code in HTML pages by using specific JSP tags, the majority of which begin with &lt;% and end with % &gt;. The only benefit of JSP is that it is simple to write JSP code for developers.</p><p>JSP is internally converted into a servlet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*OfAcaT53C8wzQgzo.png" /></figure><p>JSP conversion</p><p>Servlets are designed for dynamic web content, after all. However, there is no effective way to represent dynamic web content on a web page using Servlets. There are so many that we need to write down out.print() statements. There can’t be simply one web page in a web application. It’s a collection of web pages, actually. It is not suggested to create web pages in this manner.</p><p><strong>Scriptlet tag: </strong>Whatever is written into this tag is converted into a service function in the servlet. The business logic is written into this.</p><pre>&lt;%  java source code %&gt;</pre><p><strong>Directive tag:</strong> This element is used to declare anything that is used by the entire page, such as importing a file.</p><pre>&lt;%@ directive attribute=&quot;value&quot; %&gt;</pre><p><strong>Declarative tag:</strong> This tag is used to declare all variables and statements outside of the service function but within the class.</p><pre><strong>&lt;</strong>%!  field or method declaration %<strong>&gt;</strong></pre><p><strong>Expression tag: </strong>Everything inside this tag is printed on the screen.</p><pre><strong>&lt;</strong>%=  statement %<strong>&gt;</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9a804fa7cc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Normalization in Database (With Example)]]></title>
            <link>https://medium.com/@sknurhassan04/normalization-in-database-with-example-207a58985723?source=rss-c4fbf57e41b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/207a58985723</guid>
            <category><![CDATA[normalization-in-dbms]]></category>
            <dc:creator><![CDATA[Sknurhassan]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 03:53:19 GMT</pubDate>
            <atom:updated>2022-08-29T03:53:19.255Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Is Normalization in SQL?</h3><p>Normalization is the process to eliminate data redundancy and enhance data integrity in the table. Normalization also helps to organize the data in the database. It is a multi-step process that sets the data into tabular form and removes the duplicated data from the relational tables.</p><p>Normalization organizes the columns and tables of a database to ensure that database integrity constraints properly execute their dependencies. It is a systematic technique of decomposing tables to eliminate data redundancy (repetition) and undesirable characteristics like Insertion, Update, and Deletion anomalies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*q62FU0jyTf6ac8sMhnX4ig.jpeg" /><figcaption>Types of Normalization</figcaption></figure><h3>1st Normal Form (1NF)</h3><ul><li>A table is referred to as being in its First Normal Form if atomicity of the table is 1.</li><li>Here, atomicity states that a single cell cannot hold multiple values. It must hold only a single-valued attribute.</li><li>The First normal form disallows the multi-valued attribute, composite attribute, and their combinations.</li></ul><p>Now you will understand the First Normal Form with the help of an example.</p><p>Below is a students’ record table that has information about student roll number, student name, student course, and age of the student.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/0*AmdCFZZ-_ZsOgA1J.png" /></figure><p>In the studentsrecord table, you can see that the course column has two values. Thus it does not follow the First Normal Form. Now, if you use the First Normal Form to the above table, you get the below table as a result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/0*NL329iCBdSCm8WKZ.png" /></figure><p>By applying the First Normal Form, you achieve atomicity, and also every column has unique values.</p><p>Before proceeding with the Second Normal Form, get familiar with Candidate Key and Super Key.</p><h3>Candidate Key</h3><p>A candidate key is a set of one or more columns that can identify a record uniquely in a table, and YOU can use each candidate key as a <a href="https://www.simplilearn.com/tutorials/sql-tutorial/primary-key-in-sql">Primary Key.</a></p><p>Now, let’s use an example to understand this better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/0*w-kQ1W6mSrClU2ot.png" /></figure><h3>Super Key</h3><p>Super key is a set of over one key that can identify a record uniquely in a table, and the Primary Key is a subset of Super Key.</p><p>Let’s understand this with the help of an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*ZUQS2P9CNt5rKrO5.png" /></figure><h3>Second Normal Form (2NF)</h3><p>The first condition for the table to be in Second Normal Form is that the table has to be in First Normal Form. The table should not possess partial dependency. The partial dependency here means the proper subset of the candidate key should give a non-prime attribute.</p><p>Now understand the Second Normal Form with the help of an example.</p><p>Consider the table Location:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/0*mnsGG4MTpHaezUci.png" /></figure><p>The Location table possesses a composite primary key cust_id, storeid. The non-key attribute is store_location. In this case, store_location only depends on storeid, which is a part of the primary key. Hence, this table does not fulfill the second normal form.</p><p>To bring the table to Second Normal Form, you need to split the table into two parts. This will give you the below tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/0*Cqie0nHkqHZ-MZ31.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*xebi0SQFim1ezlDu.png" /></figure><p>As you have removed the partial functional dependency from the location table, the column store_location entirely depends on the primary key of that table, storeid.</p><p>Now that you understood the 1st and 2nd Normal forms, you will look at the next part of this Normalization in SQL tutorial.</p><h3>Third Normal Form (3NF)</h3><ul><li>The first condition for the table to be in Third Normal Form is that the table should be in the Second Normal Form.</li><li>The second condition is that there should be no transitive dependency for non-prime attributes, which indicates that non-prime attributes (which are not a part of the candidate key) should not depend on other non-prime attributes in a table. Therefore, a transitive dependency is a functional dependency in which A → C (A determines C) indirectly, because of A → B and B → C (where it is not the case that B → A).</li><li>The third Normal Form ensures the reduction of data duplication. It is also used to achieve data integrity.</li></ul><p>Below is a student table that has student id, student name, subject id, subject name, and address of the student as its columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/0*PsJ8v3aSg9Dkfnze.png" /></figure><p>In the above student table, stu_id determines subid, and subid determines sub. Therefore, stu_id determines sub via subid. This implies that the table possesses a transitive functional dependency, and it does not fulfill the third normal form criteria.</p><p>Now to change the table to the third normal form, you need to divide the table as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/0*t5SiOXXdJch9PoL2.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/0*PYV_OAzkN6VvHGao.png" /></figure><p>As you can see in both the tables, all the non-key attributes are now fully functional, dependent only on the primary key. In the first table, columns name, subid, and addresses only depend on stu_id. In the second table, the sub only depends on subid.</p><h3>Boyce CoddNormal Form (BCNF)</h3><p>Boyce Codd Normal Form is also known as 3.5 NF. It is the superior version of 3NF and was developed by Raymond F. Boyce and Edgar F. Codd to tackle certain types of anomalies which were not resolved with 3NF.</p><p>The first condition for the table to be in Boyce Codd Normal Form is that the table should be in the third normal form. Secondly, every Right-Hand Side (RHS) attribute of the functional dependencies should depend on the super key of that particular table.</p><p>For example :</p><p>You have a functional dependency X → Y. In the particular functional dependency, X has to be the part of the super key of the provided table.</p><p>Consider the below subject table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/0*yx7l4u2nHSMJwd1X.png" /></figure><p>The subject table follows these conditions:</p><ul><li>Each student can enroll in multiple subjects.</li><li>Multiple professors can teach a particular subject.</li><li>For each subject, it assigns a professor to the student.</li></ul><p>In the above table, student_id and subject together form the primary key because using student_id and subject; you can determine all the table columns.</p><p>Another important point to be noted here is that one professor teaches only one subject, but one subject may have two professors.</p><p>Which exhibit there is a dependency between subject and professor, i.e. subject depends on the professor’s name.</p><p>to</p><p>The table is in 1st Normal form as all the column names are unique, all values are atomic, and all the values stored in a particular column are of the same domain.</p><p>The table also satisfies the 2nd Normal Form, as there is no Partial Dependency.</p><p>And, there is no Transitive Dependency; hence, the table also satisfies the 3rd Normal Form.</p><p>This table follows all the Normal forms except the Boyce Codd Normal Form.</p><p>As you can see stuid, and subject forms the primary key, which means the subject attribute is a prime attribute.</p><p>However, there exists yet another dependency — professor → subject.</p><p>BCNF does not follow in the table as a subject is a prime attribute, the professor is a non-prime attribute.</p><p>To transform the table into the BCNF, you will divide the table into two parts. One table will hold stuid which already exists and the second table will hold a newly created column profid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/0*bIXHzVRHRVsSfeV9.png" /></figure><p>And in the second table will have the columns profid, subject, and professor, which satisfies the BCNF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*tXcySpYJXh4tGwYf.png" /></figure><p>With this, you have reached the conclusion of the ‘Normalization in SQL’ tutorial.</p><blockquote><em>Gain expertise in the latest Business analytics tools and techniques with the Post Graduate Program in Business Analysis. Enroll now!</em></blockquote><h3>Conclusion</h3><p>In this tutorial, you have seen Normalization in SQL and understood the different Normal forms of Normalization. Now, you can organize the data in the database and remove the data redundancy and promote data integrity. This tutorial also helps beginners for their interview processes to understand the concept of Normalization in SQL.</p><p>If you have any questions or inputs for our editorial team regarding this “The Supreme Guide to Normalization in SQL” tutorial, do share them in the comments section below. Our team will review them and help solve them for you very soon!</p><p>To get certified in SQL and start your career in it, check this course link: <a href="https://www.simplilearn.com/sql-database-training-course?source=GhPreviewCoursepages">SQL Training</a>.</p><p>Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=207a58985723" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A short summary of JAVA Codding Standards]]></title>
            <link>https://medium.com/@sknurhassan04/a-short-summary-of-java-codding-standards-1a7f69ec36b1?source=rss-c4fbf57e41b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a7f69ec36b1</guid>
            <dc:creator><![CDATA[Sknurhassan]]></dc:creator>
            <pubDate>Mon, 15 Aug 2022 12:14:23 GMT</pubDate>
            <atom:updated>2022-08-15T12:14:23.228Z</atom:updated>
            <content:encoded><![CDATA[<p>Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hGVZhDshIAXY2SnX.jpg" /></figure><h3>Why Coding Guidelines?</h3><p>The coding guidelines are important because most of the software cost goes towards maintenance. And also, the software is not always developed by a single developer. Therefore, maintaining a convention for writing software increases the readability of the program.</p><p><strong>A few of the guidelines are:</strong></p><h3><strong>1. Naming Conventions:</strong></h3><blockquote><strong>Basic Coding Rules to Follow</strong></blockquote><blockquote>Use descriptive and appropriate names for all identifiers (variables, method names, class names, constants, etc.).</blockquote><blockquote><strong>Identifier Naming and Capitalization</strong></blockquote><blockquote>1. Use descriptive names for all variables, function names, constants, and other identifiers.</blockquote><blockquote>2. Use single letter identifiers only for the counter in loops.</blockquote><blockquote>3. Class names start with an upper case letter.</blockquote><blockquote>4. Variable names start with a lower case letter. (Variables include parameters, local variables, and data fields. Exception: use UPPER_CASE for constants — final variables.)</blockquote><blockquote>5. Method names start with a lower case letter.</blockquote><blockquote>6. Multi-word identifiers are internally capitalized.</blockquote><blockquote>7. Do not use hyphens or underscores to separate multi-word identifiers (except for constants, which have all upper case letters).</blockquote><blockquote><strong>Example</strong></blockquote><blockquote>float sumOfSquares = 0;<br>final int DAYS_IN_YEAR = 365; //Use UPPER_CASE for constants (final variables)</blockquote><blockquote>Counter Example</blockquote><blockquote>float Sum = 0;<br>float sumofsquares = 0;<br>float sum_of_squares = 0;<br>float x = 0;</blockquote><h3><strong>2. Curly Braces</strong></h3><blockquote>Curly braces are used to define the bodies of classes, methods, and loops. There are two standard formats for the usage of curly braces, either of which is used.</blockquote><blockquote>No blank lines should be present after the opening brace or before the closing brace.</blockquote><blockquote>A curly brace is applied at the end of the line that starts the class, method, loop, etc., and the closing brace is on a line by itself, lined up vertically with the start of the first line. For example:</blockquote><pre>class Geeksforgeeks {<br>   ... Geeksforgeeks(){<br>    // Constructor<br>       ...<br>   }<br><br>   int Geek(int a, float b){<br>   <br>       ... for (int i = 0; i &lt; Field; i++){<br>           ....<br>       }<br>   }<br>}</pre><ul><li>Each curly brace is added on a new line, and the pair is aligned vertically. The preceding code snippet in this format would be as follows:</li></ul><pre>class Geeksforgeeks  <br>{<br>   ... Geeksforgeeks()<br>   { // Constructor<br>       ...<br>   }<br>   int Geek(int a, float b)<br>   {<br>       ... for (int i = 0; i &lt; Field; i++)<br>       {<br>           ....<br>       }...;<br>   }<br>}</pre><h3><strong>3. Indentation</strong></h3><blockquote>The unit of indentation should be 4 spaces. Tab-stops should be set exactly every 8 spaces. All indentation must be achieved by the space character and tab characters must not exist in the resultant source file. The recognized standard for increasing readability of each line is:</blockquote><blockquote>1. Apply indentation to alike items in a vertical list (such as end-of-line comments, and identifiers in declarations).</blockquote><blockquote>2. Surround the binary operators (including assignment) by spaces.</blockquote><blockquote>3. Follow a semicolon or comma by a space.</blockquote><blockquote>4. Add a space between a keyword(“if”, “while”, “return”, “catch”, “switch”, “for”) and a succeeding parenthesis.</blockquote><blockquote>5. Surplus parentheses can also help to highlight the structure of expressions (but avoid using too many nested parentheses).</blockquote><blockquote>6. Insert blank lines to differentiate between the important parts of the code.</blockquote><blockquote>Let’s implement all the above guidelines in a code:</blockquote><pre>class Geeksforgeeks {<br>   private int s;<br>   private double d;</pre><pre>   Geeksforgeeks()<br>   { // Constructor<br>       s = 1;<br>       d = 3.14;<br>   }</pre><pre>   int Geek(int a, float b)<br>   {<br>       // Must initialize local variables<br>       int l = 0;<br>       float le = 1;<br>       int n = 10;<br>       l = n - 2;<br>       le = l + b * 3;</pre><pre>       for (int i = 0; i &amp; lt; n; i++) {<br>           l = l * 2;<br>           l = l - n;<br>       }<br>       return l + a;<br>   }<br>}</pre><p><strong>4. White Space:</strong> White spaces also play a major part in readability as follows:</p><ul><li><a href="https://www.geeksforgeeks.org/operators-in-java/">Operators</a> should be surrounded by a space character. For example:</li></ul><blockquote><em>The operation should be written as: <br></em><strong><em>a = (b + c) * d;</em></strong><em><br>And not as: <br></em><strong><em>a=(b+c)*d</em></strong></blockquote><ul><li><a href="https://www.geeksforgeeks.org/list-of-all-java-keywords/">Reserved words of Java</a> should be followed by white space. For example:</li></ul><blockquote><em>The loop must be initialized as: <br>while (true) {…} <br>And not as: <br>while(true){…}</em></blockquote><ul><li>Commas should be followed by white space. For example:</li></ul><blockquote><em>The functions must be initialized as: <br>fun(a, b, c, d); <br>And not as: <br>fun(a, b, c, d);</em></blockquote><ul><li>Colons should be surrounded by white space. For example:</li></ul><blockquote><em>The case statements must be initialized as: <br>case 100 : break; <br>And not as: <br>case 100:break;</em></blockquote><ul><li><a href="https://www.geeksforgeeks.org/role-of-semicolon-in-various-programming-languages/">Semicolons</a> in for statements should be followed by a space character. For example:</li></ul><blockquote><em>The for loop must be initialized as: <br>for (i = 0; i &lt; n; i++) <br>And not as: <br>for(i=0;i&lt;n;i++)</em></blockquote><p><strong>5. </strong><a href="https://www.geeksforgeeks.org/comments-in-java/"><strong>Comments</strong></a><strong>:</strong> Java programs can have two types of comments. They are Implementation and Documentation. Comments should contain only the information that is relevant for reading and understanding the program. For example, information about how the package is built or in what directory it resides should not be included in the program as a comment.</p><ul><li><strong>Implementation Comments:</strong> Implementation comments are delimited by <strong>//</strong>. Java also allows the use of /*…*/ for implementation comments. Implementation comments are used for notes about a particular implementation or for temporarily removing code. Programs can have four styles of implementation comments: block, single-line, trailing, and temporarily removing code.</li><li><strong>Block comments</strong> are used to provide descriptions of files, methods, data structures, and algorithms. Block comments may be used at the beginning of each file and before each method or within methods. Block comments inside a method should be indented to the same level as the code they describe. A block comment should have a blank line before its start unless it comes immediately after the start of a compound statement. For example:</li></ul><blockquote><em>// block comment on line 1 <br>// block comment on line 2 <br>// block comment on line 3</em></blockquote><ul><li><strong>Single-line comments</strong> can appear on a single line indented to the level of the code that follows. If a comment can not be written in a single line, it should follow the block comment format. A single-line comment should be preceded by a blank line unless it comes immediately after the start of a compound statement. For example:</li></ul><blockquote><em>a = 10; <br>b = 20;<br>// a single-line comment <br>c = a * b;</em></blockquote><ul><li><strong>Trailing(very short) comments</strong> can appear on the same line of the code they describe but should be separated from the code at a far off distance. If more than one short comment appears in a section of related code, they should all be indented to the same tab setting. For example:</li></ul><pre>if (a == 2) {<br>   b = true; // special case<br>}<br>else {<br>   c = isPrime(x); // works only for odd<br>}</pre><ul><li><strong>Temporarily removing code:</strong> The // delimiter can comment out a partial or a complete line. It can also be used in multiple lines to comment out entire sections of code. It is important to note that this should only be used temporarily while the code is in active development; the unused code should eventually be physically removed as it can make the source more difficult to maintain. For example:</li></ul><pre>if (a &gt; 1) {<br>b = a; // + 1;<br>...<br>}<br>else {<br>// b = 2;<br>...<br>}</pre><ul><li><strong>Documentation Comments:</strong> Documentation comments describe <a href="https://www.geeksforgeeks.org/classes-objects-java/">Java classes</a>, <a href="https://www.geeksforgeeks.org/interfaces-in-java/">interfaces</a>, <a href="https://www.geeksforgeeks.org/constructors-in-java/">constructors</a>, <a href="https://www.geeksforgeeks.org/methods-in-java/">methods</a>, and fields. They are delimited by <strong>/**…*/</strong>. Note the double-asterisk (**) at the beginning with one comment per class, interface, or member. This comment should appear just before the declaration with no space between the comment and the code it refers to. Documentation comments can be extracted to HTML files using the <em>javadoc</em> tool. Javadoc of class members can be specified on a single line as follows:</li></ul><blockquote>/** This is a java documentation comment */<em><br></em>private int comments_;</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a7f69ec36b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Git…]]></title>
            <link>https://medium.com/@sknurhassan04/an-introduction-to-git-b7494a5d607e?source=rss-c4fbf57e41b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7494a5d607e</guid>
            <dc:creator><![CDATA[Sknurhassan]]></dc:creator>
            <pubDate>Sat, 06 Aug 2022 20:05:25 GMT</pubDate>
            <atom:updated>2022-08-06T20:05:25.157Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is git?</h3><blockquote>Git is a mature, actively maintained open source project originally developed in 2005 by Linus Torvalds, the famous creator of the Linux operating system kernel.<br>It is a distributed version control system for tracking changes in source code during software development. It is designed for coordinating work among programmers, but it can be used to track changes in any set of files. Its goals include speed, data integrity, and support for distributed, non-linear workflows.</blockquote><h3><strong>Features of Git</strong></h3><p><strong><em>High performance</em></strong></p><p><em>The raw performance characteristics. of Git are very strong when compared. to many alternatives. Committing new. changes, branching, merging and. comparing past versions are all. optimized for performance</em></p><p><strong><em>Secure</em></strong></p><p><em>Git has been designed with the integrity.of managed source code as a top priority. The content of the files as. well as the true relationships between files and directories, versions, tags and. commits, all of these objects in the Git repository are secured with a </em>cryptographically<em> secure hashing algorithm called SHA1.</em></p><p><strong><em>Flexible</em></strong></p><p><em>One of Git’s key design objectives is flexibility Git has been designed to support branching and tagging as first- class citizens (unlike SVN) and operations that affect branches and tags (such as merging or reverting) are also stored as part of the change history. Not all version control systems feature this level of tracking.</em></p><h3><strong>Version control with Git</strong></h3><p>Git is the best choice for most software teams today. While every team is different and should do their own analysis, here are the main reasons why version control with Git s preferred over alternatives:</p><p>Git is Good.</p><p>Git is de factor standard.</p><p>Git is a quality open source project.</p><h3>What is GitHub?</h3><blockquote>GitHub is a web-based Git repository hosting service, which offers all of the distributed revision control and source code management (SCM) functionality of Git as well as adding its own features.</blockquote><h3>So what are the main benefits of using GitHub?</h3><p>1. It makes it easy to contribute to your open source projects.<br> 2. Documentation.<br> 3. Showcase your work.<br> 4. Markdown.<br> 5. GitHub is a repository.<br> 6. Track changes in your code across versions.<br> 7. Integration options.</p><p>Git is software that works locally, your files and the revision history are stored on your computer. You can also use Github online hosts to store a copy of the files and their revision history</p><h3>Git and GitHub are not the same…</h3><h3>Git installation</h3><pre>sudo apt install git</pre><h3><strong>Basic Git workflow</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tl0aFOU_L6Xh0X1VWZ1wg.png" /><figcaption>Basic Git workflow</figcaption></figure><p><strong>Git workflow consists of</strong></p><ul><li>A working local directory: It is the local directory your working on</li><li>A Staging area: It is the area where you add changes you make to the working directory</li><li>A Repository: It is the place where Git permanently stores the changes</li></ul><h3><strong>How to create a Git repository ?</strong></h3><p>When you want to create a new project on your computer using git, the first thing you do is create a new repository.</p><p>To create the repository, open up a terminal and move to where you want to place the project on your computer using the cd (change directory) command.</p><p>For example, if you want to create your project folder on your desktop, you will do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ceb410a9d256dd669669da9aac2b0bf/href">https://medium.com/media/7ceb410a9d256dd669669da9aac2b0bf/href</a></iframe><h3><strong>Useful CLI commands</strong></h3><blockquote><strong><em>cd [directory-name]</em></strong><em> — moves to the given directory name</em></blockquote><blockquote><strong><em>mkdir [directory-name]</em></strong><em> — makes a new directory with the given name</em></blockquote><h3><strong>Here is some commands to use Git like a pro</strong></h3><pre>git init</pre><blockquote>This will create a hidden .git folder in your project folder on your computer. <strong>.git</strong> folder is the repository where it stores all the changes you make to any files within the project folder.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*TwyotRLOLbHxzEw0QFl4rA.png" /></figure><pre>git status</pre><p>List which files are staged, unstaged, and untracked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*k8fuw0YYi7q98lUId2Iyfg.png" /></figure><pre>git add &lt;file name&gt;</pre><p>The git add command adds a change in the working directory specific file to the staging area. It tells Git that you want to include updates to a particular file in the next commit. However, git add doesn&#39;t really affect the repository in any significant way—changes are not actually recorded until you run git commit.</p><pre>git add -A</pre><p>git add -A add all files to staging area.</p><pre>git commit</pre><p>Since we have finished our work, <strong>we are ready move from </strong>stage<strong> to </strong>commit<strong> for our repository</strong></p><pre>git log</pre><p>The git log command <strong>displays all of the commits in a repository’s history</strong></p><pre>git log -p</pre><p>Show <strong>all the changes </strong>of all files</p><pre>git -p &lt;number of file&gt;</pre><p>Show us all the changes of <strong>given numbers</strong> of files</p><pre>git diff</pre><p>This command<strong> compare</strong> a file with <strong>modified</strong> area to <strong>staged</strong> area.</p><pre>git diff --staged</pre><p>Compare <strong>staging </strong>area to <strong>last commit</strong>.</p><pre>git rm --cached &lt;file name&gt;</pre><p><strong>Remove</strong> the file from the <strong>commit</strong> area</p><pre>git branch &lt;branch name&gt;</pre><p><strong>Create</strong> a new branch.</p><pre>git checkout &lt;branch name&gt;</pre><p><strong>Switch </strong>to given branch from current branch.</p><pre>git merge</pre><p><strong>Merge</strong> the current branch to given branch.</p><pre>git branch -b &lt;branch name&gt;</pre><p>Branch is <strong>created and switched</strong> to the branch.</p><h3><strong>.gitignore</strong></h3><p>When you make commits in a git repository, you choose which files to stage and commit by using git add FILENAME and then git commit. But what if there are some files that you never want to commit? It&#39;s too easy to accidentally commit them (especially if you use git add . to stage all files in the current directory). That&#39;s where a .gitignore file comes in handy. It lets Git know that it should ignore certain files and not track them.</p><h3>What Kind of Files Should You Ignore?</h3><ul><li>Log files</li><li>Files with API keys/secrets, credentials, or sensitive information</li><li>Useless system files like .DS_Store on macOS</li><li>Generated files like dist folders</li><li>Dependencies which can be downloaded from a package manager</li><li>And there might be other reasons (maybe you make little todo.md files)</li></ul><h3><strong>Git with Github</strong></h3><p><strong>How to push a repository in Github ??</strong></p><p>First create a repository in Github.</p><pre>git remote add &lt;origin name&gt;</pre><p><strong>Create</strong> origin by which you can <strong>fetch and push</strong> your repository.</p><pre>git remote</pre><p>Show <strong>how much</strong> origin is saved.</p><pre>git remote -v</pre><p><strong>show name and URL</strong> of origin.</p><pre>git push &lt;origin name&gt; &lt;branch name&gt;</pre><p><strong>Push</strong> your repository branch to the given origin. Congrats you pushed your repository to Github.</p><pre>git pull &lt;origin name&gt;</pre><p><strong>Pull </strong>the repository.</p><pre>git clone</pre><p>This will download the repository from GitHub to your computer with the latest snapshot of the repository to your project folder..</p><pre>git fetch</pre><p>This will <strong>download the latest info </strong>about the repository from origin .</p><h3><strong>The Bottom Line</strong></h3><p>It’s free and you’ve got nothing to lose, so if you’re even a little bit curious, try it out. Once you get the hang of the architecture, you’ll realize that it’s really quite simple and elegant. There’s something very satisfying about understanding every detail of your blog engine and having the control to make it your own. In the process, you’ll pick up some technical skills that will serve you for the rest of your web career.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7494a5d607e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>