concept method in category software development

appears as: methods, method, Methods, A method, The method, method, The methods
Five Lines of Code

This is an excerpt from Manning's book Five Lines of Code.

The following sections dive into each of these areas and describe how we can begin our refactoring journey from a much simpler foundation, without testing and fluffy code smells smells. Learning refactoring this way can quickly catapult junior developers', students', and programming enthusiasts' code quality to the next level. Tech leads can also use the methods in this book as a basis for introducing refactoring in teams that are not routinely doing it.

When we say setters and getters, we mean methods that directly assign or return a non-boolean field, respectively. We also include C#'s properties. Notice that this has nothing to do with a method’s name — it may or may not be called getX.

Object-oriented languages have a built-in property that constructors are always called before methods on objects. We can take advantage of this property to make sure things happen in a specific order. It is even fairly straightforward to do, although it means introducing one class per step that we want to enforce. But after performing this transformation, the sequence is no longer an invariant, because it is enforced! We don’t need to remember to call one method before the other, because it is impossible not to do so. Amazing!

  • Use Encapsulate data [P6.2.3] on the method that should run last.

    Listing 6.90. Before

    function deposit(to: string, amount: number) {
      let accountId = database.find(to);
      database.updateOne(accountId, { $inc: { balance: amount } });
    }

    Listing 6.91. After (1/2)

    class Transfer { #1
      deposit(to: string, amount: number) {
        let accountId = database.find(to);
        database.updateOne(accountId, { $inc: { balance: amount } });
      }
    }
  • Use Encapsulate data [P6.2.3] on the method that should run last.

    Seriously Good Software: Code that works, survives, and wins

    This is an excerpt from Manning's book Seriously Good Software: Code that works, survives, and wins.

    Finally, our novice programmer implements the connectTo method, whose task is to merge two groups of containers with a new connection. After this operation, all containers in the two groups must hold the same amount of water because they all become communicating vessels. First, the method will compute the total amount of water in both groups and the total size of the two groups. The water amount per container, after the merge, is simply the former divided by the latter.

    You’ll also need to update the arrays of all containers in the two groups. The naive way to do so involves appending all containers in the second group to all the arrays belonging to the first group, and vice versa. That’s what the following listing does, using two nested loops. Finally, the method updates the size field n and the amount field x of all affected containers.

    The method postAddWater, in turn, splits its task into two parts: first it checks that all containers in the current group hold the same amount of water; then it verifies that the total amount in the group is equal to the old amount plus the newly added amount. (The following version of postAddWater is tentative—a better version follows.)

    Listing 5.3. Contracts: Tentative version of support method postAddWater
       private boolean postAddWater(double oldTotal, double addedAmount) {
          return isGroupBalanced() &&
                 groupAmount() == oldTotal + addedAmount;  #1 Exact comparison
                                                             of doubles
       }
    
       private boolean isGroupBalanced() {  #2 Checks that all the group
          for (Container x: group) {          shares the same amount
             if (x.amount != amount) return false;
          }
          return true;
       }
    
    
    !@%STYLE%@!
    {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":2,\"ch\":55},{\"line\":2,\"ch\":57}],[{\"line\":6,\"ch\":40},{\"line\":6,\"ch\":42}]]"}
    !@%STYLE%@!

    As you can see, checking the postcondition requires more lines of code than the original nonhardened method! The sheer number of lines may lead you to surmise that you’re more likely to make a mistake in coding the postcondition check than in writing the original method. Is there a point to this effort? If the check ends up simply repeating the same calculations that the method performed, the effort is clearly pointless. However, if you can find a different, and hopefully simpler, way to check that the outcome is correct, then the two different algorithms are checking each other. Even a mistake in the postcondition routine is an opportunity to refine your understanding of the class at hand.

    The precondition states the requirements for the method to correctly function. It talks about the legal values for the parameters and about the current state of this object (for an instance method). For example, the precondition of a square-root method might state that its argument should be non-negative.

    It’s the caller’s responsibility to respect the precondition of the method being called. In the analogy with an ordinary contract, the precondition is an obligation for the caller and a benefit for the callee. The method itself can either passively assume that the precondition holds or actively check whether it holds, and react accordingly.

    The precondition should include only properties that are under the full control of the caller. For example, a method that takes a file name as an argument and opens that file can’t list among its preconditions that the file exists, because the caller can’t be 100% sure that it does. (Another process can erase that file at any time.) The method can still throw an exception in that case, but that exception will be of the checked variety, forcing the caller to handle it.

    Conversely, the postcondition states the effect of the method and describes its return value and all the changes performed on the state of any object. In most well-designed classes, changes should be limited to the current object, but this isn’t always the case. For example, the connectTo method in our running example must modify multiple containers to achieve its intended effect.

    Figure 5.1. The high-level structure of a contract for an instance method. All consequences of a method besides its return value are called side effects.
    The Mikado Method

    This is an excerpt from Manning's book The Mikado Method.

    The framework that the method provides can help individuals and whole teams to morph a system into a new desired shape. The method itself is straightforward and simple, and can be used by anyone at any time. In the following section, we’ll look at the core concepts, the main benefits, and when you can use them.

    Last, but not least, developers find the Mikado Method quick to learn and easy to use. The method has very little ceremony and consists of a lightweight process that requires almost no additional tools—just pen and paper or a whiteboard. Its simplicity helps you keep your eye on the prize. As a bonus, you can use the Mikado Graph you develop from the process to assist you when you reflect on the work done, and this improves learning.

    Hopefully we’ve now piqued your interest in the method, and you can see where it could be beneficial in your work. Now you must be wondering how it works.

    Testing loan-server_test.jsF
    >> Loan Server - fetch
    >> TypeError: Cannot call method 'writeHead' of undefined
    >> at server.start (lib/loan-server.js:29:10)
    >> at Object.exports.Loan Server.apply (test/loan-server_test.js:11:13)
    >> at Object.exports.Loan Server.setUp (test/loan-server_test.js:7:2)
    Test Driven: Practical TDD and Acceptance TDD for Java Developers

    This is an excerpt from Manning's book Test Driven: Practical TDD and Acceptance TDD for Java Developers.

    Some of these refactorings are so well defined that modern development tools have automated them. This automation has made refactoring evolutionary designs feasible for applications and systems of pretty much any size and complexity. (Can you imagine yourself renaming a method for clarity if that would mean manually checking out some five dozen source files from version control, doing a search-and-replace, and then checking in?)

    At this point, we’re pulling out the IDE to write some code. We’ll be using JUnit 4, the latest version of the de facto unit-testing framework for Java today (http://www.junit.org). If you’re not already familiar with JUnit, take a peek at appendix A for a short introduction. You won’t need to do that quite yet, though, if you don’t feel like it. The JUnit stuff is not essential here—the purpose is to see programming by intention in action—so just focus on the code we’re writing inside the methods and pay no attention to the weird annotations we’re using.

    Listing 2.5. Stubbing out methods of the Template class to make compilation succeed
    public class Template { public Template(String templateText) { } public void set(String variable, String value) { } public String evaluate() { return null; } }

    All the constructors and methods are in place to make the compiler happy, but none of those constructors and methods is doing anything so far. We’ve written a single failing test to show us a path forward, we’ve added just enough production code to make the test compile, and the next thing to do is the often most brain-tickling part of creating the functionality our test is asking of us.

    Listing 2.16. Extracting the check for missing variables into a method

    2.5.3. Keeping methods in balance

    One property of a method that has quite an effect on the readability of our code is the consistency of the abstraction level of the code within that method. Let’s take another look at evaluate as an example of what we’re talking about: