How To Create Variables That Don't Suck - Writing Clean Java Code

Coding with John
26 Jan 202207:12

Summary

TLDRThis video script emphasizes the importance of using meaningful and descriptive names in programming to enhance code readability and maintainability. It discusses best practices for naming variables, classes, methods, and packages, drawing inspiration from 'Clean Code' by Robert C. Martin. Key takeaways include using context to inform variable names, keeping names concise yet meaningful, and adhering to naming conventions like camelCase for variables and classes. The script also stresses the value of pronounceable names for team communication and the significance of method names that clearly convey their purpose.

Takeaways

  • 🔠 **Meaningful Names**: Use variable names that clearly indicate what is stored and the purpose behind it.
  • 📏 **Context Matters**: The context in which a variable is used affects its naming; for instance, 'catWeightInKilograms' makes sense within a Cat class but not in isolation.
  • 🔑 **Keep It Short**: Variable names should be as short as possible while remaining meaningful and clear.
  • 🗣️ **Pronounceability**: Names should be easy to pronounce to facilitate communication among team members.
  • 🚫 **Avoid Type Information**: Generally, don't include type information in variable names unless necessary for clarity.
  • 🔤 **Naming Conventions**: Follow Java naming conventions such as camelCase for variables and classes, and UPPERCASE with underscores for constants.
  • 📚 **Constants**: Use all caps with underscores for constants, following the convention for enums as well.
  • 📖 **Readability**: Good method names should be verbs or verb phrases that clearly describe what the method does without needing to look into the code.
  • 🛠️ **Single Responsibility**: Methods should do one thing, making naming straightforward and reducing the chance of miscommunication.
  • ⏱️ **Time Investment**: Investing time in choosing good names pays off in the long run by making code more maintainable and understandable.

Q & A

  • Why are good names important in programming?

    -Good names are crucial in programming because they make the code more readable and maintainable, reducing the time and effort required for other programmers or future self to understand the code.

  • What does a meaningful variable name convey?

    -A meaningful variable name conveys both what is being stored in the variable and the purpose behind that variable, making it clear and understandable without needing to look at the code.

  • Why is it important to include context in variable names?

    -Including context in variable names is important because it clarifies what the variable represents, especially when it's not immediately clear from the surrounding code, such as when the variable is not part of a class or a well-defined scope.

  • What is the recommended length for variable names?

    -Variable names should be kept as short as possible while still being meaningful, avoiding overly long or verbose names that do not add clarity.

  • Why should variable names be pronounceable?

    -Variable names should be pronounceable to facilitate communication among team members during discussions, code reviews, or when explaining the code to others.

  • Why should type information generally be avoided in variable names?

    -Type information should generally be avoided in variable names because it can be redundant, as the programming language itself already defines the type, and it can clutter the name, making it less readable.

  • What is the naming convention for variables in Java?

    -In Java, variables should use camelCase, with the first letter of each word capitalized except for the first letter of the variable name, which should be lowercase.

  • How should constants be named in Java?

    -Constants in Java should be named using all uppercase letters with words separated by underscores, following the convention for enums and other constants.

  • What is the difference between class names and variable names in terms of naming conventions?

    -Class names should be nouns and use camelCase with the first letter capitalized, while variable names should also use camelCase but start with a lowercase letter.

  • Why should method names be verbs or verb phrases?

    -Method names should be verbs or verb phrases because they describe actions, which is what methods typically perform, making it clear what the method does when called.

  • How can you tell if a method name is good?

    -A good method name is one that clearly describes what the method does without needing to look inside the code, and it matches the functionality when you do look at the code.

Outlines

00:00

📚 Effective Naming Conventions in Programming

This paragraph emphasizes the importance of using meaningful and descriptive names in programming. It discusses how poor naming can lead to unreadable code and suggests that variable names should clearly indicate what they represent and their purpose. The paragraph provides examples to illustrate the point, such as improving the name 'float num' to 'weightInKilograms'. It also touches on the context of where a variable is used, suggesting that additional context might be needed in certain situations to clarify what the variable represents. The length of variable names is addressed, advocating for conciseness while maintaining clarity. Pronounceability is highlighted as a factor, especially in team environments where code is discussed verbally. The paragraph also advises against using type information in variable names and recommends using single-character variable names only when following established conventions, such as using 'i' for loop iterators. Java-specific naming conventions are briefly mentioned, including camelCase for variables and classes, all lowercase with dots for package names, and all caps with underscores for constants.

05:02

