What methods and interfaces do you (almost) always implement in classes?

What methods and interfaces do you always implement in your classes?

Do you always override equals ()? If so, are you also doing hashcode ()? to string()? Are you used to implementing the Comparable interface?

I just wrote code where I needed to implement compareTo () and override equals () to make my program work reasonably; Now I'm starting to see ways to use them everywhere ...

What do you think?

+7
java
source share
14 answers

I usually donโ€™t sell things in advance if I donโ€™t need them.

If my class contains data members, and I plan to store it somewhere, I will usually use equals, hashCode and comparable.

However, I found that most of my classes do not have this problem, so it makes no sense to do this. For example, if your class revolves around functionality on other objects, not data, why bother? If you have one instance or are organized hierarchically (like a GUI widget or window), why bother?

Do not do what you do not need, but always check whether they are needed or not, because Java usually does not warn you.

Also, make sure you use your IDE or something like Apache shared resources to create these functions. Rarely have to manually encode them.

As for toString, I rarely implement it until I find myself in debugging and do not need a better presentation in the Eclipse debugger (for example, instead of the object identifier). I am afraid of implicit conversions and never use toString when generating output.

+13
source share

(Almost) Always toString() .

This is usually useful for debugging purposes.

+8
source share

If you override equals , you (almost always) have to override hashCode . hashCode is that two objects that are equal must have the same hash code. If you redefine equalities, so that equality is based on something other than the hash code of the system identifier, it is possible that two objects will be equal to each other, but have a different hash code.

+4
source share

I think you should never implement what you do not need, or are not sure whether you will need it or not. If it does not add value to your code, do not put it. If you like to synchronize your (single) tests with your code and use them to display options for using your code, then you should not eat something that is not covered by these tests. This includes equals (), hashCode (), compareTo (), etc.

The problem that I see, besides a possible waste of time, is that it confuses the one who reads the code. "Why does this class have equal values? Is it some data value? Can it be part of the collection? Does it make sense to compare instances of this class?"

Therefore, I would say that only implement them when you need them. Therefore, I cannot say that I always apply this and this method. Perhaps toString () is the method that I write most of all, because its usefulness is very much in debugging.

+3
source share

Almost always toString (), itโ€™s a pain to debug and read something about a Class @ 123456 object

equals () and hashCode () when necessary, but always both or nowhere.

The Iterable interface is useful for collectible classes and usually returns only something like innerCollection.iterator (). Comparable may also be useful.

In addition, our company has created some interfaces that I use a lot, for example Displayable (for example, toString, but gives more or different type of information, for example, for logging) and ParseLocatable (for materials that come from the file that we are analyzing, and we want to see in which file and on which line, where, for example, a certain rule was defined (a bit like stacktraces)

+2
source share

Effective Java contains a chapter on how and when to implement toString, equals, hashCode, Comparable, etc. Highly recommended reading.

+2
source share

toString() sometimes very useful for testing purposes, when you are too lazy to write unit tests, it is also useful for hours during debugging.

But I would not recommend implementing Comparable in every object, sometimes it's beautiful, but using it wisely or you get a ton of code that you really don't need.

0
source share

Ditto for toString() and its variants in different languages โ€‹โ€‹and battery life, but I would also like to point you to the Ned Batchelder article on stringification , which is well read and close to my reasoning for this.

0
source share

For CRUD business applications, I always override ToString. This helps to bind List (Of T) to the WinForm control. For example, overriding ToString in the Customer object to return _name automatically displays the value of the customer name when the list (client) is bound to the ListBox control. Useful.

0
source share

I usually use the compareTo method, as well as the toString method. In general, itโ€™s good to know how one instance of a class compares with another instance for sorting and searching. Also, the canceled toString method is great for debugging. You can see the contents of the class (and not just the memory location) represented in such a way that makes sense for the class you wrote.

0
source share

On objects that are mainly used for storing data ("stones"), I find toString and the equals / hashcode contract invaluable. This is because stones are usually transferred and retrieved from collections all the time, primarily Hash (Set / Map) collections, which require equals and hashcode contracts, and it is very easy to see these objects in the debugger if toString. When implementing toString, I always use the Apache Common ToStringBuilder class to display all my properties - this way it is very easy to read the result. I never worry about "implicit conversion" - toString is not intended to be used as anything other than a human read string, that toString can be used to subclass Number to convert to and from this is really just quirks, etc. Production code should never rely on the toString method to convert an object to a string representation, because this is not what it is for it to read a string, so you need to define a different method if the non-standard representation is different from human, but computer code is desirable.

0
source share

For data value classes, I have an AbstractPojo class that uses reflection to implement equals, hashCode, toString and asMap ()

I extend this class for all data value objects, so I do not implement it every time.

0
source share

I do not override ToString, but sometimes I use the DebuggerDisplay attribute, which does the same for debugging purposes and does not impose a release version on the service information.

0
source share

I also found myself overriding the ToString () method. Especially during development. Although code generators help, it becomes very unpleasant to change it every time you rename a member of a class. In fact, I got so angry that I was trying to find a cure, this is what I came up with:

Creates a line of this format: MemberType MemberName = MemberValue

Using:

 string testMember = "testing"; Console.WriteLine(Member.State(() => testMember)); 

Writes the string testMember = "testing" to the console. Here he is:

 public static class Member { public static string State<T>(Func<T> expr) { var member = ExtractMemberFromLambdaExpression(expr); Type memberType = GetTypeOfMember(member); string contents = ExtractContentsFromLambdaExpression(expr); return string.Format("{0} {1}={2}",memberType.Name, member.Name, contents); } static string ExtractContentsFromLambdaExpression<T>(Func<T> expr) { if (expr() == null) { return "NULL"; } string contents = string.Empty; if (expr().GetType().IsArray) { foreach (var item in (expr() as Array)) { contents += item.ToStringNullSafe() + ", "; } contents = contents.Trim().TrimEnd(','); } else { contents = expr().ToString(); } return contents; } static MemberInfo ExtractMemberFromLambdaExpression<T>(Func<T> expr) { // get IL code behind the delegate var il = expr.Method.GetMethodBody().GetILAsByteArray(); // bytes 2-6 represent the member handle var memberHandle = BitConverter.ToInt32(il, 2); // resolve the handle return expr.Target.GetType().Module.ResolveMember(memberHandle); } static Type GetTypeOfMember(MemberInfo member) { Type memberType; if (member.MemberType == MemberTypes.Field) { memberType = GetFieldType(member as FieldInfo); } else if (member.MemberType == MemberTypes.Property) { memberType = GetPropertyType(member as PropertyInfo); } else { memberType = typeof(object); } return memberType; } static Type GetFieldType(FieldInfo fieldInfo) { return fieldInfo.FieldType; } static Type GetPropertyType(PropertyInfo propertyInfo) { return propertyInfo.PropertyType; } } 

A more detailed explanation and how to use it can be found in my blog: General ToString () method

0
source share

All Articles