Coding Conventions Java Coding Convention JavaBeans Naming Convention.

Презентация:



Advertisements
Похожие презентации
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
Advertisements

Operators and Arithmetic Operations. Operators An operator is a symbol that instructs the code to perform some operations or actions on one or more operands.
Unit II Constructor Cont… Destructor Default constructor.
Data Types in C. A Data Type A data type is –A set of values AND –A set of operations on those values A data type is used to –Identify the type of a variable.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
1 © Luxoft Training 2012 Inner and anonymous classes.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
Basic Input - Output. Output functions printf() – is a library function that displays information on-screen. The statement can display a simple text message.
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
1/27 Chapter 9: Template Functions And Template Classes.
Here are multiplication tables written in a code. The tables are not in the correct order. Find the digit, represented by each letter.
Section 2.1: Use Inductive Reasoning Conjecture: A conjecture is an unproven statement that is based on observations; an educated guess. Inductive Reasoning:
Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Customer-to-Provider Connectivity with BGP Connecting a Multihomed Customer to Multiple Service.
In mathematics, the notion of permutation is used with several slightly different meanings, all related to the act of permuting (rearranging) objects.
© Luxoft Training 2013 Using Reflection API in Java.
1 When And How To Make Interfaces Work For You Advanced OO Techniques Alex Herbstritt Principal Software Engineer, Progress Software Session 102.
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
SPLAY TREE The basic idea of the splay tree is that every time a node is accessed, it is pushed to the root by a series of tree rotations. This series.
Транксрипт:

Coding Conventions Java Coding Convention JavaBeans Naming Convention

Java Coding Convention (Соглашения о кодировании в Java) Зачем использовать соглашения о кодировании? – 80% стоимости разработки программного обеспечения приходится на поддержку – Программный код разрабатывается и поддерживается разными программистами – Соглашения о кодировании улучшают читабельность кода – Если компания разрабатывает программное обеспечение на заказ, то заказчик обязательно делает ревизию кода. Поэтому код должен был должным образом разбит на пакеты и написан в соответствии с соглашениями о кодировании. Соглашения о кодировании должны соблюдаться каждым разработчиком. Без исключений! Кто уже знаком с соглашениями о кодировании? Открываем и читаем «соглашения» по ссылке –

Java Coding Convention Соглашения касаются: – Наименования файлов – Организации файлов (количество строк, оформление класса верхнего уровня комментариями и т.д.) – Отступы – Комментарии – Декларации – Команды – Пробелы и пустые строки – Соглашения об именовании – Программные практики Рассмотрим сегодня

СОГЛАШЕНИЯ ОБ ИМЕНОВАНИИ Java Coding Convention

Соглашения о именовании 1/4 Пакеты Классы Интерфейсы Методы Переменные Константы

Соглашения об именовании 2/4 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, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, Subsequent components of the package name vary according to an organizations own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names. com.sun.eng com.apple.quicktime.v2 edu.cmu.cs.bovik.cheese Classes Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole wordsavoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). class Raster; class ImageSprite; InterfacesInterface names should be capitalized like class names. interface RasterDelegate; interface Storing;

Соглашения о именовании 3/4 Methods Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. run(); runFast(); getBackground(); Variables Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed. Variable names should be short yet meaningful. The choice of a variable name should be mnemonic that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary throwaway variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters. int i; char c; float myWidth; ConstantsThe names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores (_). (ANSI constants should be avoided, for ease of debugging.) static final int MIN_WIDTH = 4; static final int MAX_WIDTH = 999; static final int GET_THE_CPU = 1;

Соглашения о именовании 4/4 В списке рассмотренных соглашений нет соглашений об именованиях getter/setter. Это соглашение относится к JavaBeans Specification (будет рассмотрено на дальнейших слайдах).

СОГЛАШЕНИЯ О ПРОГРАММНЫХ ПРАКТИКАХ Java Coding Convention

