Правила именования классов java

Naming Conventions in Java

A programmer is always said to write clean codes, where naming has to be appropriate so that for any other programmer it acts as an easy way out to read the code. At a smaller level, this seems meaningless but think of the industrial level where it becomes necessary to write clean codes in order to save time for which there are certain rules been laid of which one of the factors is to name the keyword right which is termed as a naming convention in Java.

For example when you are using a variable name depicting displacement then it should be named as “displace” or similar likewise not likely x, d which becomes complex as the code widens up and decreases the readability aperture. Consider the below illustrations to get a better understanding which later on we will be discussing in detail.

Illustrations:

  • Class: If you are naming any class then it should be a noun and so should be named as per the goal to be achieved in the program such as Add2Numbers, ReverseString, and so on not likely A1, Programming, etc. It should be specific pointing what exactly is there inside without glancing at the body of the class.
  • Interface: If you are naming an interface, it should look like an adjective such as consider the existing ones: Runnable, Serializable, etc. Try to use ‘able’ at the end, yes it is said to try as there are no hard and fast bound rules as if we do consider an inbuilt interface such as ‘Remote’, it is not having ble at the end. Consider if you are supposed to create an interface to make read operation then it is suggested as per naming conventions in java to name a similar likely ‘Readable’ interface.
  • Methods: Now if we do look closer a method is supposed to do something that it does contains in its body henceforth it should be a verb.
  • Constants: As the name suggests it should look like as we read it looks like it is fixed for examples PI, MAX_INT, MIN_INT, etc as follows.
Читайте также:  Placeholder default color css

Naming Conventions in Java

In java, it is good practice to name class, variables, and methods name as what they are actually supposed to do instead of naming them randomly. Below are some naming conventions of the java programming language. They must be followed while developing software in java for good maintenance and readability of code. Java uses CamelCase as a practice for writing names of methods, variables, classes, packages, and constants.

Camel’s case in java programming consists of compound words or phrases such that each word or abbreviation begins with a capital letter or first word with a lowercase letter, rest all with capital. Here in simpler terms, it means if there are two

  • In package, everything is small even while we are combining two or more words in java
  • In constants, we do use everything as uppercase and only ‘_’ character is used even if we are combining two or more words in java.

Type 1: Classes and Interfaces

  • Class names should be nouns, in mixed cases with the first letter of each internal word capitalized. Interfaces names should also be capitalized just like class names.
  • Use whole words and must avoid acronyms and abbreviations.
Classes: class Student < >class Integer <> class Scanner <>
Interfaces : Runnable Remote Serializable

Type 2: Methods

  • Methods should be verbs, in mixed case with the first letter lowercase and with the first letter of each internal word capitalized.
public static void main(String [] args) <>

As the name suggests the method is supposed to be primarily method which indeed it is as main() method in java is the method from where the program begins its execution.

Читайте также:  Isp manager php ini

Type 3: Variables

Variable names should be short yet meaningful.

Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.
  • Should be mnemonic i.e, designed to indicate to the casual observer the intent of its use.
  • One-character variable names should be avoided except for temporary variables.
  • Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
int[] marks; double double answer,

As the name suggests one stands for marks while the other for an answer be it of any e do not mind.

Type 4: Constant variables

  • Should be all uppercase with words separated by underscores (“_”).
  • There are various constants used in predefined classes like Float, Long, String etc.

Type 5: Packages

  • The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, like com, edu, gov, mil, net, org.
  • Subsequent components of the package name vary according to an organization’s own internal naming conventions.

As the name suggests in the first case we are trying to access the Scanner class from the java.util package and in other all classes(* standing for all) input-output classes making it so easy for another programmer to identify.

  • For class and interfaces, the first letter has to be uppercase.
  • For method , variable, package_name, and constants, the first letter has to be lowercase.

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Источник

Правила именования переменных

При именовании классов, методов, переменных и других идентификаторов рекомендуется придерживаться следующих правил:

1. Классы и интерфейсы

  • Первая буква в имени должна быть заглавной.
  • Если в имени содержится несколько слов, то каждую первую букву в последующих словах следует делать заглавной (СamelCase формат).
  • Имена классов следует делать существительными. Например: Cat , Exam , PrintReader .
  • Имена интерфейсам следует давать в форме прилагательных: Comparable , Iterable , Navigable .

2. Методы

  • Первую букву следует делать строчной и далее следовать рекомендациям СamelCase.
  • Имена следует давать в виде сочетания глаголов и существительных: getName , doJob , setLastName .

3. Переменные

  • Первую букву следует делать строчной и далее следовать рекомендациям СamelCase.
  • Присваивайте короткие говорящие имена, чтобы было понятно для чего используется эта перем енная: firstName , buttonHeight .

4. Константы

  • Константы в Java создаются с помощью зарезервированных слов static и final .
  • Имена констант следует задавать только заглавными буквами, а слова в имени разделять знаком подчеркивания: MAX_WEIGHT .

5. Пакеты

  • В имени пакета используются только маленькие буквы.
  • Для коммерческих проектов пакет должен начинаться с com, потом следует имя организации и название проекта. Потом пакеты обычно именуются по какому-то функциональному признаку.

Презентацию с видео можно скачать на Patreon .

  • Пробелы
  • Идентификаторы
  • Комментарии
  • Разделители
  • Ключевые слова
  • Примитивные типы данных
  • Тип данных char
  • Типы byte, short, int, long
  • Числа с плавающей точкой
  • Тип данных boolean
  • Литералы
  • Методы
  • Переменные
  • Прямой код и дополнительный код
  • Преобразование и приведение примитивных типов
  • Ввод с клавиатуры
  • Задания

Источник

Оцените статью