Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
shadster4321

Avoiding repeated code

Recommended Posts

I have two different methods:

public static void constructCrudeWoodenChairs() {
        boolean isAtHouse = isAtHouse();
        if (isAtHouse && isInBuildingMode()) {
            if (Inventory.getCount("Plank") >= 2) {
                if (!isChairConstructed()) {
                    if (!isBuildChairInterfaceOpen()) {
                        openBuildChairInterface();
                    } else {
                        clickBuildCrudeWoodenChair();
                    }
                } else {
                    removeChair();
                }
            } else {
                goToCastleWars();
            }
        } else if (isAtHouse && !isInBuildingMode()) {
            enterBuildingMode();
        } else if (isAtCastle()) {
            bankForChairs("Plank");
        } else {
            goToHouse();
        }
    }

and 

public static void constructOakChairs() {
        boolean isAtHouse = isAtHouse();
        if (isAtHouse && isInBuildingMode()) {
            if (Inventory.getCount("Oak plank") >= 2) {
                if (!isChairConstructed()) {
                    if (!isBuildChairInterfaceOpen()) {
                        openBuildChairInterface();
                    } else {
                        clickBuildOakChair();
                    }
                } else {
                    removeChair();
                }
            } else {
                goToCastleWars();
            }
        } else if (isAtHouse && !isInBuildingMode()) {
            enterBuildingMode();
        } else if (isAtCastle()) {
            bankForChairs("Oak plank");
        } else {
            goToHouse();
        }
    }

These methods are identical except for two things and I am trying to keep to the principle of avoiding repeated code. Is there a way for me to not use the same code twice here? 

Share this post


Link to post
Share on other sites
12 minutes ago, EasyAsPieee said:

So write a method that takes those 2 different things as parameters and call that method? That's literally what they're for - removing repeating code

I considered that but I was worried it would break the principle of a function only doing one thing because the function would then create both oak and wooden chairs

Share this post


Link to post
Share on other sites
5 hours ago, shadster4321 said:

These methods are identical except for two things and I am trying to keep to the principle of avoiding repeated code. Is there a way for me to not use the same code twice here? 

Duplicate code should always be avoided as it just bloats the code making it harder to read and maintain. When you have duplicate code and you want to add more functionality, change anything or fix a bug you need to copy-paste the new code in all the duplicate methods, which is annoying and error prone (if you have a very large number of such methods). Both @EasyAsPieee and @Naton's solutions are viable.

 

As a side note, I've restructured the logic in your first method. It has fewer lines of code, there are no cached booleans and all conditions are only evaluated once.

public static void constructCrudeWoodenChair() {
	if (Inventory.getCount("Plank") < 2) {
		if (!isAtCastle())
			goToCastleWars();
		else
			bankForChairs("Plank");
	} else { 
		/* Has at least 2 planks*/
		if (!isAtHouse())
			goToHouse();
		else if (!isInBuildingMode())
			enterBuildingMode();
		else if (isChairConstructed())
			removeChair();
		else if (!isBuildChairInterfaceOpen())
			openBuildChairInterface();
		else
			clickBuildCrudeWoodenChair();
	}
}

 

Share this post


Link to post
Share on other sites
1 hour ago, Einstein said:

Duplicate code should always be avoided as it just bloats the code making it harder to read and maintain. When you have duplicate code and you want to add more functionality, change anything or fix a bug you need to copy-paste the new code in all the duplicate methods, which is annoying and error prone (if you have a very large number of such methods). Both @EasyAsPieee and @Naton's solutions are viable.

 

As a side note, I've restructured the logic in your first method. It has fewer lines of code, there are no cached booleans and all conditions are only evaluated once.

public static void constructCrudeWoodenChair() {
	if (Inventory.getCount("Plank") < 2) {
		if (!isAtCastle())
			goToCastleWars();
		else
			bankForChairs("Plank");
	} else { 
		/* Has at least 2 planks*/
		if (!isAtHouse())
			goToHouse();
		else if (!isInBuildingMode())
			enterBuildingMode();
		else if (isChairConstructed())
			removeChair();
		else if (!isBuildChairInterfaceOpen())
			openBuildChairInterface();
		else
			clickBuildCrudeWoodenChair();
	}
}

 

