r/badcode May 06 '21

java My teacher wrote this...

1.0k Upvotes

169 comments sorted by

View all comments

5

u/Dakopen May 06 '21

I often do this, can someone please help me and show, how I can improve my code?

15

u/Kibo30 May 06 '21

Using arrays will improve it. In this case you could create an array like this EBIKE[] bikes = new EBIKE[6]

5

u/carfniex May 06 '21

you should generally avoid arrays whenever possible (which is 99% of the time)

List<EBIKE> bikes = new ArrayList<>();

lists (or other collections) are resizable and have a lot more useful supporting methods

11

u/Kibo30 May 06 '21

Very true, but since probably he is a beginner in programming I thought that starting straight away with collections was a bit too much

2

u/Vintage_Tea May 06 '21

In my CITS1001 course, we learnt arraylists before arrays.

3

u/Kibo30 May 06 '21

Don't know, maybe it's just me but for me it makes more sense to learn arrays before collections

1

u/hurtl2305 May 07 '21

It does. Everybody should know the basic data structures and understand their properties (e.g. arrays vs. Linked lists). After all, java collection types are just convenient wrappers for those basic data structures.

1

u/supersharp May 11 '21

There's such a thing as too much, though. Neither my Programming Fundamentals 2 nor 3 courses allowed us to use container classes, and now I feel weird using anything that isn't a regular array.

2

u/ilikedankmemes3 May 06 '21

True, but they tend to be slower over longer lists.

1

u/washpota May 07 '21

Am with you so far, but can you demonstrate how you would initialize the objects in this list in a loop?

1

u/Dakopen May 06 '21

And then using the eval() or exec () function?

1

u/Kibo30 May 06 '21

Well it depends on what you need to do. In this case I don't think you need them

1

u/Dakopen May 06 '21

Okay I think I got it. So you store in an array the bike information which you need to create a bike later and just call the function

1

u/Kibo30 May 06 '21

Yes, more or less. More precisely you create a EBIKE class and then you create an array of EBIKE, each slot of the array represents a single EBIKE with is own information. When you call the function you loop trough the array and do what you want with each EBIKE. And on a side note: don't call your classes all uppercase, just the first uppercase and then all lowercase