Friday, April 14, 2023

Code practise : Good and Bad

  1. Follow naming conventions:
  2. arduino
    // Bad: int a; int x1; // Good: int age; int numberOfCustomers;
    1. Use comments:
    arduino
    // Bad: int result = 10 / 0; // Divide by zero // Good: // Divide the dividend by the divisor and return the result. // Throws DivideByZeroException if divisor is zero. int Divide(int dividend, int divisor) { if (divisor == 0) { throw new DivideByZeroException("Divisor cannot be zero."); } return dividend / divisor; }
    1. Keep your code clean and organized:
    c
    // Bad: int a=10,b=20,c=30,d=40;string name="John"; // Good: int a = 10; int b = 20; int c = 30; int d = 40; string name = "John";
    1. Use exception handling:
    arduino
    // Bad: int result = 10 / 0; // throws DivideByZeroException and crashes the program // Good: try { int result = 10 / 0; } catch (DivideByZeroException ex) { Console.WriteLine("Divide by zero error: " + ex.Message); }
    1. Use object-oriented programming principles:
    csharp
    // Bad: public int Add(int a, int b) { return a + b; } // Good: public interface IAddable { int Add(int a, int b); } public class Calculator : IAddable { public int Add(int a, int b) { return a + b; } }
    1. Write efficient code:
    scss
    // Bad: for (int i = 0; i < myList.Count; i++) { Console.WriteLine(myList[i]); } // Good: foreach (var item in myList) { Console.WriteLine(item); }
    1. Test your code thoroughly:
    csharp
    // Bad: public int Add(int a, int b) { return a + b; } // Good: [TestClass] public class CalculatorTests { [TestMethod] public void TestAdd() { Calculator calc = new Calculator(); int result = calc.Add(2, 3); Assert.AreEqual(5, result); } }

    By following these coding practices, you can write clean, maintainable, and efficient C# code that is easy to read and understand, and that works as expected.

Complete Authentication System in ASP.NET Core using JWT

JWT (JSON Web Token) authentication is widely used for securing APIs in modern applications. In this article, we will build a complete authe...