This is Class 2 on a 6 week course I taught on Software Design Patterns.
This course discusses Strategy and Template pattern.
Class based on "Head First Design Patterns."
This presentation introduces some advanced concepts of generics in Java. These slides introduce the following concepts:
- Generic classes and methods
- Type variable bounds
- Type erasure process
- Generics and inheritance
- Wildcard types
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
This is Class 2 on a 6 week course I taught on Software Design Patterns.
This course discusses Strategy and Template pattern.
Class based on "Head First Design Patterns."
This presentation introduces some advanced concepts of generics in Java. These slides introduce the following concepts:
- Generic classes and methods
- Type variable bounds
- Type erasure process
- Generics and inheritance
- Wildcard types
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
Revamped for 2011 (90% new material), this session will guide any level of programmer to greater productivity by providing the information needed to write consistent, maintainable code. Learn about project setup, assembly layout, code style, defensive programming and much, much more. Code tips are included to help you write better, error free applications. Lots of code examples in C# and VB.NET. This session is based off my latest book, David McCarter's .NET Coding Standards.
This session will introduce developers to the new powerful new feature that is part of the .NET 4.5 framework called Code Contracts. Code Contracts brings the advantages of design-by-contract programming to .NET programming. Contracts are used to improve testing via runtime checking, enable static contract verification, and documentation generation.
Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.
Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow “a type or method to operate on objects of various types while providing compile-time type safety”
The Java collections framework supports generics to specify the type of objects stored in a collection instance.
Chapter 4:Object-Oriented Basic ConceptsIt Academy
Exam Objective 1.1 Describe, compare, and contrast primitives (integer, floating point,boolean, and character), enumeration types, and objects.
Exam Objective 3.1 Develop code that uses primitives, enumeration types, and object references, and recognize literals of these types.
Chapter 3 of An Apocalypse of Ice. In which Eowyn chooses her aspiration, Sansa chooses Eowyn's husband, and Addison wishes he was in this chapter more.
(for disclaimer, see chapter 1)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
Revamped for 2011 (90% new material), this session will guide any level of programmer to greater productivity by providing the information needed to write consistent, maintainable code. Learn about project setup, assembly layout, code style, defensive programming and much, much more. Code tips are included to help you write better, error free applications. Lots of code examples in C# and VB.NET. This session is based off my latest book, David McCarter's .NET Coding Standards.
This session will introduce developers to the new powerful new feature that is part of the .NET 4.5 framework called Code Contracts. Code Contracts brings the advantages of design-by-contract programming to .NET programming. Contracts are used to improve testing via runtime checking, enable static contract verification, and documentation generation.
Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.
Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow “a type or method to operate on objects of various types while providing compile-time type safety”
The Java collections framework supports generics to specify the type of objects stored in a collection instance.
Chapter 4:Object-Oriented Basic ConceptsIt Academy
Exam Objective 1.1 Describe, compare, and contrast primitives (integer, floating point,boolean, and character), enumeration types, and objects.
Exam Objective 3.1 Develop code that uses primitives, enumeration types, and object references, and recognize literals of these types.
Chapter 3 of An Apocalypse of Ice. In which Eowyn chooses her aspiration, Sansa chooses Eowyn's husband, and Addison wishes he was in this chapter more.
(for disclaimer, see chapter 1)
A brief overview about how to write human readable and meaningful code. Here is described why and how to write meaningful names of variables or method, what to follow about writing a function for SRP / Open-Closed principle rule, when to write comments and rules of Code Formatting. Advantages of clean code is also described here.
TDD is now mainstream but a lot people don't know or don't remember what is its purpose. TDD is about software design not testing or catching bug. TDD helps developers to shape and create software with "good" design, what is a "good" design is something that we will discuss in the topic.
A summary of clean code concepts and tips along with some examples and good practices.
These are the slides translated in English from my talk on Clean Code to my coworkers back then
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxDeepasCSE
Object-Oriented Programming (OOP) is a programming paradigm that focuses on organizing and modeling software as a collection of objects. In OOP, objects are instances of classes, which serve as blueprints or templates for defining the structure and behavior of those objects. OOP is built on several key principles and concepts, which include:
Objects: Objects are the basic building blocks of an OOP system. They represent real-world entities, and they encapsulate both data (attributes or properties) and behavior (methods or functions) that operate on that data.
Classes: Classes are the templates or blueprints from which objects are created. They define the attributes and methods that objects of the class will possess. Classes enable the concept of abstraction, allowing you to create objects with common characteristics and behaviors.
Encapsulation: Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on that data into a single unit, i.e., a class. This unit is called an object. Encapsulation restricts access to the internal state of an object, providing data hiding and promoting information hiding, which helps manage complexity and reduces potential issues.
Inheritance: Inheritance is a mechanism that allows a class (a child or derived class) to inherit the attributes and methods of another class (a parent or base class). This promotes code reusability and the creation of specialized classes.
Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables the use of a single interface to represent a general class of actions. Polymorphism can take the form of method overriding (a subclass provides a specific implementation of a method defined in its superclass) or method overloading (multiple methods with the same name but different parameters).
Abstraction: Abstraction is the process of simplifying complex reality by modeling classes based on the essential properties and behaviors. It hides the unnecessary details while providing a clear and well-defined interface for interacting with objects.
Object-Oriented Programming is widely used in various programming languages like C++, Java, C#, Python, and more. It promotes code organization, modularity, and the modeling of real-world entities in a way that makes it easier to design, develop, and maintain software systems. OOP is particularly suited for large and complex projects where code readability, reusability, and maintainability are critical.
3. Bjarne Stroustrup, inventor of C++
and author of The C++ Programming
Language
I like my code to be elegant and efficient. The logic should be
straightforward to make it hard for bugs to hide, the
dependencies minimal to ease maintenance, error handling
complete according to an articulated strategy, and per-
formance close to optimal so as not to tempt people to make
the code messy with unprinci-pled optimizations. Clean code
does one thing well.
4. “Big” Dave Thomas, founder
of OTI, godfather of the
Eclipse strategy
Clean code can be read, and enhanced by a developer other
than its original author. It has unit and acceptance tests. It has
meaningful names. It provides one way rather than many ways
for doing one thing. It has minimal depen dencies, which are
explicitly defined, and pro- vides a clear and minimal API. Code
should be literate since depending on the language, not all
necessary information can be expressed clearly in code alone.
5. Michael Feathers, author of Working
Effectively with Legacy Code
I could list all of the qualities that I notice in clean code, but
there is one overarching quality that leads to all of them.
Clean code always looks like it was written by someone who
cares. There is nothing obvious that you can do to make it
better. All of those things were thought about by the code’s
author, and if you try to imagine improvements, you’re led
back to where you are, sitting in appreciation of the code
someone left for you—code left by some one who cares
deeply about the craft.
6. My personal View
The code considered to be clean will need these:
Well written test (Unit test) for every public methods.
A class should be small and does one thing only
A method should be small enough( not longer then 20 lines)
A method should does only one thing and does it well
After all, I should able to hand over my code to other, and they should
able to carry on the work.
8. Meaningfull Names
Use Intention-Revealing Names:
Intention-
It should tell you why it exists, what it does, and how it is
used.
int d; // elapsed time in days
OR
int elapsedTimeInDays;
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays;
9. Avoid Disinformation
avoid words whose entrenched meanings vary from
our intended meaning.
Eg. grouping of accounts -> var accountList
10. Use Pronounceable Names
class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private final String pszqint = "102";
/* ... */
};
To
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;;
private final String recordId = "102";
/* ... */
};
11. Avoid Encodings
Hungarian Notation
PhoneNumber phoneString;
// name not changed when type changed!
Member Prefixes
public class Part {
private String m_dsc; // The textual
description
void setName(String name) {
m_dsc = name;
}
} To
public class Part {
String description;
void setDescription(String description) {
this.description = description;
}
}
12. Avoid Mental Mapping
Readers shouldn’t have to mentally translate your
names into other names they already know.
This problem generally arises from a choice to use
neither problem domain terms nor solution domain
terms.
var r; //url
var fn; //first name
15. Pick One Word per Concept
Pick one word for one abstract concept and stick with it
Eg.
Fetch(), retrieve(), get() as equivalent
methods of different classes.
controller and a manager and a driver in the same code base.
16. Don’t Pun
Avoid using the same word for two purposes
Eg.
add(firstItem, secondItem), concatinat two items.
add(newItem), append to existing item
17. Use Solution Domain Names
Do not afraid of using computer science team like:
Name of patters
Algorithm
• getMinWidthComposite()
•AccountVisitor
18. Add Meaningful Context
enclosing them in well-named classes, functions, or
namespaces
private void thereIsOneLetter() {
number = "1";
verb = "is";
pluralModifier = "";
}
19. Function
Small, should be hardly every 20 lines long
Does one thing, it should does one thing, does it well,
and does it only.
20. Function: One Level of Abstraction per
Function
gtk.Button.prototype.setImage = function(image){
this._widget2 = image;
this.resize(this._minWidth, this._minHeight);
this._widget2._domObj.style.display = "";
this._imageDom.appendChild(this._widget2._domObj);
};
To
gtk.Button.prototype.setImage = function(image){
this._widget2 = image;
this.resize(this._minWidth, this._minHeight);
this.hide(this._widget2);
this._appendImage(this._widget2._domObj);
};
gtk.Button.prototype.hideWidget = function(widget){
widget._domObj.style.display = "";
};
gtk.Button.prototype.appendImage = function(){
this._imageDom.appendChild(this._widget2._domObj);
};
21. Function Arguments
What is the best number of arugments passed in:
Zero (niladic)
Two (dyadic)
Three (polyadic)
More then this is evil
Reasons not to have many arguments:
For public methods, user fine it hard to use the method.
For private method, it should able to access the class
properties, why have to pass in.
22. Function Arguments
Flag Arguments: Passing a boolean into a function is a truly
terrible practice
render(true)
OR
renderForSuite() and renderForSingleTest()
23. Function Arguments
Argument Objects: more than two or three arguments, they
ought to be wrapped into a class of their own.
Circle makeCircle(double x, double y,
double radius);
OR
Circle(circleProperties);
24. Don’t repeat yourself
If you see the same code structure more than one
place, then extract the method and invoke the code
from both places
25. Switch Statement
How to make switch statement does one thing?
public Money calculatePay(Employee e)
throws InvalidEmployeeType {
switch (e.type) {
case COMMISSIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateHourlyPay(e);
case SALARIED:
return calculateSalariedPay(e);
default:
throw new InvalidEmployeeType(e.type);
}
}
26. Comment
Comments Do Not Make Up for Bad Code:
“Ooh, I’d better comment that!” No! You’d better
clean it!”
// Check to see if the employee is eligible for full
benefits
if ((employee.flags & HOURLY_FLAG) && (employee.age >
65))
OR
if (employee.isEligibleForFullBenefits())
28. Comment
Legal Comments
// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
// Released under terms of the GNU General Public License version 2 or later.
Informative Comments
// Returns an instance of the Responder being tested.
protected abstract Responder responderInstance();
OR
protected abstract Responder getResponderInstance();
29. Warning of Consequences
Warning of Consequences
// Don't run unless you
// have some time to kill.
public void _testWithReallyBigFile()
{
writeLinesToFile(10000000);
response.setBody(testFile);
response.readyToSend(this);
String responseString = output.toString();
assertSubString("Content-Length: 1000000000", responseString);
assertTrue(bytesSent > 1000000000);
}
30. TODO Comments
Leave TODO comment
//TODO-MdM these are not needed
// We expect this to go away when we do the checkout model
protected VersionInfo makeVersion() throws Exception
{
return null;
}
32. Redundant Comments
The comment that takes longer to read than the code
itself
// Utility method that returns when this.closed is true. Throws an exception
// if the timeout is reached.
public synchronized void waitForClose(final long timeoutMillis) throws Exception
{
if(!closed)
{
wait(timeoutMillis);
if(!closed)
throw new Exception("MockResponseSender could not be
closed");
}
}
33. Noise Comments
Sometimes you see comments that are nothing but noise.
They restate the obvious and provide no new information.
/**
* Returns the day of the month.
*
* @return the day of the month.
*/
public int getDayOfMonth() {
return dayOfMonth;
}
34. Don’t Use a Comment When You Can Use a
Function or a Variable
// does the module from the global list <mod> depend on the
// subsystem we are part of?
if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem()))
OR
ArrayList moduleDependees = smodule.getDependSubsystems();
String ourSubSystem = subSysMod.getSubSystem();
if (moduleDependees.contains(ourSubSystem))
35. Position Markers
Mark a particular position in a source file
// Actions //////////////////////////////////
36. Class Names
Classes and objects should have noun or noun phrase
names like Customer, WikiPage, Account, and
AddressParser.
37. Reference
Clean Code: a hand book of agile software
craftmanship by Robert C. Martin
Refactoring, Improving the design of existing
code by Martin Fowler