Extend a Java class or provide a static help class?

For example: I have to use the date class in my project, but I, for example, need simple methods to add minutes to the date, etc. Should I:

Make a static class using methods such as public static Date addToDate(Date date, int timeToAdd) Create a MyDate class that extends the date and exposes methods like public Date add(int duration)

As I studied this question, I became interested in what might be a better approach in general, especially regarding classes from the standard library.

+4
source share
5 answers

I would go for the first approach. One of the things that I hate about some OOP degenerations is that sometimes useless classes propagate - often it's a perfectionist’s whim that escalates weird classes where there are two methods and nothing really significant, and that leads to a bunch of useless code .

Just create a DateUtils class and always check that the Java Runtime no longer provides something like that.

+5
source

People often suggest using composition instead of inheritance. In any case, there are cases where inheritance is better. You said:

I need, for example, simple methods for adding minutes to a date, etc.

If you really need simple methods and no extra fields are needed to store additional properties, then follow the @Giacomo approach, using the DateUtils class, as he suggested, with static methods that can perform the necessary operations.

If you need to store additional data in a Date object, then consider using a class for this. If so, I disagree with @thasc, because even if usually using composition instead of inheritance might be good practice, creating an extended version of the Date class will allow you to use ExtendedDateObject directly in the method that requires the Date parameter.

+2
source

Inheritance from a date requests problems. There is enough confusion with java.util.Date, java.util.Timestamp, java.sql.Date, without adding complexity to your own subclasses. Definitely use the static method method.

Remember that some of the features you may need are already implemented in commons-lang . If your instructor allows this, you might be better off using this library instead of following one of the options in the question.

+1
source

I would choose the second option for the following reason

  • I see more classes as a less dominant problem, as well as too many static methods. Where to start and where to stay? Are 3 methods enough to create a subclass?

You could call it sth. like DateWithMinuteHandling to reduce the probability of naming items

0
source

Consider using the Joda-Time library to process date / time.

-1
source

All Articles