Using NON static class Methods Without reference - java

I'm new to Java. I know the concept of static and non static method.
I'm wondering if it's possible to use non static methods of a class without having to create a reference to it.
Like for example, for my program I'm working with Date objects, and I need to get yesterday's date in one of them. I know one possible way is like the following:
Calendar cal= Calendar.getInstance();
cal.add(Calendar.DATE,-1);
Date yesterdayDate = new Date();
yesterdayDate = cal.getTime();
Is there a way to do that without having to create the cal reference that I will be using just once in the whole program?
Something like this (I know this is by no means a correct syntax):
Date yesterdayDate = new Date();
yesterdayDate = Calendar.getInstance().add(Calendar.DATE,-1).getTime();

If Calendar was following a fluent builder pattern, where i.e. the add method was adding, then returning the mutated instance, you would be able to.
You're not, because Calendar#add returns void.
But don't be fooled: Calendar.getInstance() does create an instance as indicated - you're just not assigning it to a reference.

What you are referring to is the known Builder pattern.
The Calendar class isn't build to support the builder pattern, but there are many other classes / apis where it is.
For example, DateTimeFormatterBuilder from joda time.
DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder()
.appendMonthOfYearText()
.appendLiteral(' ')
.appendYear(4, 4)
.toFormatter();
You can always go ahead and create your own builders. (In your example, CalendarBuilder).
But you should be aware that the Calendar class is generally regarded as evil - it's not thread safe, for one. Newer alternatives are joda time and the java 8 api's.

if method return type is instance of any class, you should chain calls on it and you dont need to create named variable.
This is used in Fluent interface api, where every method returns instance of "this" class.
Note:
Be careful if you call many chained methods on different objects like:
collection.get(0).getAddress().getStreet().length();
because of possible NullPointerExceptions.
On the other hand, use of fluent api should be safe, because you always call it on "this" instance, so if api has not some strange bugs, it is safe and NPE should not occur.

The general answer is no, because classes like Calendar are stateful and therefore require an initialized instance to be able to operate. If you do:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-1);
You are first calling a factory method getInstance() to create an instance of GregorianCalendar, which is the default concrete implementation of Calendar. It is initialized to the default timezone and locale and set to the current system time. This means it is different than another instance you create some milliseconds later.
Then, calling add(...) or other manipulation methods on your instance affects the calendar state, following the programmed calendar logic. If this was not a discrete instance but global (static) state, multiple threads would interfere with each other and cause very confusing results.
The same holds for example for the SimpleDateFormat class. It is often incorrectly set up as a field and re-used for formatting dates in a multi-threaded context (e.g. the handle method of a servlet). This will now and then cause erratic behavior because SimpleDateFormat is also stateful.
So the conclusion is: you need to create isolated instances of classes like Calendar and SimpleDateFormat because they are stateful and thus not thread-safe.
Bear in mind that sometimes you can optimize a bit by declaring your instance before any iterations you are doing, and then re-setting its state instead of creating a new instance on each iteration (after all, creating an instance of Calendar is indeed a bit expensive).

The other answers all correct, but I think they miss one crucial point: if you are new to Java ... don't waste your time thinking about such questions.
Don't get me wrong: it is always good to understand the programming language you are using in great depth; and it is also important to have some common sense to avoid "really stupid performance" mistakes.
But: don't worry about "performance" and spent hours to reduce the number of objects your program is dealing ... from 100 to 95. That is a complete waste of time.
If you intend to write programs that are used for a longer period of time, and by more than one person (and "good" programs tend to get there pretty fast) then it is much more important that your program is easy to read, understand, and change.
The only valid reasons to look into "performance" are:
You are in the design phase; and as mentioned before one should avoid stupid mistakes that render your end-product "unusable" because of performance issues.
You are actually confronted with "performance" issues. Then you should start profiling your application; and then, based on that analysis improve the "slow" parts.
In other words: don't try to solve "non-existing" problems. And unless your application is running in an embedded environment where every byte of memory and every CPU cycle can come at a certain prize ... don't worry about creating those Calendar objects 10, 100 or 500 times.

It is not only because method is not static. Understand that you cannot chain like this -- yesterdayDate = Calendar.getInstance().add(Calendar.DATE,-1).getTime(); because add() method does not return anything. If that method would have returned you the same calendar object, you could chain them without creating a reference.
Just to understand how chaining works, you can try creating your own methods those return objects and call other methods on them.

Related

Should org.joda.time.DateTimeZone be declared as static field in a class instead of creating new instance each time