🔍 The Power of Clear Method Naming

The second paragraph focuses on the significance of method names in code readability. It asserts that a well-named method should clearly indicate its functionality without the need to inspect the code. The paragraph contrasts a vague method name 'calculate' with a more descriptive one 'calculateAverage', highlighting how the latter immediately conveys the method's purpose. It stresses the principle of single responsibility for methods, suggesting that if a method name is complex, the method might be doing too much and should be simplified. The paragraph also advises on the length of method names, advocating for clarity over brevity, and encourages programmers to ensure that the method's behavior matches its name to avoid confusion. The importance of choosing good names is reiterated, with a humorous note on the potential for future confusion if names are not chosen carefully. The paragraph concludes with a call to action for viewers to engage with the content and follow the channel for more Java tutorials.

Mindmap

Keywords

💡Naming Conventions

Naming conventions are the standardized rules for choosing the character sequence in identifiers which are used in source code. In the video, the importance of using clear and meaningful names for variables, classes, methods, and packages is emphasized. Good naming conventions make the code more readable and maintainable. For instance, the video suggests using 'catWeightInKilograms' instead of 'num' to clearly indicate what the variable represents.

💡Meaningful Names

Meaningful names are a core aspect of writing clean and understandable code. They should convey the purpose and the content of variables or functions. The video stresses that a good variable name should tell exactly what is being stored and its purpose, like 'weightInKilograms' for a variable holding weight data, which is more descriptive than a generic name like 'num'.

💡Variable Context

The context in which a variable is used can influence its naming. The video explains that the same variable might have different appropriate names depending on where it is located in the code. For example, 'catWeightInKilograms' makes sense when it's a standalone variable, but within a 'Cat' class, simply 'weightInKilograms' might suffice, as the context implies it belongs to the cat.

💡Pronounceability

Pronounceability refers to the ease with which a name can be articulated. The video suggests that variable names should be pronounceable to facilitate communication among team members. This is crucial for discussing code during reviews or when answering questions, as names like 'updateTimestamp' are easier to say and understand than a long, complex string of characters.

💡Avoiding Type Information

The video advises against including type information in variable names as it can be redundant, especially when the type is already defined by the programming language's syntax. For example, 'floatCatWeightInKilograms' is less preferable to 'catWeightInKilograms' because the type 'float' is unnecessary when the context makes the variable's type clear.

💡Single Character Variable Names

Single character names are generally discouraged unless they are part of a widely accepted convention, such as using 'i' for an iterator in a for loop. The video points out that single character names should be used sparingly because they do not convey much information and can lead to confusion, unlike more descriptive names that enhance code readability.

💡CamelCase

CamelCase is a naming convention used in programming where the first letter of each word or abbreviation in a compound word or phrase is capitalized. The video mentions that for variable names, the first letter should be lowercase, while for class names, the first letter of each word should be uppercase. This convention helps in distinguishing between variables and classes at a glance.

💡Constants

Constants are values that do not change during the execution of a program. The video describes the convention for naming constants as all uppercase letters with words separated by underscores, such as 'GRID_SIZE'. This makes it clear that these variables are not meant to be modified and are distinct from other variables.

💡Verbs in Method Names

Method names should typically be verbs or verb phrases that describe the action performed by the method. The video gives the example of 'saveCat', which implies that the method saves a cat to a database. Using verbs makes it clear what the method does, which is important for understanding the functionality without needing to look inside the method's code.

💡Single Responsibility Principle

This principle, mentioned in the video, states that a method should have only one reason to change, meaning it should only perform one task. If a method is difficult to name succinctly, it might be doing too much and should be refactored. This principle helps in creating methods with clear, descriptive names that align with their functionality.

Highlights

Names are crucial in programming as they define classes, variables, methods, and packages.

Using poor names can lead to unreadable code and frustration among team members.

Good variable names should clearly convey what is stored and the purpose of the variable.

Avoid vague names like 'float num'; instead, use descriptive names like 'weightInKilograms'.

Variable names should include units when the context is not clear, such as 'catWeightInKilograms'.

Within a class, you can use shorter names as the context is already established.

Keep variable names short but meaningful; avoid overly long or nonsensical names.

Variable names should be pronounceable for easy communication among team members.

Avoid using type information in variable names unless necessary for clarity.

Single character variable names are acceptable in loops following standard conventions.

Follow naming conventions such as camelCase for variables and classes, and all caps for constants.

Class names should be nouns, while method names should be verbs or verb phrases that describe their actions.