1. Providing Access to Instance and Class Variables Dont make any instance or class variable public without good reason. Often, instance variables dont need to be explicitly set or gottenoften that happens as a side effect of method calls. One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then its appropriate to make the classs instance variables public.

2. Programing Practice: Referring to Class Variables and Methods Avoid using an object to access a class (static) variable or method. Use a class name instead. For example: classMethod(); //OK AClass.classMethod(); //OK anObject.classMethod(); //AVOID!

3. Constants Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values. for (int i=0; i

4. Variable Assignments (1/2) Avoid assigning several variables to the same value in a single statement. It is hard to read. Example: fooBar.fChar = barFoo.lchar = 'c'; // AVOID!

4. Variable Assignments (1/2) Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example: d = (a = b + c) + r; // AVOID! should be written as a = b + c; d = a + r;

5. Parentheses It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to othersyou shouldnt assume that other programmers know precedence as well as you do. if (a == b && c == d) // AVOID! if ((a == b) && (c == d)) // USE

6. Returning Values (1/2) Try to make the structure of your program match the intent. Example: if (booleanExpression) { return true; } else { return false; } should instead be written as return booleanExpression;

6. Returning Values (2/2) Similarly, if (condition) { return x; } return y; should be written as return (condition ? x : y); If an expression containing a binary operator appears before the ? in the ternary ?: operator, it should be parenthesized. Example: (x >= 0) ? x : -x;

JAVABEANS

Java Beans Specification Спецификацию можно найти по ссылкам: – – documentation/spec html documentation/spec html

Назначение JavaBeans JavaBeans были созданы с целью определить компонентную модель программного обеспечения для Java – Повторно-используемые компоненты – Возможность получать свойства и методы компонента – Возможность использовать компоненты в визуальных утилитах, в других компонентах и программах (GUI-элементы для «визуального» программирования, составные документы и т.д.) Компоненты JavaBeans должны соответствовать соглашениям об именовании и проектировании JavaBeans (соглашения указаны в JavaBeans spec) Предполагалось, что JavaBeans обладают следующей функциональностью: – Поддержка «интроспекции» – Поддержка «событий» – Поддержка «свойств» – Поддержка сохранения состояния JavaBeans – это был ответ технологиям Microsoft: OLE, COM, ActiveX

Что интересует нас в JavaBeans Нас интересуют только соглашения об именовании для JavaBeans – так как они широко используются в популярных Java-фреймворках для доступа к свойствам объектов

JavaBeans vs Enterprise Java Beans JavaBeans Enterprise Java Beans Enterprise Java Beans (EJB) – часть платформы Java EE. Будем рассматривать позже.

Что такое JavaBean? JavaBean – это обычный Java класс: – public класс верхнего уровня – implements java.io.Serializable – Конструктор по умолчанию (без аргументов) – Наличие getter/setter для доступа к свойствам бина

Java Beans Properties Свойства – это именованные атрибуты, изменение которых ведет к изменению состояния или поведения компонента Для программного доступа и изменения свойств должны быть предоставлены методы get/set

Свойства Для доступа к свойству должны быть предоставлены методы: public get (); public void set ( a); Для булевых свойств допустимо название getter-метода: public boolean is (); Пример 1: MyType foo; public MyType getFoo(); public void setFoo(MyType f); Пример 2: Boolean foo; public boolean isFoo(); public void setFoo(boolean f);

Индексированные свойства Пусть дано свойство типа [] (массив) Методы доступа public get (int a); public void set (int a, b); Пример: public MyType[] getFoo(); public void setFoo(MyType a[]); public MyType getFoo(int a); public void setFoo(int a, MyType b);

Определение имен свойств Для определения имени свойства компонента (по названиям getter/setter используются следующие правила): FooFoo fooFoo Z z URL

JavaBean Example public class SimpleBean implements Serializable { /* Properties */ private String name = null; private int age = 0; /* Empty Constructor */ public SimpleBean() {} /* Getter and Setter Methods */ public String getName() { return name; } public void setName(String s) { name = s; } public int getAge() { return age; } public void setAge(int i) { age = i; } }