What is good code?
Posted by optiontrader561@reddit | learnprogramming | View on Reddit | 56 comments
As I'm going through the journey of learning computer science and programming one of the things that drives me crazy is the in fighting between great programmers. For example James Gosling I would imagine is known as a great programmer and so is Linus Torvalds. But then I hear Linus talk about how Java is horrible and I'm just thinking well then what is good. But its more then just this, there is arguing about functional vs oop, and much more. Is there any common ground on what is "good"?
StrayFeral@reddit
S.O.L.I.D. i guess
Tobacco_Caramel@reddit
Just make things. Making things is good.
danielt1263@reddit
Good code is broken up into files and there is minimal churn. If you can add a feature by adding files and only maybe changing one file, you have a great codebase. If you can fix a bug by only changing one or two files, then you are in good shape.
If you find yourself having to break open a whole bunch of files to fix a bug or add a feature, if you find that you always are breaking open the same files whenever you have to add a feature or fix a bug, then those are areas of poor code.
This is true whether you use OOP or FP, and no matter what principles or patterns you use.
Kaiser_Steve@reddit
Clean, lean, well-commented upon and docstringed for easy understanding and reference
CodeToManagement@reddit
Good code is the code you’re writing
Terrible code is the code someone else wrote
Bad code is the code you wrote yesterday. But that’s ok. You’re refactoring it today and you only write good code.
Same goes for languages. The best one is the one you use and the bad ones are ones everyone else uses.
To be serious though good code is clean and easy to understand. Well named, and I’d say generally follows at least the single responsibility principle.
Dudeshoot_Mankill@reddit
Tell us more. Lots of comments? Is there a specific guide for writing good comments? How would you explain the single responsibility principle?
dariusbiggs@reddit
Clear over clever
Well documented
Easy to review and maintain
If you came back to it in 6 months, can you understand it 15 minutes of reading (try it on code you wrote six months ago).
jezemine@reddit
Do not add comments saying what each line does. "Add one to x" is not a useful comment.
Good code is code that you can read and easily understand 6 months after you first wrote it.
Bomaruto@reddit
The fewer comments the better, if you need to explain anything with a comment then your code has some issues.
Sometimes it is necessary, but it's a few times a year rare for me.
no_brains101@reddit
Comments should never have to say what the code does.
They should be left in places where you do something which is odd or unintuitive, and they should include WHY it does the thing not what it does.
The more of these comments you leave, either the worse your code is, or the worse the library is that you are interfacing with.
youngbull@reddit
Well, that is a question that requires at least a book's worth of an answer. Check out e.g. "a philosophy of software design" by John Ousterhout.
JayDrr@reddit
I think you should strive to write as few comments as possible. Instead try to choose your variable and function names in a way that comments are irrelevant.
Here is a video on the subject : https://youtu.be/Bf7vDBBOBUA?si=OB96VGW1vt42CC1B
For single responsibility, the underlying idea is to break things down as far as they logically can be, and to compose larger ideas out of smaller ones. The opposite of this being a large class that has lots of optional code.
As a quick example: You have a screwdriver class.
You could pass in construction parameters such as the bit type, maginetic or not, grip type etc.. inside the constructor it calls different construction logic depending on the input parameters. The screwdriver class is responsible for combining the parts, knowing about all the different parts, and constructing each part. Lots of responsibility.
Instead you could have a screwdriver class that only puts together other smaller classes. Then you have a bit class with subclasses for the types of bits.
- The screwdriver is only responsible for combining the pieces, and any methods related to the combined whole. - Each bit knows only about its own construction. And methods related to it self, such as do I fit?
CodeToManagement@reddit
Less focus on comments and more focus on good naming convention is always best. In my mind you should only use comments to explain particularly complex blocks of code - the ideal is method names and variable names tell you what’s going on much better than comments which can go out of date and be irrelevant if people don’t update them with changes.
Single responsibility principle means each class / function has one responsibility. It’s not a hard and fast rule but if you can’t say “this function does x” or “this class contains everything for y” you’re probably over complicating things
Dudeshoot_Mankill@reddit
Are there any books you would recommend?
CodeToManagement@reddit
None I can think of that I’ve personally read recently
Things like the pragmatic programmer are recommended fairly often.
Best thing can sometimes be look at some good GitHub projects to see how they do things.
Confident-Word-9065@reddit
From my experience there is no good or bad code.
There are tonnes of patterns and structures that are agreed upon which helps a group of people to come to agreement or understand easily what the code is doing.
So basically - if the code does what's desired - if multiple people who you work with find it easy to read - if making a change is easy and won't create chaos
People would call it good code.
What does it mean in practice?
The answer is a hated one "it depends". It's similar to asking what's a good life; it's often subjective.
Is it good life to own a house and car ? Is it good life to live in a farm ? Is it good life to be a multi millionaire with cars ?
People will try to tell you what's good because they believe that's good. But it's up to us to find what's goodish Enough to code among our fellow devs and satisfactory enough for us to enjoy and work.
Finally; if you're lost just follow any pattern; functional oop etc... Personally I believe you will find almost all patterns lead to a similar mindset eventually. Each pattern has it's own quirks that's all.
DigThatData@reddit
a question you will be trying to answer for the next 40 years
worst_timeline25@reddit
Good code is Readable, Maintainable and Debuggable by someone who is not you.
thmsbdr@reddit
The only code every can agree is “good,” is no code.
naslock3r@reddit
Also the arguement over functional vs oop is kinda stupid. If ur doing a large complex project that requires collaboration with other devs tho id say oop is preferable, everything is neatly sorted into classes, its easier to update, if u mess a function up in one class it wont break the entire project, u dont have to rewrite the same code multiple times since u can just call a function from its class and reuse it as much as u want. For smaller personal projects using either oop or functional is fine it doesnt rly matter since its more to do w preference
naslock3r@reddit
Good code has:
meaningful variable and function names allowing anyone to look at it and understand what ur code does.
comments to document the code.
enough white space to make it look neat and tidy, being formatted in a way that breaks up the code into smaller easier to read sections rather than a large wall of text.
functions carry out required tasks using the least amount of code possible (efficiency!)
has good error handling to prevent potential errors and prints errors to make debugging easier allowing u to change the code as needed to prevent said errors from reoccuring.
preferably it works as intended lol.
Theres probably more i havent listed but this is enough for a good starting point
SnugglyCoderGuy@reddit
The less effort it takes to read and comprehend what is going on and why, the better the code is.
LettuceAndTom@reddit
Consistency and readability is pretty big. The steps I take are:
Get it to work.
Make it more efficient.
Clean up and comment the code so it's readable.
Bomaruto@reddit
If you want to see what's wrong with Java you look at Kotlin.
Java has definitely improved over the years, but it's still struggling by being uncessary verbose.
And verbosity matters as that makes your code harder to understand.
Zeronullnilnought@reddit
Good code is simple, readable and long rather than short.
I despise trying to decipher some cleverly done code done in as few a steps/words as possible.
However there seems to be some misunderstanding here, when I read good code it makes me think well written code. But you are talking about languages(java) and coding concepts like functional vs oop. These are multiple questions really
Pale_Height_1251@reddit
Linus Torvalds has opinions same as the average redditor does. They are not special or important opinions just because he is Linus Torvalds.
Aggressive_Ad_5454@reddit
Don’t listen to people, big shots or not, when they argue about ideology. Who gives a F?
Just write programs that delight your users and don’t make you crazy when you maintain or debug them.
Seriously.
Opposite-Value-5706@reddit
IME, “Good code” can be found in almost any coding language. So Java may or may not be ‘horrible’ but can do exactly what you want it to do and without error if programmed correctly (Great code within a ‘horrible’ language).
Intelligent-Ad-1424@reddit
Low level programmers like Torvalds basically make the argument that good code is code that doesn’t inherently fight with the internals of the machine. High level languages like Java typically cause a performance hit due to the addition of an abstraction layer. Whether the hit matters enough to your particular use case though, and whether the abstraction layer usage is worth that trade off, is an additional discussion. Some will make the argument that the performance hit is negligible on modern machines, but it’s very easy to accidentally cause further performance slowdowns if you don’t know what the abstraction layer is doing under the hood.
Stargazer__2893@reddit
TL;DR: Good code is code that delivers the desired functionality and is as easy to maintain as possible.
Why our profession is culty on this question
One thing you need to understand about our profession is that most practices have the following pattern:
Some smart people devise an approach that fit their needs and allowed them to produce some exceptional value.
Some non- or less technical people saw the money and started either selling this approach as "the right way to do things" for money or telling their engineers to start doing it because they think it will make more money.
The purpose behind the practice is lost, but people nevertheless dogmatically follow the practice since it's "the right way to do things" and some smart people said to do it.
You can see this with agile, OOP, functional programming, every framework you've ever used, etc.
What you actually need to do
Writing quality, maintainable code is about minimizing complexity, and there are multiple kinds of complexity.
Computer efficiency - How efficiently your machine can execute your code.
Local complexity - How easy it is to understand a file you're looking at on the screen.
System complexity - How easy it is to understand how all your files interact with one another across your entire application.
Generally speaking you need to sacrifice one or two of these in other to achieve the other. Rarely can you get all three at once.
Object-oriented programming and functional programming are approaches for managing system complexity. With OOP, you're defining components as "objects" with specific functionalities so that you have a system-wide vocabulary for what things do. Furthermore, by making things modular, you limit how much you have to fit in your head at any one time in order to change the system.
With functional programming, you're trying to isolate state to as few places as possible and keep all your functions throughout your system simple and deterministic, so when you're writing a function you have a finite number of ways that function can behave and it's simple to create, write, and test.
I have met very few engineers who understand why OOP and FP are desirable. They just follow them dogmatically because they were taught them in college and don't know how to do things another way. Furthermore, they often do them wrong. They think simply using functions is FP or just defining boilerplate objects is OOP without actually writing coherent modules to reduce system complexity.
If you'd like a more robust discussion on this, my favorite book on the topic is "A Philosophy of Software Design" by John Ousterhout. Hope you found this comment helpful.
TheHollowJester@reddit
This guy fucks.
ruat_caelum@reddit
All code is bad
Every programmer occasionally, when nobody’s home, turns off the lights, pours a glass of scotch, puts on some light German electronica, and opens up a file on their computer. It’s a different file for every programmer. Sometimes they wrote it, sometimes they found it and knew they had to save it. They read over the lines, and weep at their beauty, then the tears turn bitter as they remember the rest of the files and the inevitable collapse of all that is good and true in the world. This file is Good Code. It has sensible and consistent names for functions and variables. It’s concise. It doesn’t do anything obviously stupid. It has never had to live in the wild, or answer to a sales team. It does exactly one, mundane, specific thing, and it does it well. It was written by a single person, and never touched by another. It reads like poetry written by someone over thirty. Every programmer starts out writing some perfect little snowflake like this. Then they’re told on Friday they need to have six hundred snowflakes written by Tuesday, so they cheat a bit here and there and maybe copy a few snowflakes and try to stick them together or they have to ask a coworker to work on one who melts it and then all the programmers’ snowflakes get dumped together in some inscrutable shape and somebody leans a Picasso on it because nobody wants to see the cat urine soaking into all your broken snowflakes melting in the light of day. Next week, everybody shovels more snow on it to keep the Picasso from falling over. There’s a theory that you can cure this by following standards, except there are more “standards” than there are things computers can actually do, and these standards are all variously improved and maligned by the personal preferences of the people coding them, so no collection of code has ever made it into the real world without doing a few dozen identical things a few dozen not even remotely similar ways. The first few weeks of any job are just figuring out how a program works even if you’re familiar with every single language, framework, and standard that’s involved, because standards are unicorns.
huuaaang@reddit
Good code ya when you can walk away from it for a year and when you get back it still makes sense.
dudleydidwrong@reddit
Good code works. It does what it is supposed to do.
Good code contains few, if any bugs. It is structured so that it may be examined and tested.
Good code is easily maintained. Bugs may be fixed. The code may be adapted to changing execution environments and user needs.
azkeel-smart@reddit
Let's paraphrase it. What is a good tool? Is it a hammer? Is it a screwdriver? Why nobody can agree on the best tool?
Best tool only exist in a context of the job that needs to be done and your skill in using that specific tool. Some problems needs functional programming and some problems need OOP for the best solution. Some problems are easier to solve in Python and some are easier to solve in C#. There is no, one best tool.
Caramel-Makiatto@reddit
Readable AND maintainable. Contains comments explaining blocks of code and what it interacts with. Variables use common naming conventions and consistently (camel case, snake case or pascal case). Things are located where you expect to find them, not just mixed together in the order you wrote them. Don't write lines that are overly long and avoid nesting more than necessary, try to make use of guard statements and similar concepts.
Don't expect that you'll master this right away, just aim to keep things tidy as you go and later on do an introspective of what could have been done better. If you spend all of your time doing clean up then you'll never get shit done in time and likely just burn yourself out.
gunjanj2003@reddit
Good code isn’t just code that “works”, it’s code that’s clear, maintainable, and easy to reason about. Anyone (including future you) should be able to read it and quickly understand what’s going on without mental gymnastics. It follows solid naming conventions, avoids unnecessary complexity, and handles errors gracefully.
Good code is also modular, broken into small, reusable pieces rather than one giant function doing everything. It’s efficient, but not at the cost of readability. It includes comments only where needed and uses meaningful variable names instead of random letters.
Most importantly, good code solves the right problem in a clean way. It’s not about writing “fancy” code, it’s about writing something reliable, scalable, and won’t make your teammates (or your future self) hate you.
SynapseNotFound@reddit
Good code:
Required:
Works ✅
Easy to read ✅
Optional:
Easy to maintain ✅
Easy to scale ✅
Depending on what youre doing, the optional parts can be skipped
mapadofu@reddit
Good code does what it says it does when you read it.
gooddelorean@reddit
C is good. Java is a bytecode interpretation framework, which is also what BASIC was, but with BASIC you didn't even have to pretend to assemble it, and you'd not be silly enough to bog it with fat software. You could say Java is SUPER BASIC.
ButchDeanCA@reddit
To understand what good code is you need to think about how it is achieved. Good code is something where the collective agree that a piece of code is good or not. It normally is a group of experienced programmers who come together and talk through issues that are found and fix them through mutual agreement.
Notice I made it clear that more than one person is required to judge what good code is and alluded to them having knowledge of said code? This is how code reviews are conducted and if done properly, you get “good code”.
Great_Guidance_8448@reddit
> But then I hear Linus talk about how Java is horrible
lol
HealyUnit@reddit
"Conan! What is good code?"
"To crush the bugs, see them resolved before you, and to hear the jubilations of the devs."
KC918273645@reddit
Good code is the one which looks so simple a a child could write and understand what it does. Writing such code takes a really good programmer, though...
Master-Rub-3404@reddit
Code that can be easily read/understood by a complete stranger years in the future without having to ask you.
dnult@reddit
Consider that Linus' view is primarilu from a kernel development perspective which is very different than typical app development. Kernel code has to adhere to some pretty strick design patterns for many reasons.
I consider "good code" to be code that makes sense and can be easily extended to support new features. There is nothing worse to me than taking on a development exercise that should only take a day or two, but ends up being a 2 week refactor job.
AdElectronic50@reddit
Good code is code that works and that you can understand as you read it.
Lotton@reddit
Code you can put away for months and come back later to and able to understand it
POGtastic@reddit
Any code that you can completely forget about as a solved problem is good. In almost any codebase, there is code that you dread as a ticking time bomb. "maaan I really hope that nothing changes about our requirements, because if it does I'm going to have to refactor that mess." That's shitty code.
A very important thing to understand here is that the requirements of your program will dictate what works as code and what doesn't. Linus has Opinions about languages and coding practices because he has dedicated his entire life to kernel programming. The problems that you face in kernel programming are really different from the problems that Java is designed to solve!
Informal_Rule_8604@reddit
Depends on the language but I think the biggest thing is to not overcomplicate your code.
CodeTinkerer@reddit
It's kind of like you know it when you see it. It should be readable and preferably on the shorter side. It should be well-documented and not repetitive.
It's like "what makes for good writing" when writing fiction (or non-fiction). I mean, some general principles apply, but it's hard to nail it down precisely.
TheCozyRuneFox@reddit
First every language will have advantages and disadvantages and which one is better depends on what you are doing and personal preference.
Name your variables, functions, classes, files, etc in a descriptive/informative way that is consistent with the rest of the code base. if you use camel case for function Mae’s, use it for every function. Consistency and short but informative names is key.
As for OOP vs Functional, it depends on what it is you are doing and what the rest of the code base is. Either is fine so long as you are consistent and follow good practices fir each style respectively
Groson@reddit
Well documented and well structured and scalable. Think to yourself: if you died tomorrow how easy would it be to pick up your work? There's your answer.
SeriousDabbler@reddit
This is highly contextual and depends on individuals' sense of esthetics. Code doesn't just have form, though, and one of its functions is readability. There are some moderately clear thoughts out there about what constitutes bad code, though. I'd look up Martin Fowler's refactoring book. He catalogues a number of "code smells" which you might start to recognize
BusyClerk3287@reddit
Totally subjective and dependent on context. The only universal standard I can think of across all languages and types of software is Don’t Repeat Yourself. That in itself is a great condensation of what makes good code: Efficient, simple, and modular.
mehneni@reddit
Horses for courses. And strong personalities have strong opinions. You don't write an OS or programming language from scratch if you don't have any strong convictions on doing something better than others.
Nobody would write an OS in java (well almost nobody) and writing a web application in C is not the best idea.
There is probably no common ground on what is good that is accepted by all. But there is a lot of common ground on what is not.