• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
Bartenders:
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

How can I reduce this redundancy in my code?  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I'm going through a little project I did a while back and seeing if I can organise the code and replace parts of it. There's a merge sort implementation in here that works but has a lot of redundancy since there are Arrays of 3 object types that could need sorting and each requires sorting based on different arguments. I've just started getting into funtional interfaces and lambdas and have been scratching my head figureing if I could implement here. Any pointers?

 
Master Rancher
Posts: 1162
18
Firefox Browser Hibernate IntelliJ IDE Java MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could reduce your 6 methods to two if you use generics...
 
Marshal
Posts: 63454
207
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I presume that code works, and I presume you have been told to write your own merge sort code, rather than using the ready‑made methods in List and Collections.
Why have you marked everything static? Is that a utility class? In which case it is probably right to have everything static, but you should add a private constructor, for reasons explained here.
Daniel is right that you will need to make that method generic, which you can read about in the Java™ Tutorials (third section down). But before that, I suggest you read the Java™ Tutorials section about ordering objects.

The reason you have so much redundancy is that you are taking implementation details of your Reservation class into the Sorting class. The Sorting class has no need to know about date or ID or anything like that. In fact, that sort of thing couples the two classes tightly; any changes in Reservation require a corresponding change in a Sorting method (‍) If you have read the two links I showed you, you will know what sort of object to pass as an argument to your sort methods. So yoiu can rwite the correct type rather than my XXX. You can even make such objects fields of the Reservation class (or Bill). You will end up with this sort of thing (there are other ways to do it):-Then you can create a generic method, as Daniel said, to sort any kind of List.

By the way, if you use dates, don't use this and don't use this nor its subclasses. Use this; read about dates in the Java™ Tutorials.
 
Enric Haber
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Welcome to the Ranch

I presume that code works, and I presume you have been told to write your own merge sort code, rather than using the ready‑made methods in List and Collections.
Why have you marked everything static? Is that a utility class? In which case it is probably right to have everything static, but you should add a private constructor, for reasons explained here.
Daniel is right that you will need to make that method generic, which you can read about in the Java™ Tutorials (third section down). But before that, I suggest you read the Java™ Tutorials section about ordering objects.

The reason you have so much redundancy is that you are taking implementation details of your Reservation class into the Sorting class. The Sorting class has no need to know about date or ID or anything like that. In fact, that sort of thing couples the two classes tightly; any changes in Reservation require a corresponding change in a Sorting method (‍) If you have read the two links I showed you, you will know what sort of object to pass as an argument to your sort methods. So yoiu can rwite the correct type rather than my XXX. You can even make such objects fields of the Reservation class (or Bill). You will end up with this sort of thing (there are other ways to do it):-Then you can create a generic method, as Daniel said, to sort any kind of List.

By the way, if you use dates, don't use this and don't use this nor its subclasses. Use this; read about dates in the Java™ Tutorials.



Thanks! I will give those links a read before I continue any further. You're right so far i've been using the sorting class as a utility class but it has a lot of redundancy since the same algorithm is repeated for each object type and there's private methods to take care of the merging based on different values. Hopefully what i'm missing wil become clear one I get thorugh the tut. cheers.
 
Enric Haber
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is the reason for provitizing classing good coding etiquette? So that other devs working on the software don't make instances of it?

Anyway the way I did things seems so inefficient after I read the ordering tut. Now I made all the classes I want sortable implement Comparable.



and gave them one or more Comparator variables to make them sortble by unnatural ordering.



And using these in the sorting algo does the job but I still need to repeat the same merge process to account for every sort value / object type. I'm guessing this is where that generics tut comes in? I'll read it first thing tomorrow!

 
Campbell Ritchie
Marshal
Posts: 63454
207
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Enric Haber wrote:Is the reason for provitizing classing good coding etiquette? So that other devs working on the software don't make instances of it?

Not sure I understand that question. A utility class with all static members doesn't need any instances. You use a private constructor to prevent instantiation at all.
It is possible to cause weird errors if you call a static method on an object reference; the runtime type of the reference and the runtime type of the method may be different. That can be cured by always calling static methods on the class name.


. . .  read the ordering tut. Now I made all the classes I want sortable implement Comparable. . . .

Please avoid abbreviations like “tut”, which are difficult to read, particularly for people who didn't learn English as small children.
It isn't necessarily right to make everything implement Comparable. Have you read the documentation for Comparable<T>? It says it implements a total ordering, and that means you would have one feature you sort by. If you want to sort by different features, you would require a Comparator.