Method names should be clear and concise, telling you what the method does without looking at the code.

If a method is doing too much, it may be difficult to name, indicating a need to refactor.

Good method names should match expectations and not surprise the reader with their functionality.

Choose meaningful method names even if they are longer, as long as they are clear and descriptive.

Taking the time to choose great names improves code readability and maintainability.

The video encourages viewers to leave a like and subscribe for more Java tutorials.

Transcripts

play00:00

names are the building blocks of every

play00:02

single thing we program classes

play00:04

variables methods packages that means

play00:06

using bad names is a great starting

play00:09

point for writing impossible to read

play00:10

code that makes other programmers regret

play00:13

being on your team in this video we'll

play00:14

talk about how to create names that will

play00:16

make your code a pleasure for other

play00:18

programmers or your future self to read

play00:20

and maintain i also have a full java

play00:22

course available in a link down in the

play00:24

description so go check it out a lot of

play00:26

these ideas are heavily inspired by one

play00:28

of my favorite programming books a

play00:30

classic in the programming world called

play00:32

clean code by robert c martin you can

play00:34

find it at the link down in the

play00:35

description let's start with naming

play00:37

variables you probably know you're

play00:39

supposed to use meaningful names but

play00:41

what does that actually mean to me a

play00:43

good variable name will tell you exactly

play00:46

what it is being stored in the variable

play00:48

and will also convey the purpose behind

play00:50

that variable so what if you're looking

play00:52

at someone's code and you see something

play00:53

like float num equals 94.5

play00:58

but this doesn't tell you anything about

play01:00

what this variable actually represents

play01:02

so maybe you know that this is supposed

play01:04

to be a weight so a little bit better

play01:06

name would be

play01:07

weight but if something weighs 94.5

play01:10

that's not really enough information is

play01:12

that pounds kilograms milligrams let's

play01:14

say you find out this is supposed to be

play01:16

a weight in kilograms so probably a

play01:18

better name would be weight in kilograms

play01:21

the context of where a variable appears

play01:23

is also important to how you're going to

play01:25

name it right now since this is a

play01:27

variable just floating in our main

play01:29

method we don't know exactly what this

play01:31

is a weight of is it a rock or a planet

play01:34

or a cheeseburger so in this context it

play01:36

might make sense to add to the variable

play01:38

name to clarify what it's a weight of so

play01:41

if it's a weight of a cat we could say

play01:43

cat weight in kilograms however if we

play01:46

were going to create a weight variable

play01:48

as a property of a cat class here it's

play01:51

fine to just use weight in kilograms as

play01:53

the variable name because we're already

play01:55

within the cat context so it can be

play01:57

assumed here that the name age and

play01:59

weight are all attributes of the cat

play02:02

without having to spell it out in the

play02:04

variable names for the length of your

play02:05

variable names you want to keep them as

play02:07

short as you can while still keeping

play02:09

them meaningful so here cat weight in

play02:11

kilograms tells you everything you need

play02:13

to know without being overly long

play02:15

something like fluffy's weight in

play02:17

kilograms before accounting for the

play02:20

rotational velocity of the earth on the

play02:22

second thursday of the month after i ran

play02:25

out of diet coke that one time this

play02:27

doesn't help anyone make it long enough

play02:29

to be meaningful and no longer you

play02:31

should also make your names

play02:33

pronounceable if you're going to work on

play02:34

a team of developers and anyone who's

play02:36

going to do this professionally will be

play02:39

you're going to have a lot of occasions

play02:40

where you need to talk to somebody else

play02:42

about a piece of code maybe in a code

play02:44

review or if they have a question about

play02:45

it whatever when you do you'll want to

play02:47

be able to talk about those variables in

play02:49

plain english like update timestamp

play02:52

instead of something like update mdms

play02:56

you can maybe also pronounce this update

play02:58

month month day day year year year year

play03:00

hours hours minutes minutes second

play03:02

seconds but you'll also want to be able

play03:04

to say the variable names without

play03:06

passing out from lack of oxygen you

play03:08

should generally avoid using type

play03:10

information in your variable names for

play03:12

example for this cat weight in kilograms

play03:14

you probably don't need to say float cat

play03:17

weight in kilograms one exception to

play03:19

that could be if you're doing some kind

play03:20

of type conversion for example if you

play03:22

need to take in this weight as a string

play03:24

and convert it to a float you might have

play03:27

one variable that's called string cat

play03:28

weight in kilograms and another called

play03:31

float just to differentiate the two in

play03:33

