Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
73 views

Coding Guidelines

Common coding practices include using camelCase for variable names, avoiding global variables, following principles of encapsulation, avoiding duplicate code, properly handling exceptions, limiting variable scope, and following SOLID principles of single responsibility, open/closed, Liskov substitution, interface segregation, and dependency inversion. The document also provides guidelines for annotations, logging, line lengths, line wrapping strategies, code refactoring and other best practices.

Uploaded by

Kanishk
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Coding Guidelines

Common coding practices include using camelCase for variable names, avoiding global variables, following principles of encapsulation, avoiding duplicate code, properly handling exceptions, limiting variable scope, and following SOLID principles of single responsibility, open/closed, Liskov substitution, interface segregation, and dependency inversion. The document also provides guidelines for annotations, logging, line lengths, line wrapping strategies, code refactoring and other best practices.

Uploaded by

Kanishk
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

Common Coding Practices


1.1.Variable Naming and Access
1.1.1.Variable Naming
CamelCase ballRadius
Underscore between words -> ball_radius at start (private/protected) -> _speed
Uppercase for constants GRAVITY
Capitalize the first word for classes Person()
1.1.2.Variable Access
Avoid global variables unless it drastically simplifies code.
Use your intuition. If the variable is used throughout the entire program, global
is probably fine.
Avoid public variables for classes.
1.1.3.Enforce the idea of encapsulation
Instead of public variables, create getters and setters.

1.2. Code Reuse


Avoid having duplicate code
More code → more bugs (usually)
More code → more things to fix
More code → more time to implement
More code → lower grade!
1.3. Don't ignore exceptions
You must never do the following:
void setServerPort(String value) {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) { } }
1.4. Don't catch the generic exception
You should not do this:
try {
someComplicatedIOFunction(); // may throw IOException
someComplicatedParsingFunction(); // may throw ParsingException
someComplicatedSecurityFunction(); // may throw SecurityException
// phew, made it all the way
} catch (Exception e) { // I'll just catch all exceptions
handleError(); // with one generic handler!
}
1.5. Don't use finalizers
We don't use finalizers. There are no guarantees as to when a finalizer will be
called, or even that it will be called at all. In most cases, you can do what you
need from a finalizer with good exception handling. If you absolutely need it,
define a close() method (or the like) and document exactly when that method needs
to be called. See InputStream for an example. In this case, it is appropriate but
not required to print a short log message from the finalizer, as long as it is not
expected to flood the logs.
1.6. Use spaces for indentation
Use 4 space indents for blocks:
if (x == 1) {
x++;
}
Use 8 space indents for line wraps:
Instrument i = someLongExpression(that, wouldNotFit, on, one, line);

1.7. Limit variable scope


