java中的辅助对象是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2135775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:59:42  来源:igfitidea点击:

What are helper objects in java?

java

提问by giri

I come across few of the times called helper objects... can anybody elaborate what are those helper objects and why do we need them?

我很少遇到被称为辅助对象的时间……谁能详细说明这些辅助对象是什么以及我们为什么需要它们?

采纳答案by Bozho

Some operations which are common to a couple of classes can be moved to helper classes, which are then used via object composition:

一些对几个类通用的操作可以移动到辅助类,然后通过对象组合使用:

public class OrderService {
    private PriceHelper priceHelper = new PriceHelper();

    public double calculateOrderPrice(order) {
        double price = 0;
        for (Item item : order.getItems()) {
            double += priceHelper.calculatePrice(item.getProduct());
        }
    }
}

public class ProductService {
    private PriceHelper priceHelper = new PriceHelper();

    public double getProductPrice(Product product) {
        return priceHelper.calculatePrice(product);
    }
}

Using helper classes can be done in multiple ways:

可以通过多种方式使用辅助类:

  • Instantiating them directly (as above)
  • via dependency injection
  • by making their methods staticand accessing them in a static way, like IOUtils.closeQuietly(inputStream)closes an InputStreamwihtout throwing exceptions.
  • at least my convention is to name classes with only static methods and not dependencies XUtils, and classees that in turn have dependencies / need to be managed by a DI container XHelper
  • 直接实例化它们(如上)
  • 通过依赖注入
  • 通过创建它们的方法static并以静态方式访问它们,例如IOUtils.closeQuietly(inputStream)关闭InputStream而不抛出异常。
  • 至少我的约定是仅使用静态方法而不是依赖项来命名类XUtils,而这些类又具有依赖项/需要由 DI 容器管理XHelper

(The example above is just a sample - it shouldn't be discussed in terms of Domain Driven Design)

(上面的例子只是一个例子 - 它不应该从领域驱动设计的角度讨论)

回答by Paul Wagland

These are objects that "sit to the side" of the main body of code, and do some of the work for the object. They "help" the object to do it's job.

这些是“坐在代码主体旁边”的对象,并为对象做一些工作。他们“帮助”对象完成它的工作。

As an example, many people have a Closer helper object. This will take various closeable objects, for example, java.sql.Statement, java.sql.Connection, etc and will close the object, and ignore any errors that come out of it. This tends to be because if you get an error closing an object, there is not much you can do about it anyway, so people just ignore it.

例如,很多人都有一个 Closer 助手对象。这将采用各种可关闭的对象,例如 java.sql.Statement、java.sql.Connection 等,并将关闭该对象,并忽略由此产生的任何错误。这往往是因为如果您在关闭对象时遇到错误,无论如何您都无能为力,因此人们只会忽略它。

Rather than having this boilerplate:

而不是拥有这个样板:

try {
  connection.close();
} catch (SQLException e) {
  // just ignore… what can you do when you can't close the connection?
   log.warn("couldn't close connection", e);
}

scattered around the codebase, they simply call:

分散在代码库中,他们只是调用:

Closer.close(connection);

instead. For example, look at guava closeQuietly.

反而。例如,看看番石榴closeQuietly

回答by Malaxeur

A 'helper' method is typically a method to make something easier, whatever it is. Sometimes they're used to make things more readable/clearly organized (some may argue this, but it's ultimately very subjective):

'helper' 方法通常是一种使事情变得更容易的方法,无论它是什么。有时它们被用来使事情更具可读性/组织得更清晰(有些人可能会争论这一点,但最终是非常主观的):

public void doStuff() {
   wakeUp();
   drinkCoffee();
   drive();
   work();
   goHome();
}

Where, each 'helper method' on their own are fairly complex... the concept becomes really clear and simple.

其中,每个“辅助方法”本身都相当复杂……概念变得非常清晰和简单。

Another very good use of helper methods is to provide common functionality across many different classes. The best example of this is the Mathclass which contains a ton of static helper methods to help you calculate things like the log of a number, the exponent of a number... etc.

辅助方法的另一个非常好的用途是提供跨许多不同类的通用功能。最好的例子是Math包含大量静态辅助方法的类,以帮助您计算诸如数字的对数、数字的指数等内容。

Where you draw the line as to what's a helper method and what's just a regular method is pretty subjective, but that's the gist of it. Other answers here are pretty good too.

在什么是辅助方法和什么只是常规方法之间划清界限是非常主观的,但这就是它的要点。这里的其他答案也很不错。