I'm pleased to see you know how to write a λ, but that formula looks complicated. Go through the Comparator documentation and you will find methods which return ready‑made Comparator instances. If getID() returns an int, you can shorten that toThat technique also doesn't have the slight eccentricity your example displays

And using these in the sorting algo does the job but I still need to repeat the same merge process to account for every sort value / object type. I'm guessing this is where that generics tut comes in? . . .

Yes, I think so.
Don't call a List array or newArray; those names can cause confusion.
 
Enric Haber
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:
I'm pleased to see you know how to write a λ, but that formula looks complicated. Go through the Comparator documentation and you will find methods which return ready‑made Comparator instances. If getID() returns an int, you can shorten that toThat technique also doesn't have the slight eccentricity your example displays



ah! thanks for that. My code is full of those 'eccentricities' and I'll be working on removing them and streamlining everything.

Mild success this morning with the generics: Produced a generic merge sort but it only sorts by ID(int), when I send any string comparators (eg. by name) it just reverses the list.

//the comparator


//when sorting is required:




 
Campbell Ritchie
Marshal
Posts: 63454
207
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Enric Haber wrote:. . . . My code is full of those 'eccentricities'  . . .

As long as you know waht the eccentricity is

Don't try a merge sort on Guests or anything. Try it on an int[]. You will need things like if (i >l j) ... When you have got that working, copy it exactly into a generic methodThen you etend that to take a Comparator<T> as a second parameter. Remember the algorithm is exactly the same; the only difference is the test if (myComparator.compare(t1, t2)i > 0) ... Or similar.
 
Campbell Ritchie
Marshal
Posts: 63454
207
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Earlier today, I wrote:. . .  You will need things like if (i >l j) ... . . .

You will also need to work out how many spellling mistaikes I have made
 
Saloon Keeper
Posts: 9856
199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question is, why are you implementing a sort at all? Java has a built in generic sort algorithm. Are you doing this as an exercise?
 
Campbell Ritchie
Marshal
Posts: 63454
207
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe this is an algorithms exerise to write a merge sort program.
 
Sheriff
Posts: 13174
219
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:It is possible to cause weird errors if you call a static method on an object reference; the runtime type of the reference and the runtime type of the method may be different.


Not sure what weird errors you're referring to here, Campbell. Not sure what you're referring to as the "runtime type of the method" either. Methods don't have runtime types vs compile-time types. You're probably referring to late/dynamic binding done at runtime vs. early/static binding done at compile time.

Static methods are not polymorphic and are bound/resolved based on the declared type at compile time, regardless of whether you're referencing them through an object or class. The worst you can get from accessing a static method through an object reference is confused and get results that you weren't expecting. But that's because you misunderstand how the binding works. Java, however, will know exactly what to do and use the declared type to bind/resolve the call at compile time.

You can even demonstrate this in jshell:

  1 : class Foo {
         static void bar() {
            System.out.println("Foo.bar()");
         }
         void foo() {
            System.out.println("Foo.foo()");
         }
      }
  2 : class Bar extends Foo {
         static void bar() {
            System.out.println("Bar.bar()");
         }

         @Override
         void foo() {
            System.out.println("Bar.foo()");
         }
      }

jshell> Bar bar = new Bar()
bar ==> Bar@5c7fa833

jshell> bar.bar() // statically bound
Bar.bar()

jshell> bar.foo() // dynamically bound
Bar.foo()

jshell> Foo foo = bar
foo ==> Bar@5c7fa833

jshell> foo.bar() // statically bound
Foo.bar()

jshell> foo.foo() // dynamically bound
Bar.foo()
 
Campbell Ritchie
Marshal
Posts: 63454
207
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I phrased that badly, didn't I.
If you declare a reference as a superclass type, then all instance methods are polymorphic and called by runtime binding, as Junilu said more accurately than I did. So the runtime type of an object determines which version of the method is called:-I used more or less the same technique as Junilu. You can see that the static method follows which type the reference is declared of; polymorphism and overriding don't apply to static methods. Had I called MiddleClass.staticMethod(789); I would have got the expected output of MiddleClass 789.
 
We find this kind of rampant individuality very disturbing. But not this tiny ad:
Become a Java guru with IntelliJ IDEA
https://www.jetbrains.com/idea/
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!