Should org.joda.time.DateTimeZone be defined as static in a class instead of creating a new instance each time it's needed, specially when we're always using the same time zone.
DateTimeZone is thread-safe and immutable so it does not make sense to create a new instance each time. Is my thinking correct?
To add more details, currently my class creates a DateTimeZone object in the constructor of my class, always for the same time zone, so I thought why not make it static instead of creating a new object each time.
DateTimeZone is thread-safe and immutable, and all subclasses must be as well.
See api
So yes. It can be declared as static field.
Should you do it or not, it depends on your class and overall project design. See here why static fields may be evil.
Yes, I think you can create is as a static field - and the link in #Mike's answer tells you about the possible drawbacks of doing so (like possible problems if you want to test your code in a different timezone and so on).
But if your concerns are about performance and memory usage, I wouldn't worry too much about that. It seems that Joda-Time uses an internal cache of DateTimeZone objects:
DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTimeZone other = DateTimeZone.forID("Europe/London");
System.out.println(zone == other); // true
The code above prints true, which means that both are the same object.
Of course this is an implementation detail (I'm using Joda-Time 2.9.9) and it's not good to rely on such details as these things can change.
Anyway, if you're sure that this timezone will never change, you can make it static. If there's a possibility of having more than one in the future, don't (I wouldn't).

Why is Date better than Calendar for property typing when stuck using the legacy API?

First, please note that this question is not a duplicate of this Question:
Java Date vs Calendar. My question is much more specific. The referenced question asks "what" (or "which"), but I already know the "what" and am asking the "why".
I am on a team working on enhancements to an existing Java project for a client. This Java project uses java 6, and does not have Joda Time as a dependency. After inquiring, it looks like adding Joda Time or upgrading to Java 8 are not options.
So, when it comes to representing date/time as a field in an object, we have to use either Calendar or Date for property typing. The legacy code of this project is littered with Objects that use Calendar to represent date/time fields -- fields that we would never have cause to manipulate (as in add or subtract units of time, etc). I know that this is bad practice, as Calendar is a more complex object, while Date is simpler and would work just as well. (And granted, I know that both are fundamentally wrappers for a long of epoch millis, are mutable, and are poorly designed, but again these are our only two options.)
In other words, an object like this:
public class Reservation {
private Guest guest;
// Set only once, never used for calculations
private Calendar dateReserved;
...
}
Should be this instead:
public class Reservation {
private Guest guest;
// Set only once, never used for calculations
private Date dateReserved;
...
}
I then noticed that when adding new Objects for new features, my team was following the same convention of using Calendar instead of Date. When I brought this up, the reply was that it's better to use Calendar because it can do more and doesn't have all these deprecated methods like Date does.
I know that this reasoning is oversimplified. I also see that this answer to the broader question of usage expresses the same view, namely that Calendar should not be used for property typing. However, the answer doesn't contain much explanation as to why Calendar should not be preferred.
So I already know the "What". But I'm trying to make the case to my team, so my question is, "Why"? Why, when property typing, should Date be preferred to Calendar? What are the disadvantages of using Calendar instead of Date for property typing?
I agree with Jon Skeet's comment regarding calendar systems and time zones, and I think your premise is fundamentally flawed. Dates aren't better than Calendars. If you're never ever ever going to compare times, or never ever ever have two dates in different time zones, then sure, the smaller footprint can be nice, I guess, but at that point, just use longs and Unix timestamps. Calendars are by far the better object model, and after all, if you absolutely need it, you can get a Date object from it.
If you are stuck having to choose between Date and Calendar when property typing:
Use Calendar if either one of these is true:
You need to be able to adjust the date/time after it is initially set
(such as changing the month while leaving the day and hour the same).
You need to be aware of timezone.
Otherwise, use Date for the following reasons:
Expressing your intentions accurately. If you use Calendar, you are implying that you want a certain functionality that you don't actually intend to use (timezones, changing the day or month, etc).
Less hassle with String representations. For example, consider this class:
public class Reservation {
private Guest guest;
private Calendar dateReserved;
#Override
public String toString() {
return String.format("Reservation{guest=%s,dateReserved=\"%s\"}",
guest, dateReserved);
}
}
Now if you print out an instance of this class, you'll get something hideous:
Reservation{guest=Guest{id=17,name="John Smith"},dateReserved="java.util.GregorianCalendar[time=1426707020619,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=77,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=30,SECOND=20,MILLISECOND=619,ZONE_OFFSET=-28800000,DST_OFFSET=3600000]"}
Whereas if you had used Date instead, you'd get this:
Reservation{guest=Guest{id=17,name="John Smith"},dateReserved="Wed Mar 18 12:34:26 PDT 2015"}
So if you use Calendar and you want your toString() to be usable, you would need to call dateReserved.getTime() -- which means you'd need to add a null check. This goes for whether or not you end up using a DateFormat object.
Date is a smaller object, quicker to instantiate and with less overhead.
Date is practically immutable -- meaning that the only way to change a date object is to use deprecated methods. So, as said in point 1, expressing your intentions matters. If your date field should be immutable, don't confuse developers who will touch your code in the future by using Calendar (unless of course you need timezone awareness).
"Date" is a more intuitive name than "Calendar" for the type of a field that represents a single point in time.
Date object has fewer fields and occupies less memory than Calendar object and is also faster to instantiate.

Using enums and switch statements to control method execution

