Top 5 Terrible Java Coding Techniques You Need to Be Using Right Now
Вставка
- Опубліковано 27 чер 2024
- How to write horrifically awful Java code!
Complete Java course: codingwithjohn.thinkific.com/...
Any fool can write good Java code, but it takes an expert to create truly awful, unreadable, impossible-to-maintain Java code. That's what we'll be learning in this lesson!
What makes code bad? There are many ways you can create terrible Java code, and we'll go over a handful of techniques you can use to make other developers hate trying to read your code.
By the end of this video, you'll be able to create Java code so bad that no one will be able to decipher it for years to come.
Learn or improve your Java by watching it being coded live!
Hi, I'm John! I'm a Lead Java Software Engineer and I've been in the programming industry for more than a decade. I love sharing what I've learned over the years in a way that's understandable for all levels of Java learners.
Let me know what else you'd like to see!
Links to any stuff in this description are affiliate links, so if you buy a product through those links I may earn a small commission.
📕 THE best book to learn Java, Effective Java by Joshua Bloch
amzn.to/36AfdUu
📕 One of my favorite programming books, Clean Code by Robert Martin
amzn.to/3GTPVhf
🎧 Or get the audio version of Clean Code for FREE here with an Audible free trial
www.audibletrial.com/johnclean...
🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)
bit.ly/3QPNGko
📹Phone I use for recording:
amzn.to/3HepYJu
🎙️Microphone I use (classy, I know):
amzn.to/3AYGdbz
Donate with PayPal (Thank you so much!)
www.paypal.com/donate/?hosted...
☕Complete Java course:
codingwithjohn.thinkific.com/...
codingwithjohn.com
I died when he said:
"Now you will always know in which line of code you have the problem..." (when you only have 1 line)
I, too, had a good laugh at this. Of course, real programmers understand the distinction between "line of code" vs "executable statement."
XD🤣😂
Should've saved it for April 1.
I didn't even think about that but you're totally right. Missed opportunity there.
@@CodingWithJohn instead now you can make a part two with even more techniques 🔥
Well said! I'm lucky I watched this video for the first time on April 1. 🤣
You can get pretty down thinking about all the things you don't know. Sometimes it is good to be reminded of what you do know. So thanks this was oddly encouraging haha
Here's an advanced technique I like to call Re-try: Surround the contents of each method with a try / catch block, and in the catch block, re-call the method with the same parameters. This will enable the application to continuously run a method until it succeeds. Now you've got persistence both in the business logic AND the data layer! After all, if at first you !succeed...
Another awesome idea for the next one
@@CodingWithJohn Feel free to throw it in there! I'm placing that 'advice' under MIT license.
Do you just catch Exception, or do you also catch Error, so that if you run out of memory, or the stack overflows, you can add allocate some more memory and add a new call to the stack to fix it?
@HrHaakon y e s
@@Astroz87 throw LOL
"You're not here to _think_, your here to code."
I laughed for a solid minute.
I cried, but then again, I'm a tech lead.
I laughed so hard on this one, I almost had a heart attack.
@@Soromeister More or less, I had to pause the video to catch my breath.
You know what Java really misses to be a great language? A goto statement. It's a shame that at some point they decided to get rid of such advanced feature.
and inline assembler
Oh man, one of the things which made disassembled C code hard to read is that assembly instructions jump all around every time you use a loop or an if statement.
Have I not see that I wouldn't be as thankful that there are other ways of doing conditional logic in higher level languages.
Precompiler directives would be pretty handy too! You would also hide a massive amount of boring code in #define section and never read it again. It would be really awesome! No more type-checking induced headache again...
goto is pretty useful if you need to have nested loops (in things like parsing) to break out of the outer loop.
@@Katniss218 only if you don't know how to code properly. Break and continue are everything you should need
Another PRO tip, use as many different libraries as possible. Somebody put a lot of sweat and tears in them and they deserve that they're work is being used. Furthermore you can prove to the team and your boss how much libraries you know!
Just like this, you're on your way to professional JavaScript development!
@@encrypt3d587 lmfao!!!!
Im new to Java. Could you explain why using a lot of libraries might not be the best thing?
@@ThePeacefullplay absolut valid question, I realized my statement was misleading. Of course you want to use libraries, but you want to avoid using different libraries for achieving the same thing within a project. For instance there are tons of different implementations to do a simple REST call. You should stick to the same way across your project. This is especially important when using a more advanced framework (like Spring in my case), you want to use the implementation offered by Spring (RestTemplate). Hope this helps!
This is TERRIBLE code. Really you should be writing ALL the code yourself - no libraries! This way everyone can see exactly how your code works!
lol, the int i global was hilarious. Someone I know spent a lot of time debugging a program when one of the i variables was being accessed outside the loop. Not me of course, I would never...
Good lord I only know a little Java to do random projects every couple months and that'd make me set my project down forever
As a new java programmer, some of these ideas seem really good to implement into my code! Thank you for the tips :)
😨
Nooooooooooo
@@CodingWithJohn What have you done😓😓
NO
There's a SERIOUS logical flaw in your code.
You're passing a single boolean to the if condition, which is nonsense as it could be either true or false. There is a common practice to help Java to understand booleans, like literally: String.valueOf(printBoard).equals("true").
Hope I could help writing more robust code.
Great minds think alike
I prefer “
String.valueOf(printBoard).equals(“true”) == true
“
You need to see if that is true though, so it really ought to be:
if(String.valueOf(printBoard).equals("true") == true) {
// code here
}
@@bobboo101 (int)String.valueOf(printBoard).equals("true") + 41 == 42
wow, what if someone tryes to read your code? its a giga security factor that someone might understand what's going on with those nicely named variables and methods, isnt it better to just call variables like... v1, v2, v3? same goes for methods -> m1, m2, m3.. you could try harder you know! its almost a readible code, who would want that? its not like you write your code once, refactor and then read it hundreds of times... a well written code does not need to be checked upon ever again anyways
These are some great ideas for the next one of these videos
@@CodingWithJohn Code obfuscation done right :) Why obfuscate code if you can make your code unreadable in the first place?
There are actually programs out there to do just that. They obfuscate the code prior to compilation so if/when someone decompiles your java code, they can't figure it out.
why even use more than one variable like, ever, when you can just use an array of objects?
List allTheThings;
You never need to scroll up again to remember your variable name.
Thank me later.
@@kriptonis yeah, you are genius
If you're working at the enterprise level, remember that you gotta work fast and with minimal impact. Every time you're asked to implement a new feature that's similar to another existing feature, never spend the time to factor out commonality. Doing so is error-prone, and when it comes to testing, you now have to test the all the similar existing features as well as the new one, and who knows how long it takes to fix those? There's just too much work for very little gain.
Instead, you copy-paste the most similar feature, renaming it to whatever it is you need. Don't worry if you miss a few things in the comments. No one but you reads this code anyways, and really you should just be reading the code, because you're a professional. Then, you modify it as needed per your customer requirements. Not only does this avoid triggering a retest of existing features, but it scores you points with your customer, who will be very impressed with your turnaround time.
Now I know what some of you more experienced software engineers are thinking. Doesn't this vastly increase your technical debt? Trust me. Your customer doesn't care about that. They're paying top dollar for you to solve theirs and any that you incur ought to be included in the price, and you're gonna get paid that price, because you're working at the enterprise level. I mean, by the time the technical debt really starts causing problems, you'll probably be working somewhere else that pays more because you gotta keep up with inflation.
Do note that after you replace all of the newlines with spaces, you should replace all of the tabs with spaces too. That way, the file size becomes incredibly smaller and your monitor will thank you!
unironically replacing tabs with spaces is the cornerstone of python programming because tabs are inconsistent and weird
Genius! By having more compact code, you don't have to scroll your one line as much to debug or update it!! I highly recommend replacing long and tedious variable names with single letters. Even more compact code YAY!
@@CallMeJoshua Just use braces and semi-colons to write all your Python programs on one line. It is pretty much just like English, and that's typically written in one line with word wrap turned on. Do the same for your Python code, and just read it like a blog.
And if the file was CRLF use double spaces...
People underestimate the power of "teaching" like this. If you do the complete opposite of the way it should be done, you can keep it better in mind how you really have to do it. Great work, John :D
I feel called out a little bit when he talked about making everything global. I made my first game app (which was a chess app, which is again, similar to tic tac toe in the sense that it is doable by a beginner) and I made an object which has bunch of info about the game be a public static member of another class. And for what purpose? So that a lot of info about the chess game can be easily accessed from within anywhere in the program. What was my thinking? Isn't it wasteful to pass around variables everywhere instead of having them in one place only and making them global.
I made this chess app several months ago, I knew my approach was bad before watching this video.
I also have 1 method for sending and receiving moves from the opponent (if your opponent is another PC from the WiFi network) but I am not sure if that is also considered to be bad. The method is then calling a method to receive move and to play a move.
"Do you have an int i variable for your for-loop? Yep, you guessed it! Global." gave me a good laugh
As a javascript developer, I honestly agree with the extra processing power that is saved from putting all the code in one line.
After years of studying at university with no success I gave up and got a job as an intern at a big corporation dealing with large chunks of Java source code. I had no idea how to code in Java but thanks to you I've learnt the very basics and I realized that the source code they used was incredibly flawed. I've now updated the entire code base to follow your tips and standards, and I have to say that everyone is super pleased with the increased file sizes, the massive reduction in lines of code, and the amount of keyboards broken by developers debugging problems on line 1, that last one really adds a lot of enthusiasm to the workspace atmosphere. Thank you for this.
Yours Sincerely,
A now-very-good Java programmer
ProTip: Name your variables, methods and such using really difficult to understand names. Like:
public class c____
{
int i = 0;
int i__ = 1;
int i___ = 2;
int i____ = 4;
}
That way your coworkers will ask you what they do instead of trying to figure it out for themselves.
Hey John. Im having a problem withe the advice you gave in this video. so pretty much, im trying to make a recursive Ken-Ken solver, but every time i replace the recursive method with itself there always appears another call to that method out of nowhere. any idea on how to fix this? Thanks in advance!
You can add support to up-to 10 reappearances of the method and call it a day if it needs more than that, what would need so many calls anyway? That's inefficient!
that's just asking for a stackoverflowerror! you should unroll it and solve it with a switch statement so you also have the added benefit of having pre-calculated all the paths. win-win!
The actual technique you want is a Y combinator. No, I'm serious. that would let you get away with what you're describing.
@@imusthegreat Asking in StackOverflow*
1:04 the fact that you initialize a new cat makes me burst out laughing for some reason.
Oh I do that in probably 70% of my videos. Can't have enough cat objects!
I never thought I could cry of laughter with a programming video yet here I am. The final one line trick was the icing on the cake.
The part from 4 20 to 4 30 sounded like a commercial trying to sel you some dumb thing. The video is great I love it.
I once wrote a Java program for a coding exercise task. It was supposed to run some algorithms, like computing the convex hull, on some input data. Algorithm to use was determined by a positional parameter.
So how do you do that? First, create an enum with constants for each algorithm, so that you can simply pass the argument as a string into the enum constructor to find the algorithm constant. Each constant had a string attached that contained the Java source code of said algorithm.
When the algorithm to use was determined, it took the string, fed that into the Eclipse Java compiler imported for that purpose, and stuffed the result into a byte array.
I then used a ByteArrayClassLoader to load the class from said byte array and accessed the method required via Reflection.
That was hilarious fun to review^^
Thank you for sharing these amazing technics! Now my code looks much cleaner :)
Man, for a minute I just thought I was doing everything wrong!! Hearing about coding from you, John, sounds like "this' the correct way of programming/coding"! I had to double check this video's title a couple of times.
By the way, thank you a lot for so many awesome and instructive videos!
Great video, very informative. Everyone in my job already applies all of your advices, that's how smart this video is.
I wanna cry.
Naming the Variables class "V" reminded me of when I was brand new at coding and actually thought having a smaller file would make my program faster lmao. I'm sure my high school teacher thought my space bar was broken
Actually you can improve the doAnything function by instead of having boolean variables just let the function do all of them and if someone wants to do only some of the functionalities of the function he can always go to the function code and choose which lines to comment / uncomment in order for the function to do what he wants. The benefit of this method is that it would make your function have a lot of comments so it would be clearer.
Glad do have you back, your videos are a lot of help
The first programming tutorial that made me cry. I'm serious! Thanks for that :)
These are great tips! Going to apply them all on the next project! Thanks, John!
Finally something I can relate to.
😂😂😂
Hey John, would you do a video about reflection? It's one of those concepts I always get on paper but I never got the full power of them. Love the videos, thanks!!!
this have to be one of the funniest thing i have watched in awhile, the replace all new line with spaces really got me
Man! You are on fire! I have also purchased your course and I am enjoying ever single lectures! Also in UA-cam. Keep it up Johny!
Awesome! Thanks, I'm really glad you're enjoying them!
@@CodingWithJohn More than you can imagine. let me be a little bit personal. I borrowed some money to join your course. Worth every singe penny. ( so it is more than enjoying) Still a winner. Thnx a lot for providing such great explanation with fun.
I have worked with libraries where the API call is literally just a method named .call(mask) that takes a bitmask of all the possible options - some of which even contradict each other! A true joy to work with 😅
I already do most of this, so I'm way ahead of the curve.
I'm so glad I saw your video today, I'm going to implement all of your tips in my company now, you really need to tell my workmates that 12 tabs indented if-else statements aren't that bad they always think that I'm crazy
Well, nice the see other good self taught programmer out there
I would keep these tips secret. This helps with job security. Your boss will soon see that you understand your code and everyone else's, but your code is just above the understanding of others.
They will be happy to keep you so that at least someone can work with what you've written.
I'm a C++ dev, but the tip with making the loop variable global is a 300 IQ pro coder move. I will definitely use it in my code
Man you are so convincing I almost started to agree with you
I made a game in Java for a highschool project, and did about 90% of this. I had this exact thought process when I was first learning.
Hi. Do you have or could you do a tutorial on socket Communications in Java? Something where you could set up the basics of a microservices architecture?
I love how you explain JAVA to make it make sense. Would you have a UA-cam video for understanding GUI and scanner names or integers? I have not seen it yet..
Hi John
Thank you ALL Of your wonderful videos!! Truly appreciate your hard work!
I have seen people argue about defining a global variable static or NON static & and it’s pros & cons, would it be possible to make one video to explain which way you prefer & why?
(I believe the background might’ve been related to JDBC )
I’m sure it would help thousands of Java enthusiasts like myself in the days, or even decades to come. (Given we still use Java in the future)
Thank you in advance!!
Good video! Also I have a suggestion which is to talk about Annotations in java and reflection
Dangerous video, my man. Someone is going to rock a global variable helper class now
From a newbie's perspective, THIS IS AWESOME! It shows what not to do if a person does not know what they are doing.
Thanks for your effort.
Please make video on sets and map.
Thanks for using my methods John, appreciate it
hey John, awesome videos :) can you cover topics for OCA and OCP exams for java?
Thank you kind guy. I'll use these tips at work!
😨
I loved this video so much. I hope you make more.
When you created the "doAnything" method and started passing booleans, I remember seeing methods that take in one integer, e.g. 10=1010b, which is equivalent to passing (true, false, true, false). What do you think about those. I'm too young to understand why such methods exist, I think
Im not a experienced java developer but this is how I understand it
The integer is changed using with x
I have seen this in c before.
it is a way to reduce the number of arguments that have to be passed and (theoretivally) increase readability, if your function has a lot of boolean inputs that work like "options".
You define the opions outside of the function and then bitwise-or them together when you call it:
#define PRINT_BOARD 1
#define CALL_MUM 1
@@admiralakbar9673 Exactly but then you are not passing true or false you are passing constants which can be easily understood, as opposed to an array of true/false
This can also be used to reduce memory, since a Boolean only needs 1 bit, but most computers can only allocate memory by bytes, so if memory is really limited, you can store multiple bools in a byte and use logic to parse the value.
@@matthewparker9276 Your comment reminded me of studying computer science in highschool. We were learning theory for 2 years straight without any practice (except for excel, photos hop and a couple of programs like that, but we did no programming where all that theory would be useful). Studying theory like that was incredibly boring. I didn't have good grades in that class. I couldn't care less about bits and bytes, CPU, ALU, cache memory, RAM, Endianess, what are compilers, what is assembly, about variable types in programming languages (int, float, boolean etc.) etc.
These things were so removed from being anywhere near relevant.
Yet, as soon as I started studying the practice of computer science (writing computer programmes, first in Pascal, then in C, now in Java) I find all of these things very interesting and relevant.
I wish computer science classes started teaching with practice and theory combined instead of teaching a bunch oftheory before practice which makes theory incredibly dry, boring and irrelevant. Learning what you would consider the basics about computers in the first 2 years of highschool was one of the most boring subjects back then.
Hi John, I really like your videos and explanations.
Could you make a video with examples of CompletableFuture?
Very good video as always. Interestiing to see what's on your mind most of the time; feeding the cat, calling mum, bloody mortgage... :D
The first example with method doAnything plus flags is called _control coupling_ in software engineering. Look for coupling and cohesion to learn about other related problems.
Please be consistent your videos are awesome.
Hey, just a quick question: What IDE do you use for these tutorials? just asking
Good ideas! Let's create a hashtable called "universalAnswers'", which the key is just the set of all questions in the universe unique, and value is there answers. Everything returns in O(1)!
Every once in a while, I try to code something intentionally without using something else. The weirdest one I used was not using if statements (or the ? one liner). Instead, I relied on a while loop for the if, and threw different types of exceptions in a try/catch to either move to the else block or exit the "if/else" statement.
What a savage video to cover horrible coding😅, for a moment I thought what the hack😆.
Anyway nice video 👍
I fell in love with the one line technique ❤
Add Goto to the list and you are exactly where we're at in CNC programming.
It's awful.
I'll see if I can get a goto going in Java for the next one
Hey, great channel! Could you please make a video with complete explanation of Iterator in java? Thanks in advance.
This is unironically helpful in understanding why do we do certain things in programing
This came 9 days too early, but it was still fun to watch. :D
This generated my headache for the day. Thank you! 😅
Hi John, do you have any tutorial with GUI in java?
Hi John, please make a video tutorial on " interface and implementing interfaces in java", java process memory. Thank you so very much.
Great video! I'm in physical pain now.
Thank Jhon greeting from Colombia!
Sometimes the faster way to learn how to do somerhing is to learn first how not to do something. Great content.
thank you for your video! It's amazing!!!!
nice tutorial, make part 2 please!
Awesome stuff!
Thx for the tips i will use it all ❤
Wow, you got me. Here I was thinking that I was learning something useful just to find out this whole video was joke lmao! I've lost 8 minutes to work on my project haha.
Very funny,
I love the style :) :) :) :)
explaining how to do wrong !
and a list of variables made me remind the nice environment variables of the machine ...
find your var in this ...
Where have you been man :D also can you make a introduction video for gui? thnks!
Funny video, all of those hints are a nightmare when you are debugging or adding new features especially replacing all the function calls with multiple lines of code. It would take a lot of time to find all of function calls and even longer when you need to add new features.
Would you be able to help with heat map please?
It was fun, thanks!)))
I like changing all my variable, method, and class names to single characters. It saves me so much memory space!
Once when creating a method that received a string, I mispelled it and put (String LL). Since then, when I need to use a string as a parameter I always call it LL
In my very early days writing code I had a decision tree that I mapped out successfully as ternary operators nested 5 layers deep..
Sure, it was fast... but, at least I had the good sense to include documentation of what was happening.
OH! And this was in Oracle 8i PL/SQL.
I'm indeed using a global class for all my constants. have to try it for variables as well 😀
That one line is interesting enough i should try it.
Do you know the book Implementation Patterns by Kent Beck? Should probably make a series of your version :)
hey john please make a video on the java native methods .. i want to learn how to implement a java method in c++ . tnx
You could've changed the title to "How to write better java code" and would've been able to troll all of us
hey master ! can you make a video only about Static ?
please make your full java course free on youtube. we'd love to go through your videos.
While going through the video at some point of time, everyone must have forgot whether you are telling the right things or pointing out the bad things. You have a really high level of sarcasm going in this video.
Hello John! What color scheme are u using ?
I think it's the default IntelliJ dark theme, just with the background darker than normal
I wrote a program that is working on decompressing or compressing a file (reverse-engineered custom compression in a videogame). I had the file being worked on as a global so any functions could read or write to the file, as needed during the operation. Is it such a sin to do that?
1:10 the code at 179 doesn't feed your cat (which is what you wanted) it just feeds a random cat. I mean its good to feed cats but make sure at some point you also feed your cat so it won't starve ;))
Also, start naming your variables “some_strings”, “variable1”, “var”, “theOtherVar”
I'll definitely have a part 2 at some point, and something like this could be part of it for sure.
This is a good reminder that in many cases I know what I'm doing but a lot of the time I'm lazy as hell
the global int i is hilarious
I got nightmares when he said to make the "i" variable from a for-loop global :D
Well, that was disgusting and went against everything that i've ever known and swore to protect.
Loved it!