回答by Zachary

Helper class, in my opinion, is similar to normal functions declared outside of classes in C++. For example, if you need a global constant for many classes, then you can define a helper class that encloses a final static const variable.

在我看来,Helper 类类似于在 C++ 类之外声明的普通函数。例如,如果您需要一个用于许多类的全局常量,那么您可以定义一个包含最终静态常量变量的辅助类。

回答by firecharger65

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Helpers {
public static String getDate() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        return dateFormat.format(new Date());
    }

    public static boolean isTimeABeforeTimeB(String timeA, String timeB) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
            Date dA = dateFormat.parse(timeA);
            Date dB = dateFormat.parse(timeB);
            if (dA.getTime() < dB.getTime()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            //
        }
        return false;
    }

    public static String getDateAndTimeInput(String prompt) {
        Scanner input = new Scanner(System.in);
        String ans;
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
        dateFormat.setLenient(false);
        boolean dateValid;
        do {
            System.out.print(prompt);
            ans = input.nextLine();
            ans = ans.trim();
            dateValid = true;
            try {
                Date d = dateFormat.parse(ans);
            } catch (Exception e) {
                dateValid = false;
            }
        } while (!dateValid);
        return ans;
    }


    public static String getStringInput(String prompt) {
        Scanner input = new Scanner(System.in);
        String ans;

        do {
            System.out.print(prompt);
            ans = input.nextLine();
            ans = ans.trim();
        } while (ans.length() == 0);
        return ans;
    }

    public static double getDoubleInput(String prompt) {
        Scanner input = new Scanner(System.in);
        double ans = 0;
        boolean inputValid;
        do {
            System.out.print(prompt);
            String s = input.nextLine();
            //Convert string input to integer
            try {
                ans = Double.parseDouble(s);
                inputValid = true;
            } catch (Exception e) {
                 inputValid = false;
            }
        } while (!inputValid);
        return ans;
    }

    public static int getIntegerInput(String prompt) {
        Scanner input = new Scanner(System.in);
        int ans = 0;
        boolean inputValid;
        do {
            System.out.print(prompt);
            String s = input.nextLine();
            // Convert string input to integer
            try {
                ans = Integer.parseInt(s);
                inputValid = true;
            } catch (Exception e) {
                inputValid = false;
            }
        } while (!inputValid);
        return ans;
    }

    public static int getIntegerInput(String prompt, int lowerBound, int upperBound) {
        Scanner input = new Scanner(System.in);
        int ans = 0;
        boolean inputValid;
        do {
            System.out.print(prompt);
            String s = input.nextLine();
            // Convert string input to integer
            try {
                ans = Integer.parseInt(s);
                if (ans >= lowerBound && ans <= upperBound) {
                    inputValid = true;
                } else {
                     inputValid = false;
                }
            } catch (Exception e) {
                inputValid = false;
            }
       } while (!inputValid);
       return ans;
   }
}

that is an example of of a Helper Class. It contains method which of are common use of the other classes in the project.

这是 Helper 类的一个例子。它包含项目中其他类的常用方法。

Example if someone wants to enter an Integer number from a class hew ill have to type in this: String num = Helpers.getIntegerInput("input your number");

例如,如果有人想从类中输入整数,则必须输入: String num = Helpers.getIntegerInput("input your number");

The prompt is the output that is show to the user. Other examples to input a String, double, date and time etc.

提示是显示给用户的输出。输入字符串、双精度、日期和时间等的其他示例。

回答by ahma

You can see a helper class as a toolbox that can be used by other classes to perform task like testing if a string is a palindrome, if a given number is prime, if an array contains negative number etc. You can create helper class by making all its methods static and its constructor private, and optionally you can also make the class final. Thus it can not be instantiated and one can easily access to all its methods directly.

您可以将辅助类视为工具箱,其他类可以使用该工具箱来执行诸如测试字符串是否为回文、给定数是否为素数、数组是否包含负数等任务。您可以通过以下方式创建帮助类它的所有方法都是静态的,它的构造函数是私有的,你也可以选择使类成为最终的。因此它不能被实例化,并且可以很容易地直接访问它的所有方法。

public final class HelperClass{

       private HelperClass(){
       }

       public static boolean isPositive(int number) {

             if (number >= 0) 
                    return true;
             else
                    return false;
       }
}

Here the function can be use directly to test a number :

这里的函数可以直接用来测试一个数字:

 HelperClass.isPositive(5);