My question concerns a specific design convention for methods in Java... but really it would apply to C++, C# and others as well. I don't know what this convention is called, but if there is a standardized convention, I would like to know how to find it. In other words, I wish to describe this convention as I have encountered it and be directed to a place where I can learn more.
Consider java.util.Calendar, specificlaly its child, GregorianCalendar. It has an interesting "getter / setter" convention. Let's say that you instantiate this object:
GregorianCalendar cal = new GregorianCalendar();
The fields of cal now describe the instant in time (down to the millisecond) at which the constructor was called.
Now let's say that you want to access the year field or the month field. You would use the following getters.
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
Notice that it's not cal.getYear() or cal.getMonth(). It looks like there is only one getter method for this class and that the return value is determined by the parameter naming the desired field. I would imagine that within the class there is an enum set up to list the fields... and that the getter function itself is composed of some kind of switch statement.
This type of architecture is not described in any of my books... it is however something that I've been using in my current work... but I've been doing it "my" way (basically just making it up as I go along). If there is a standardized way of doing this that other people use... I'd sure love to know it. Specifically, using enums and switch statements to control the execution of methods.
Thanks so much for your time! This is my first question on this site... I have been a long time lurker though. :)
First, note that the two approaches to API design are not mutually exclusive: one could have both a "get by index" and a "get by name", i.e.
int y1 = cal.get(Calendar.YEAR);
int y2 = cal.getYear();
The primary driving force behind getters controlled by an int constant in the Calendar class is uniformity: it lets users of the Calendar class, such as the date formatters, build code that accesses the calendar by index, without further interpretation. For example, if you wanted to implement a formatter that takes a format string and stores a data structure to pull data from a calendar, you would be able to do it with an array of integers: "dd-mm-yyyy" would become int[] {Calendar.DAY, Calendar.MONTH, Calendar.YEAR}, and you would be able to get the data from calendar with a simple for loop.
Note that one of the reasons why Calendar uses integer constants instead of enums is backward compatibility: that Java did not have enum at the time when the Calendar class has been introduced.
Also note that you do not need a switch statement on an enum or int constants to implement Calendar's getters and setters: they can be implemented as direct reads and writes of the calendar component array.
Actually those are not enums. Those are integers instead. Here is the source code of the Calender get method:
public int get(int field)
{
complete();
return internalGet(field);
}
But having a single method accepting a ENUM and returning different values based on that, is good practice.
As far as the design pattern goes, IMHO it is a variation of Factory pattern.
I'm not actually aware of a name for this specific design, although I've seen it used in a few places. It's certainly not one of the standard "Design Patterns" and is really too small to qualify as a design pattern in its own right. It's just a different way of achieving encapsulation over the more traditional way with multiple getters and setters.
If I was to call it something it would probably be something like "flexible getter" or "extensible getter". I.e. "Rather than having multiple setters lets have one flexible getter"
If I was implementing something like this I would probably use the strategy pattern to do it though:
public abstract class Getter<T> {
private T getData(MyCalendar ob);
}
public static final Getter<Integer> MONTH {
Integer getData(MyCalendar ob) {
return ob.month;
}
}
Then your get method just looks like:
<T>public T get(Getter<T> toGet) {
return toGet.getData(this);
}
This uses polymorphism to fetch the data rather than a massive switch statement. It is fully flexible and extensible while still being type safe, etc.

Why would anyone need a thread safe SimpleDateFormat object?

I was looking for the usage of ThreadLocal and landed on this popular page When and how should I use a ThreadLocal variable?
The accepted, highest voted answer says
One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (I'm looking at you, SimpleDateFormat).
And the core part of the code is
return new SimpleDateFormat("yyyyMMdd HHmm");
which won't change or be affected by conncurrent execution, or would it?
Can you please highlight how this could be a issue? And why would we need a thread safe object here?
In other occurrence, I have come across a similar usage with java.security.MessageDigest;, which is also a puzzler to me. It would be great if anyone could explain the reasons behind this, with some helpful code if possible.
SimpleDateFormat extends DateFormat which has setter methods so one thread could be changing properties of the SimpleDateFormat instance while others could be using it and assuming earlier properties or, even worse, have the properties change in the middle of an execution causing internally inconsistent results.
Well, take the first line in format(Date, StringBuffer, FieldDelegate):
calendar.setTime(date);
calendar there is an instance member, so that's obviously not thread-safe there. Firstly there's a date race (since setTime is not synchronized), but even more glaringly, someone could come through and set the calendar's time to something else part-way through the function (calendar's value is accessed in subFormat, which format calls).

How can I test that two Joda-Time DateTime objects are nearly equal?

In unit tests I often have methods that return a DateTime on or about now(). Is there a way to say that the actual DateTime is within a few seconds of the actual DateTime?
That sounds like a bad idea. Unit tests should not depend in any way on the real current time... this is why it's a good practice to inject some interface, called Clock perhaps, in your class's constructors and use that as the source for the current time. Then in your unit tests you can use a special implementation of that for which you can control the time it returns, making your tests deterministic.
That said, I'm sure you could easily write a method that checks that a DateTime is within a certain range of another DateTime by creating new DateTimes by adding and subtracting the desired number of seconds and then comparing.
Turns out, this is pretty easy with Joda Time:
Duration dur = new Duration(sender.getStartTime(), new DateTime());
assertTrue(5000 > dur.getMillis());

Categories