The scope of local variables should be kept to a minimum (Effective Java Item 29).
By doing so, you increase the readability and maintainability of your code and
reduce the likelihood of error. Each variable should be declared in the innermost
block that encloses all uses of the variable. Local variables should be declared at
the point they are first used. Nearly every local variable declaration should
contain an initializer. If you don't yet have enough information to initialize a
variable sensibly, you should postpone the declaration until you do.
1.8. SOLID Principles
Your code must follow SOLID principles.
1.8.1. Single Responsibility
The single responsibility principle is one of the most commonly used design
principles in object-oriented programming. You should apply it to classes, software
components, and microservices.
To follow this principle, your class isn’t allowed to have more than one
responsibility, e.g., the management of entities or the conversion of data types.
This avoids any unnecessary, technical coupling between responsibilities and
reduces the probability that you need to change your class. It also lowers the
complexity of each change because it reduces the number of dependent classes that
are affected by it.
1.8.2. Open/Closed Principle
Objects or entities should be open for extension, but closed for
modification.Software entities (classes, modules, functions, etc.) be extendable
without actually changing the contents of the class you’re extending. If we could
follow this principle strongly enough, it is possible to then modify the behavior
of our code without ever touching a piece of original code.
1.8.3. LisKov Substitution Principle
Let q(x) be a property provable about objects of x of type T. Then q(y) should be
provable for objects y of type S where S is a subtype of T.
It states that any implementation of an abstraction (interface) should be
substitutable in any place that the abstraction is accepted. Basically, it takes
care that while coding using interfaces in our code, we not only have a contract of
input that the interface receives but also the output returned by different Classes
implementing that interface; they should be of the same type.
1.8.4. Interface Segregation Principle
A client should never be forced to implement an interface that it doesn't use or
clients shouldn't be forced to depend on methods they do not use.
This rule means that we should break our interfaces in many smaller ones, so they
better satisfy the exact needs of our clients.
1.8.5. Dependency Inversion
Entities must depend on abstractions not on concretions. It states that the high
level module must not depend on the low level module, but they should depend on
abstractions.
By applying the Dependency Inversion the modules can be easily changed by other
modules just changing the dependency module and High-level module will not be
affected by any changes to the Low-level module.
1.9. Annotations
1.9.1. Annotations practices
According to the Android code style guide, the standard practices for some of the
predefined annotations in Java are:
@Override: The @Override annotation must be used whenever a method overrides the
declaration or implementation from a super-class. For example, if you use the
@inheritdocs Javadoc tag, and derive from a class (not an interface), you must also
annotate that the method @Overrides the parent class's method.
1.9.2. Annotations style
Classes, Methods, Constructors, When annotations are applied to a class, method, or
constructor, they are listed after the documentation block and should appear as one
annotation per line.
1.10. Logging guidelines
Use the logging methods provided by the Log class to print out error messages or
other information that may be useful for developers to identify issues:
Log.v(String tag, String msg) (verbose)
Log.d(String tag, String msg) (debug)
Log.i(String tag, String msg) (information)
Log.w(String tag, String msg) (warning)
Log.e(String tag, String msg) (error)
As a general rule, we use the class name as tag and we define it as a static final
field at the top of the file. For example:
public class MyClass {
private static final String TAG = MyClass.class.getSimpleName();

public myMethod() {
Log.e(TAG, "My error message")}}}
1.11. Line length limit
Code lines should not exceed 100 characters. If the line is longer than this limit
there are usually two options to reduce its length:
Extract a local variable or method (preferable).
Apply line-wrapping to divide a single line into multiple ones.
1.11.1. Line-wrapping strategies
There isn't an exact formula that explains how to line-wrap and quite often
different solutions are valid. However, there are a few rules that can be applied
to common cases. Break at operators when the line is broken at an operator, the
break comes before the operator. For example:
int longName = anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne
+ theFinalOne;
1.11.2. Assignment Operator Exception
An exception to the break at operators rule is the assignment operator =, where the
line break should happen after the operator.
int longName =
anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne +
theFinalOne;
1.11.3. Method chain case
When multiple methods are chained in the same line - for example when using
Builders - every call to a method should go in its own line, breaking the line
before the.
Picasso.with(context).load("http://ribot.co.uk/images/
sexyjoe.jpg").into(imageView);
Picasso.with(context)
.load("http://ribot.co.uk/images/sexyjoe.jpg")
.into(imageView);

1.11.4. Long parameters case


When a method has many parameters or its parameters are very long, we should break
the line after every comma ,
loadPicture(context, "http://ribot.co.uk/images/sexyjoe.jpg",
mImageViewProfilePicture, clickListener, "Title of the picture");
loadPicture(context,
"http://ribot.co.uk/images/sexyjoe.jpg",
mImageViewProfilePicture,
clickListener,
"Title of the picture");
1.12. Code Refactoring
Rewriting code for clarity, not bug fixing. Similar to writing paper drafts.
Rewrites may include:
○ Documentation / Comments
○ Change in Flow
○ Variable Naming Conventions
○ Creation of Functions / Classes
Simplification
Eliminating Duplicate Code
Re-usable

You might also like