【问题标题】:Newbie Refactor Procedural programming to OOP HASHING function新手将过程编程重构为 OOP HASHING 函数
【发布时间】:2020-06-05 22:08:40
【问题描述】:

你好,我是 JAVA 编程语言的新手,我已经学习了很多 Java 教程,但我发现很难让它在这段代码中工作面向对象编程。 我有 2 个程序,第一个是程序方式。我使用了一个字符串数组来存储两个 dates.toString (short, long) 和两个 Hashes(dates.toString[long,short])

import java.math.BigInteger;
import java.time.format.DateTimeFormatter;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import org.hsqldb.Trace;

public class Hashing {

    private LocalDateTime justNow;
    /**
     * Full Date and Time
     */
    private String fullDate;

    /**
     * Current date and time cropped
     */
    private String currentDateCropped;

    /**
     * Hashing Function of FullDate HASHED
     */
    private String showFullDate;

    /**
     * Hashing Function of DateCropped HASHED
     */
    private String showCurrentDateCropped;

    /**
     * Arguments:
     * Refactoring procedure below with Object oriented Programming
     * @return String Array of 2 results [0] Limited Date [1]
     *         FullDate
     */

      public string getDate() {
      setFullDateNow();

      System.out.println(getFullDate().toString(true));
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
      DateTimeFormatter dtfFull = DateTimeFormatter.ofPattern("dd/MM/yyyy | HH");

      LocalDateTime now;
      now = LocalDateTime.now();

      System.out.println(dtf.format(now));
      System.out.println(dtfFull.format(now));
      Date date = java.util.Calendar.getInstance().getTime();
      String[] dateStr = new String[2];
      dateStr[0] = " ";
      dateStr[1] = " ";
      dateStr[0] = dtf.format(now);
      dateStr[1] = dtfFull.format(now);

      return dateStr;

      }


    public static byte[] getSHA(String input) throws NoSuchAlgorithmException {
        // Static getInstance method is called with hashing SHA 
        MessageDigest md = MessageDigest.getInstance("SHA-256");

        // digest() method called 
        // to calculate message digest of an input 
        // and return array of byte 
        return md.digest(input.getBytes(StandardCharsets.UTF_8));
    }

    public static String toHexString(byte[] hash) {
        // Convert byte array into signum representation 
        BigInteger number = new BigInteger(1, hash);

        // Convert message digest into hex value 
        StringBuilder hexString = new StringBuilder(number.toString(16));

        // Pad with leading zeros 
        while (hexString.length() < 32) {
            hexString.insert(0, '0');
        }

        return hexString.toString();
    }

    // Driver code 
    public Hashing() {

        try {

//remove

              System.out.println("HashCode Generated by SHA-256 for:");
              String[] currentDate = getDate();
              String[] result = new String[4];
              result[0] = currentDate[0];
              result[1] = currentDate[1];
              result[2] = toHexString(getSHA(currentDate[0]));
              result[3] = toHexString(getSHA(currentDate[1]));
              System.out.println("\n" + currentDate[0] + " : " + toHexString(getSHA(currentDate[0])));

        } // For specifying wrong message digest algorithms 
        catch (NoSuchAlgorithmException e) {
            System.out.println("Exception thrown for incorrect algorithm: " + e);
        }
        return myString;
    }

    public static void main(String args[]) {
        Hashing();
    }
}

另一个重构的代码块是:

import java.math.BigInteger;
import java.time.format.DateTimeFormatter;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import org.hsqldb.Trace;

public class Hashing {

    private LocalDateTime justNow;
    /**
     * Full Date and Time
     */
    private String fullDate;

    /**
     * Current date and time cropped
     */
    private String currentDateCropped;

    /**
     * Hashing Function of FullDate HASHED
     */
    private String varFullDateHash;

    /**
     * Hashing Function of DateCropped HASHED
     */
    private String varCurrentDateCroppedHash;

    /**
     * Initializer of what time is now on the constructor (Netbeans Warning)
     */
    public void initComponentstatic() {
        setFullDateNow();
    }

    /**
     * Getter for getting Full Date
     *
     * @return LocalDateTime Just NOW!
     */
    public LocalDateTime getFullDate() {
        LocalDateTime inner = this.justNow;
        return inner;
    }

    /**
     * Setter for Setting a Custom Date to private variable justNow
     *
     * Void justNOW=CustomDate
     */

    public void setFullDate(LocalDateTime MyDate) {
        LocalDateTime inner = MyDate;
        this.justNow = inner;
    }