Damn, that code is really nice. It fixes the 'arrow code'  problem that I had, making it much easier to understand. I doubt I would have thought of this myself. Are there any ways I can improve my ability to write my code in a more logical way like yours?

Share this post


Link to post
Share on other sites
4 minutes ago, shadster4321 said:

Damn, that code is really nice. It fixes the 'arrow code'  problem that I had, making it much easier to understand. I doubt I would have thought of this myself. Are there any ways I can improve my ability to write my code in a more logical way like yours?

Thank you! :)

The 'arrow code problem' is actually called the pyramid of doom. To answer your question, the only way to get better at coding is by deliberate practice.

Share this post


Link to post
Share on other sites
6 hours ago, shadster4321 said:

Damn, that code is really nice. It fixes the 'arrow code'  problem that I had, making it much easier to understand. I doubt I would have thought of this myself. Are there any ways I can improve my ability to write my code in a more logical way like yours?

Try to keep 1 action per loop.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Our picks

    • This update features:

      Fixed broken hooks from today's update


      Fix wilderness level with RuneLite (Thanks @Todd)


      Add support for Kotlin .class files in scripts (Thanks @wastedbro)


      Overhaul Inventory API (Thanks @wastedbro)


      Add List support for common methods


      Change method grouping to make more sense (by functionality)


      Refactor methods to utilize Java 8 streams instead of cumbersome loops




      Recognize chatbox minimization (Thanks @JoeDezzy1)


      Fix Screen#isInViewport when NPC chat is open (Thanks @JoeDezzy1)


      Fix login bot bugs (Thanks @erickho123)


      Fix hint arrow return values (Thanks @Encoded)


      Fix depositAllExcept functionality (Thanks @wastedbro)


      Change containing box interface bound and adjust for Y values (Thanks @erickho123)
      • 151 replies
    • This release will:

      Fix prayers and world hopper API (Thanks @JoeDezzy1 and @erickho123)


      Improve banking API (Thanks @Encoded)


      Adds methods for returning and using Java Lists, rather than arrays


      Slightly randomizes some hardcoded behaviour


      Removes sleeps from waitConditions; the efficiency saving potential is negligible in these use-cases, therefore cleaner code is preferable


      Other back-end improvements





      Note: If you are using LG, please restart both the RS client and TRiBot.
      • 90 replies
    • This release will:

      Add new internal framework for capturing exceptions


      Fix issue with not selecting the last column in world hopper (Thanks @Todd)


      Add a message about pin usage in Banking#openBank (Thanks @Todd)


      Disable the firewall by default (Thanks @Todd)


      Fix handling of the welcome screen after login (Thanks @Encoded)


      Fix wrong amount bank withdrawal (Thanks @Encoded)


      Fix Screen#isInViewport


      Fix Game#isInViewport (Thanks @Encoded)


      Call onBreakEnd for ListenerManager Breaking Listeners (Thanks @Encoded)


      Fix Prayer#getPrayerPoints NumberFormatException (Thanks @JoeDezzy1)



      Note: If you are using LG, please restart both the RS client and TRiBot.
      • 28 replies
    • This release will:

      Fix LG for both OSBuddy and RuneLite


      Fix issue where the resizable client isn't able to be made smaller (Thanks @JoeDezzy1)


      Fix detection of the logout game tab when resizable mode and side panels are enabled (Thanks @JoeDezzy1)


      Add initial support for Sentry to allow us to identify and easily debug exceptions happening with all TRiBot users


      Add methods to determine if the bank is actually loaded, and not just the overarching interface (Thanks @wastedbro)



      Upcoming updates:

      Improved CLI support


      Full Sentry support


      Much more
      • 64 replies
    • This release will:

      Fix NPE in Camera API (Thanks @wastedbro)


      Update deposit box interface ids (Thanks @Encoded)


      Add various bank methods (Thanks @wastedbro)


      Banking#getWithdrawXQuantity


      Banking#getDefaultWithdrawQuantity


      Banking#arePlaceholdersOn




      Fix resizeable minimap bug (Thanks @wastedbro)


      Remove Java 8 requirement


      Please note: TRiBot is not yet fully compatible with Java 10+




      Fix the break handler issues by ensuring the break handler thread never gets paused


      Fix broken settings hooks



      Upcoming updates:

      Improved CLI support


      Much more



      Note: If you are using LG, please restart both the RS client and TRiBot
      • 68 replies
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...