that instance you should also generally

play03:35

avoid using single character variable

play03:37

names unless that single character name

play03:39

is a convention like in a for loop the

play03:42

convention in a standard for loop is to

play03:44

use i for your iterator so everybody

play03:46

will know what the purpose of this i is

play03:48

speaking of conventions if there's some

play03:51

convention for naming what you're naming

play03:53

use it here's a few quick java naming

play03:55

conventions for variables you should use

play03:57

what's called camelcase which means that

play04:00

the first letter of every word in the

play04:02

variable name is going to be capitalized

play04:04

except for the first letter which should

play04:06

be lowercase class names should also be

play04:08

camelcase but with the first letter of

play04:10

the class name capitalized package names

play04:13

should be all lowercase with different

play04:15

sections separated by dots if you're

play04:17

naming a variable that's intended to be

play04:19

a constant like this private static

play04:21

final int grid size the convention is to

play04:24

use all caps with the words separated by

play04:27

underscores for enums it's the same

play04:29

thing all caps with multiple words

play04:32

separated by underscores which makes

play04:33

sense because enums are just another

play04:35

kind of constant you should generally

play04:37

avoid using underscores in other types

play04:39

of variable names that aren't constants

play04:42

class names and variable names should be

play04:44

nouns like cat or update timestamp or

play04:47

max hit points method names however

play04:49

should usually be a verb or a verb

play04:51

phrase and the name should tell you

play04:53

exactly what the method does and if it

play04:55

makes sense what it does that too for

play04:58

example this save cat method saves a cat

play05:01

to a database you already know what this

play05:03

method is going to do

play05:05

just by looking at the name and there's

play05:06

no surprises or anything with what the

play05:08

method actually does in this case we've

play05:10

called this method save cat but we could

play05:13

probably even get rid of the cat from

play05:15

the name because it's implied that this

play05:17

method is going to save whatever it is

play05:19

that's being passed in which in this

play05:21

case is a cat a great method name tells

play05:24

you what it does without having to look

play05:26

inside the code you shouldn't have to

play05:27

look through the code to figure out what

play05:29

it's doing here's an example of a bad

play05:31

method name so it's taking in a list of

play05:34

doubles and it's just called calculate

play05:36

but what exactly is it calculating well

play05:39

you can't know in this case without

play05:40

reading through the method to find out

play05:42

what it's actually doing so then you

play05:44

have to take the time to read through it

play05:45

okay what is it doing oh it's

play05:47

calculating the average of this list of

play05:49

numbers well a better name would be

play05:51

calculate average now you know exactly

play05:54

what this method is doing just by

play05:56

looking at the name methods that you

play05:58

make should only be doing one thing so

play06:00

that should make naming them pretty

play06:02

straightforward if you're having trouble

play06:04

giving your method a simple name it

play06:06

might mean that your method is doing too

play06:08

much and needs to be broken up also if

play06:10

you read the name of a method and then

play06:12

you're surprised by something that

play06:14

happens in that method that probably

play06:16

means either the name is bad or the

play06:18

method is bad and doing something that

play06:20

it shouldn't as before you want to keep

play06:22

method names as short as you can while

play06:24

still keeping them meaningful sometimes

play06:27

to make a method name meaningful might

play06:29

mean a little bit longer of a name but

play06:31

i'd rather read a long method name that

play06:33

tells me exactly what it does then see a

play06:35

short method name that leaves out

play06:37

important details about the method's

play06:39

functionality a good way to know if a

play06:41

method name is good is if you read the

play06:43

method name and then look at a method

play06:45

and you just go yup does pretty much

play06:46

what i thought it would do take the time

play06:49

to choose great names when you're

play06:50

programming otherwise you'll find

play06:52

yourself two years down the line looking

play06:54

at somebody's code going what what is

play06:56

this code even doing who wrote this

play06:57

garbage oh it was me if you enjoyed this

play07:00

video or learned something please let me

play07:02

know by leaving a like and be sure to

play07:03

subscribe so you don't miss each new

play07:05

java tutorial as always thank you so

play07:07

much for watching i really do appreciate

play07:09

you being here with me and i'll see you

play07:10

next time

Rate This

5.0 / 5 (0 votes)

الوسوم ذات الصلة
Clean CodeCode ReadabilityVariable NamingJava TutorialProgramming Best PracticesCode MaintenanceSoftware DevelopmentCamelCaseMethod NamingCode Conventions
هل تحتاج إلى تلخيص باللغة الإنجليزية؟