    /**
     * Setter for Setting a Current Date to private variable justNow
     *
     * Void justNOW=now()
     */

    public void setFullDateNow() {
        LocalDateTime now;
        now = LocalDateTime.now();
        this.justNow = now;
    }

    /**
     * Setter for Setting a Current Date to private variable justNow
     *
     * Void justNOW=now()
     */

    //@Override It doesn't Need to be overriden because it has a a parameter (Boolean)
    public String toString(boolena full) {
        DateTimeFormatter dtf;
        String TEMP;
        LocalDateTime currentDate;
        if (full) {
            dtf = DateTimeFormatter.ofPattern(
                    "dd/MM/yyyy | HH:mm:ss:SS");
        } else {
            dtf = DateTimeFormatter.ofPattern(
                    "dd/MM/yyyy | HH");
        }
        /** This doesn't work 
        try {
            if (this.justNow = null) {
                System.out.println("justNow Inited");
            } else {
                System.out.println("justNow Empty");
            }

        } catch (Exception e) {
        }*/

        currentDate = this.justNow;
        TEMP = currentDate.format(dtf);
        return TEMP; //To change body of generated methods, choose Tools | Templates.
    }

    /**
     * Arguments:
     * Refactoring procedure below with Object oriented Programming
     * The variables are stored in this new OOP code as private variables, and accessed through getters and setters.
     */
    /**
     * public string getDate() {
     * setFullDateNow();
     *
     * System.out.println(getFullDate().toString(true));
     * /**
     * DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy |
     * HH");
     * DateTimeFormatter dtfFull = DateTimeFormatter.ofPattern("dd/MM/yyyy |
     * HH:mm:ss:SS");
     *
     * LocalDateTime now;
     * now = LocalDateTime.now();
     *
     * System.out.println(dtf.format(now));
     * System.out.println(dtfFull.format(now));
     * Date date = java.util.Calendar.getInstance().getTime();
     * String[] dateStr = new String[2];
     * dateStr[0] = " ";
     * dateStr[1] = " ";
     * dateStr[0] = dtf.format(now);
     * dateStr[1] = dtfFull.format(now);
     *
     * return dateStr;
     *
     * }
     */

    public static byte[] getSHA(String input) throws NoSuchAlgorithmException {
        // Static getInstance method is called with hashing SHA 
        MessageDigest md = MessageDigest.getInstance("SHA-256");

        // digest() method called 
        // to calculate message digest of an input 
        // and return array of byte 
        return md.digest(input.getBytes(StandardCharsets.UTF_8));
    }

    public static String toHexString(byte[] hash) {
        // Convert byte array into signum representation 
        BigInteger number = new BigInteger(1, hash);

        // Convert message digest into hex value 
        StringBuilder hexString = new StringBuilder(number.toString(16));

        // Pad with leading zeros 
        while (hexString.length() < 32) {
            hexString.insert(0, '0');
        }

        return hexString.toString();
    }

    // Driver code 
    public Hashing() {

        try {

//remove
            initComponentstatic();
            DateTimeFormatter dtf;
            dtf = DateTimeFormatter.ofPattern(
                    "dd/MM/yyyy | HH:mm:ss:SS");
            //System.out.println(getFullDate().toString(true));
            String myString = getFullDate().toString(true);
            System.out.println(myString);
            fullDate=getFullDate().toString(true);
            currentDateCropped=getFullDate().toString(false);
            varFullDateHash=toHexString(getSHA(fullDate));;
            varCurrentDateCroppedHash=toHexString(getSHA(fullDateCropped));;;
            System.out.println("\n" + fullDate + " : " + varFullDateHash);
            System.out.println("\n" + currentDateCropped + " : " + varCurrentDateCroppedHash);
             */
        } // For specifying wrong message digest algorithms 
        catch (NoSuchAlgorithmException e) {
            System.out.println("Exception thrown for incorrect algorithm: " + e);
        }
        return myString;
    }

    public static void main(String args[]) {
        Hashing();
    }
}

这个想法是将程序代码转换为 4 个类的变量。 我的问题是为什么我的类散列的 toString(boolean) 不起作用应该我覆盖,还是不应该? 我不知道我的代码有什么问题,它说当前参数(不需要参数)不匹配(1 个参数布尔值) 我不能让它工作。 我想如果有人能给我一个线索我做错了什么,那么我可以解决它。 如果我覆盖系统说它不需要,因为 toString() 需要的参数。 感谢您的帮助,将不胜感激。 如果顺便有一些关于面向对象编程的书籍,任何人都可以建议我会非常感谢。 来自阿根廷的问候。

