برچسب: Functions

  • small functions bring smarter exceptions | Code4IT

    small functions bring smarter exceptions | Code4IT


    Smaller functions help us write better code, but have also a nice side effect: they help us to understand where an exception was thrown. Let’s see how!

    Table of Contents

    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    Small functions not only improve your code readability but also help to debug faster your applications in case of unhandled exceptions.

    Take as an example the program listed below: what would happen if a NullReferenceException is thrown? Would you be able to easily understand which statement caused that exception?

    static void Main()
    {
    	try
    	{
    		PrintAllPlayersInTeam(123);
    
    	}
    	catch (Exception ex)
    	{
    		Console.WriteLine(ex.Message);
    		Console.WriteLine(ex.StackTrace);
    	}
    
    }
    
    public static void PrintAllPlayersInTeam(int teamId) {
    
    	Feed teamFeed = _sportClient.GetFeedForTeam(teamId);
    	Team currentTeam = _feedParser.ParseTeamFeed(teamFeed.Content.ToLower());
    
    	Feed playerFeed = _sportClient.GetPlayersFeedForTeam(currentTeam.TeamCode.ToUpper());
    
    	var players = _feedParser.ParsePlayerFeed(playerFeed.Content.ToLower()).ToList();
    
    	foreach (var player in players)
    	{
    		string report = "Player Id:" + player.Id;
    		report += Environment.NewLine;
    		report += "Player Name: " + player.FirstName.ToLower();
    		report += Environment.NewLine;
    		report += "Player Last Name: " + player.LastName.ToLower();
    
    		Console.WriteLine(report);
    	}
    
    }
    

    With one, single, huge function, we lose the context of our exception. The catch block intercepts an error that occurred in the PrintAllPlayersInTeam function. But where? Maybe in teamFeed.Content.ToLower(), or maybe in player.FirstName.ToLower().

    Even the exception’s details won’t help!

    Exception details in a single, huge function

    Object reference not set to an instance of an object.
       at Program.PrintAllPlayersInTeam(Int32 teamId)
       at Program.Main()
    

    Yes, it says that the error occurred in the PrintAllPlayersInTeam. But where, exactly? Not a clue!

    By putting all together inside a single function, PrintAllPlayersInTeam, we are losing the context of our exceptions.

    So, a good idea is to split the method into smaller, well-scoped methods:

    static void Main()
    {
    	try
    	{
    		PrintAllPlayersInTeam(123);
    	}
    	catch (Exception ex)
    	{
    		Console.WriteLine(ex.Message);
    		Console.WriteLine(ex.StackTrace);
    	}
    
    }
    
    public static void PrintAllPlayersInTeam(int teamId)
    {
    	Team currentTeam = GetTeamDetails(teamId);
    
    	var players = GetPlayersInTeam(currentTeam.TeamCode);
    
    	foreach (var player in players)
    	{
    		string report = BuildPlayerReport(player);
    
    		Console.WriteLine(report);
    	}
    
    }
    
    public static string BuildPlayerReport(Player player)
    {
    	string report = "Player Id:" + player.Id;
    	report += Environment.NewLine;
    	report += "Player Name: " + player.FirstName.ToLower();
    	report += Environment.NewLine;
    	report += "Player Last Name: " + player.LastName.ToLower();
    
    	return report;
    }
    
    public static Team GetTeamDetails(int teamId)
    {
    	Feed teamFeed = _sportClient.GetFeedForTeam(teamId);
    	Team currentTeam = _feedParser.ParseTeamFeed(teamFeed.Content.ToLower());
    	return currentTeam;
    }
    
    public static IEnumerable<Player> GetPlayersInTeam(string teamCode)
    {
    	Feed playerFeed = _sportClient.GetPlayersFeedForTeam(teamCode.ToUpper());
    
    	var players = _feedParser.ParsePlayerFeed(playerFeed.Content.ToLower()).ToList();
    	return players;
    }
    

    Of course, this is not a perfect code, but it give you the idea!.

    As you can see, I’ve split the PrintAllPlayersInTeam method into smaller ones.

    If now we run the code again, we get a slightly more interesting stack trace:

    Object reference not set to an instance of an object.
       at Program.GetTeamDetails(Int32 teamId)
       at Program.PrintAllPlayersInTeam(Int32 teamId)
       at Program.Main()
    

    Now we know that the exception is thrown on the GetTeamDetails method, so we reduced the scope of our investigations to the following lines:

    Feed teamFeed = _sportClient.GetFeedForTeam(teamId);
    Team currentTeam = _feedParser.ParseTeamFeed(teamFeed.Content.ToLower());
    return currentTeam;
    

    It’s easy to understand that the most probable culprits are teamFeed and teamFeed.Content!

    Of course, you must not exaggerate! Don’t create a method for every single operation you do: in that way, you’ll just clutter the code without adding any value.

    Downsides

    Yes, adding new functions can slightly impact the application performance. In fact, every time we call a function, a stack operation is performed. This means that the more nested methods we call, the more stack operations we perform. But does it really impact the application performance? Or is it better to write cleaner code, even if we lose some nanoseconds? If you want to see the different standpoints, head to my article Code opinion: performance or clean code?

    Conclusion

    Writing smaller functions not only boosts the code readability but also helps us debug faster (and smarter). As usual, we must not move every statement in its own function: just find the right level of readability that works for you.

    👉 Let’s discuss it on Twitter or on the comment section below!

    🐧





    Source link

  • Top 10 JavaScript Array Functions.

    Top 10 JavaScript Array Functions.


    Unlocking the Power of JavaScript: The Top 10 Array Functions You Need to Know.

    JavaScript, the language that breathes life into web pages, has a powerful array of functions that can transform your code into elegant, efficient, and concise masterpieces. Whether you’re a seasoned developer or just starting, mastering these functions will elevate your coding skills and streamline your workflow.

    In this blog post, we dive into the top 10 JavaScript array functions every developer should have in their toolkit. From transforming data with map() and filter() to perform complex operations reduce(), we’ll explore each function with examples and best practices. Join us on this journey as we unlock the potential of JavaScript arrays and take your coding abilities to the next level.

    Here are the top 10 JavaScript array functions that are widely used due to their efficiency and versatility:

    1. map():

    • Purpose: Creates a new array by applying a callback function to each element of the original array.
    • Example:
    const numbers = [2, 3, 4, 5];
    const squared = numbers.map(x => x * x);
    console.log(squared);
    

    2. filter():

    • Purpose: Creates a new array with all elements that pass the test implemented by the provided callback function.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const evens = numbers.filter(x => x % 2 === 0);
    console.log(squared);
    

    3.reduce():

    • Purpose: Executes a reducer function on each element of the array, resulting in a single output value.It integrate a whole array into a single value using a callback function.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const sum = numbers.reduce((total, num) => total + num, 0); 
    console.log(sum); 
    

    4.forEach():

    • Purpose: Executes a provided function once for each array element.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    numbers.forEach(x => console.log(x));
    

    5.find():

    • Purpose: Returns the value of the first element in the array that satisfies the provided testing function.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const firstEven = numbers.find(x => x % 2 === 0);
    console.log(firstEven);
    output: 2

    6.some():

    • Purpose: Tests whether at least one element in the array passes the test implemented by the provided callback function. 
    • Example:
    const numbers = [2, 3, 4, 5];
    const hasEven = numbers.some(x => x % 2 === 0);
    console.log(hasEven); output: true

    7.every():

    • Purpose: Tests whether all elements in the array pass the test implemented by the provided function.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const allEven = numbers.every(x => x % 2 === 0);
    console.log(allEven); output: false

    8.includes():

    • Purpose: Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const hasNumber = numbers.includes(5);
    console.log(hasNumber); output: false

    9.push():

    • Purpose: Adds one or more elements to the end of an array and returns the new length of the array.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    numbers.push(6);
    console.log(hasNumber); output: [2, 3, 4, 5,6];

    10.slice():

    • Purpose: Returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const subArray = numbers.slice(1, 3); 

    These functions are fundamental tools in JavaScript programming, enabling you to manipulate and traverse arrays effectively.

    JavaScript Program To Check Whether a String is Palindrome or Not.      Binary Gap In Javascript.



    Source link

  • Trigonometric Functions – Sine – Useful code


    import numpy as np

    import matplotlib.pyplot as plt

    import matplotlib.animation as animation

     

    # Generate unit circle points

    theta = np.linspace(0, 2 * np.pi, 1000)

    x_circle = np.cos(theta)

    y_circle = np.sin(theta)

     

    # Initialize figure

    fig, ax = plt.subplots(figsize=(8, 8))

    ax.plot(x_circle, y_circle, ‘b-‘, label=“Unit Circle”)  # Unit circle

    ax.axhline(0, color=“gray”, linestyle=“dotted”)

    ax.axvline(0, color=“gray”, linestyle=“dotted”)

     

    # Add dynamic triangle components

    triangle_line, = ax.plot([], [], ‘r-‘, linewidth=2, label=“Triangle Sides”)

    point, = ax.plot([], [], ‘ro’)  # Moving point on the circle

     

    # Text for dynamic values

    dynamic_text = ax.text(0.03, 0.03, “”, fontsize=12, color=“black”, ha=“left”, transform=ax.transAxes)

     

    # Set up axis limits and labels

    ax.set_xlim(1.2, 1.2)

    ax.set_ylim(1.2, 1.2)

    ax.set_title(“Sine as a Triangle on the Unit Circle”, fontsize=14)

    ax.set_xlabel(“cos(θ)”, fontsize=12)

    ax.set_ylabel(“sin(θ)”, fontsize=12)

    ax.legend(loc=“upper left”)

     

    # Animation update function

    def update(frame):

        angle = theta[frame]

        x_point = np.cos(angle)

        y_point = np.sin(angle)

        degrees = np.degrees(angle) % 360  # Convert radians to degrees

        

        # Update triangle

        triangle_line.set_data([0, x_point, x_point, 0], [0, y_point, 0, 0])

        

        # Update point on the circle

        point.set_data([x_point], [y_point])  # Fixed this line to avoid the warning

        

        # Update text for angle, opposite side length, and sin(θ)

        dynamic_text.set_text(f“Angle: {degrees:.1f}°\nOpposite Side Length: {y_point:.2f}\nsin(θ): {y_point:.2f}”)

        return triangle_line, point, dynamic_text

     

    # Create animation

    ani = animation.FuncAnimation(fig, update, frames=len(theta), interval=20, blit=True)

    plt.show()



    Source link