1

I am reading about design pattern and would like to know what would be a good way to eliminate the below code duplication for the format function.

Assume I have the below code, what approach is best to take?. I can create an abstract class and inherit function or pull out the function into a separate static and make reference.

public interface Generator{
    generate()
}

public class test1 implementes Generator{
    generate()
    public static string FormatDate(){
        String date_s = " 2011-01-18 00:00:00.0"; 
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); 
        Date date = dt.parse(date_s); 
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
        System.out.println(dt1.format(date));
    }
}

public class test2 implementes Generator{
    generate()
    public static string FormatDate(){
    String date_s = " 2011-01-18 00:00:00.0"; 
    SimpleDateFormat dt = new SimpleDateFormat("yyyy-mm-dd"); 
    Date date = dt.parse(date_s); 
    SimpleDateFormat dt1 = new SimpleDateFormat("yyyymmdd");
    System.out.println(dt1.format(date));
    }
}
jason bourne
  • 87
  • 1
  • 9

3 Answers3

2

You can write a separate util class which will have this static function and refer it in test1 and test2.

S.K.
  • 3,597
  • 2
  • 16
  • 31
0

You could write something like this

Mainclass

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

    public class Testclass implements Generator, DateFormatter {

        public static void main(String[] args){
            Testclass stack = new Testclass();
            try {
                stack.generate();
                stack.formatDate("2011-01-18 00:00:00.0", "yyyy-mm-dd hh:mm:ss", "yyyy-mm-dd");
                stack.generate();
                stack.formatDate("2011-01-18 00:00:00.0", "yyyy-mm-dd", "yyyymmdd");
            } catch (ParseException e) {
                // TODO add some more Exceptionhandling here
                System.out.println("The given String could not be parsed.");
                e.printStackTrace();
            }
        }

        @Override
        public void generate() {

        }

        @Override
        public void formatDate(String dateString, String parserFormat, String outputFormat) throws ParseException {
            SimpleDateFormat dt = new SimpleDateFormat(parserFormat);
            Date date = dt.parse(dateString);
            SimpleDateFormat dt1 = new SimpleDateFormat(outputFormat);
            System.out.println(dt1.format(date));
        }
    }   

Interfaces

Generator:

    public interface Generator {

        void generate();
    }

DateFormatter:

    import java.text.ParseException;

    public interface DateFormatter {

        void formatDate(String dateString, String parserFormat, String outputFormat) throws ParseException;
    }

One thing i want to add:
Dont use Date or SimpleDateFormat, if you are using Java 8 use DateTime Oracle about DateTime
If you cant use Java 8, use the force

BadK
  • 307
  • 3
  • 12
  • A lot of sources mention the fact that you should always program to an interface (which is what you done). But is there a reason why abstract would not be best here? – jason bourne Aug 13 '15 at 12:01
  • In this special case maby abstract would be better, but a good answer would be longer than the comment field. You have to decide yourself on every different case. For further reading: http://stackoverflow.com/questions/10040069/abstract-class-vs-interface-in-java When you look over my example, maby you will notice its not even needed to have an interface nor an abstract class. ;-)) – BadK Aug 13 '15 at 12:17
  • Yeah thank you. I am just reading up on patterns and trying to improve my style of coding. I am familiar with most of these techniques just a matter of knowing where to implement!. Thanks again for your help. – jason bourne Aug 13 '15 at 13:31
-1

You can create an abstract class with 2 abstract methods String getFormat1() and String getFormat2().

Then add a non-static method formatDate() which contains your code above, and calls getFormat1() and getFormat2() when creating the SimpleDateFormat objects.

You can then create 2 classes that extend the abstract class and define the abstract methods returning appropriate values ("yyyy-mm-dd hh:mm:ss" and "yyyy-mm-dd" for the first and the others for the second).

If you need more formats, just create another subclass.

You also want to stop using static all the time, since that'll prevent you from using many design patterns as well as cause other problems.

This is the Template Method Pattern.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • @Robert as you get more experience, you tend to write less code and do more design and architecture, so you're definitely on to something. Thanks for contributing a valuable comment to a 6 year old answer, you've certainly made StackOverflow a haven of knowledge for everyone. – Kayaman Oct 19 '21 at 19:50
  • @Robert I'm sure you won't be gaining any experience from my words. You are free to use code, words, interpretative dance or hieroglyphs to explain what you wish. I however will leave my old answers unedited, no matter how much they may annoy you. Since I don't contribute on SO anymore, I'm glad that my old answers at least cause some annoyance to Roberts who have not answered **any** questions at all. I'm not sure how to put this comment into code form so you would understand it, but maybe `I.dontCareAbout(robert.getOpinion());` works? ;) – Kayaman Oct 31 '21 at 14:47