【问题讨论】:

    标签: java refactoring procedural-programming


    【解决方案1】:

    我已修正您的程序代码中的所有错别字和错误。
    现在它可以编译并运行,但请修改它,以确保它按预期工作。

    Main.java(再次更改为 Hashing.java)

    import java.math.BigInteger;
    import java.time.format.DateTimeFormatter;
    import java.nio.charset.StandardCharsets;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.time.LocalDateTime;
    import java.util.Calendar;
    import java.util.Date;
    
    public class Main {
    
     private LocalDateTime justNow;
     /**
      * Full Date and Time
      */
     private String fullDate;
    
     /**
      * Current date and time cropped
      */
     private String currentDateCropped;
    
     /**
      * Hashing Function of FullDate HASHED
      */
     private String showFullDate;
    
     /**
      * Hashing Function of DateCropped HASHED
      */
     private String showCurrentDateCropped;
    
     /**
      * Arguments:
      * Refactoring procedure below with Object oriented Programming
      * @return String Array of 2 results [0] Limited Date [1]
      *         FullDate
      */
    
     public String[] getDate() {
    
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
      DateTimeFormatter dtfFull = DateTimeFormatter.ofPattern("dd/MM/yyyy | HH");
    
      LocalDateTime now;
      now = LocalDateTime.now();
    
      System.out.println(dtf.format(now));
      System.out.println(dtfFull.format(now));
      Date date = java.util.Calendar.getInstance().getTime();
      String[] dateStr = new String[2];
      dateStr[0] = " ";
      dateStr[1] = " ";
      dateStr[0] = dtf.format(now);
      dateStr[1] = dtfFull.format(now);
    
      return dateStr;
    
     }
    
    
     public static byte[] getSHA(String input) throws NoSuchAlgorithmException {
      // Static getInstance method is called with hashing SHA 
      MessageDigest md = MessageDigest.getInstance("SHA-256");
    
      // digest() method called 
      // to calculate message digest of an input 
      // and return array of byte 
      return md.digest(input.getBytes(StandardCharsets.UTF_8));
     }
    
     public static String toHexString(byte[] hash) {
      // Convert byte array into signum representation 
      BigInteger number = new BigInteger(1, hash);
    
      // Convert message digest into hex value 
      StringBuilder hexString = new StringBuilder(number.toString(16));
    
      // Pad with leading zeros 
      while (hexString.length() < 32) {
       hexString.insert(0, '0');
      }
    
      return hexString.toString();
     }
    
     // Driver code 
     public void hash() {
    
      try {
    
       //remove
    
       System.out.println("HashCode Generated by SHA-256 for:");
       String[] currentDate = getDate();
       String[] result = new String[4];
       result[0] = currentDate[0];
       result[1] = currentDate[1];
       result[2] = toHexString(getSHA(currentDate[0]));
       result[3] = toHexString(getSHA(currentDate[1]));
       System.out.println("\n" + currentDate[0] + " : " + toHexString(getSHA(currentDate[0])));
    
      } // For specifying wrong message digest algorithms 
      catch (NoSuchAlgorithmException e) {
       System.out.println("Exception thrown for incorrect algorithm: " + e);
      }
     }
    
     public static void main(String args[]) {
      Main e = new Main();
    
      e.hash();
     }
    }
    

    现在,您应该可以将其重构为 OOP。

    电流输出

    05/06/2020 : 669454683ee2e26f3ac1d18452437d58b8f07b780c9f898735881130cca69621
    

    【讨论】:

    • 非常感谢 Snix 我会检查一下!
    • 非常感谢 Snix 的帮助。我尝试生成 Main 变量的实例并将其运行到我的 .toString(true) 类'中,它指出了相同的错误。你认为我的 toString(boolean Argument) 不能这样使用吗?非常感谢您的合作!
    • 抱歉,我不得不编辑问题以进行澄清。
    • 所以你将类作为变量调用?然后生成一个新语句 How does that Works?主 e = new Main();例如,变量 e 应该是类 Main = 生成构造函数 Main(arguments) ?
    • 您应该检查static and not-static methods 之间的区别。它将清楚为什么我创建 main 的对象实例。但最后,是的,就像你说的那样。
    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 2013-12-16
    • 2020-03-27
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    相关资源
    最近更新 更多