Object Design Style Guide
eBook - ePub

Object Design Style Guide

Matthias Noback

Condividi libro
  1. English
  2. ePUB (disponibile sull'app)
  3. Disponibile su iOS e Android
eBook - ePub

Object Design Style Guide

Matthias Noback

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

Objects are the central concept of languages like Java, Python, C#. Applying best practices for object design means that your code will be easy to read, write, and maintain. Object Design Style Guide captures dozens of techniques for creating pro-quality OO code that can stand the test of time. Examples are in an instantly familiar pseudocode, teaching techniques you can apply to any OO language, from C++ to PHP.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Object Design Style Guide è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Object Design Style Guide di Matthias Noback in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Object Oriented Programming. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2019
ISBN
9781617296857

Chapter 1. Programming with objects: A primer

This chapter covers
  • Working with objects
  • Unit testing
  • Dynamic arrays
Before we get into the actual style guide, this chapter covers some of the fundamental aspects of programming with objects. We’ll briefly go over some important concepts and establish a shared terminology that we can build on in the following chapters.
We’ll be covering the following topics in this chapter:
  • Classes and objects— Creating objects based on classes, using a constructor, static versus object methods, static factory methods for creating new instances, and throwing exceptions inside a constructor (section 1.1).
  • State— Defining private and public properties, assigning values to them, constants, and mutable versus immutable state (section 1.2).
  • Behavior— Private and public methods, passing values as arguments, and NullPointerExceptions (section 1.3).
  • Dependencies— Instantiating them, locating them, and injecting them as constructor arguments (section 1.4).
  • Inheritance— Interfaces, abstract classes, overriding implementations, and final classes (section 1.5).
  • Polymorphism— Same interface, different behavior (section 1.6).
  • Composition— Assigning objects to properties and building more advanced objects (section 1.7).
  • Return statements and exceptions— Returning a value from a method, throwing an exception inside a method, catching exceptions, and defining custom exception classes (section 1.9).
  • Unit testing— Arrange-Act-Assert, testing for failures, and using test doubles to replace dependencies (section 1.10).
  • Dynamic arrays— Using them to create lists or maps (section 1.11).
If you are somewhat familiar with all of these topics, feel free to skip this chapter and jump to chapter 2. If some topics are unknown to you, take a look at the corresponding sections. If you are just beginning as an object-oriented programmer, I recommend reading this whole chapter.

1.1. Classes and objects

The runtime behavior of an object is defined by its class definition. Using a given class, you can create any number of objects. The following listing shows a simple class, with no state or behavior, which can be instantiated.
Listing 1.1. A minimum viable class
class Foo { // There's nothing here } object1 = new Foo(); object2 = new Foo(); object1 == object2 // false 1
  • 1 Two instances of the same class should not be considered the same.
Once you have an instance, you can call methods on it.
Listing 1.2. Calling a method on an instance
class Foo { public function someMethod(): void { // Do something } } object1 = new Foo(); object1.someMethod();
A regular method, like someMethod(), can only be called on an instance of the class. Such a method is called an object method. You can also define methods that can be called without an instance. These are called static methods.
Listing 1.3. Defining a static method
class Foo { public function anObjectMethod(): void { // ... } public static function aStaticMethod(): void { // ... } } object1 = new Foo(); object1.anObjectMethod(); 1 Foo.aStaticMethod(); 2
  • 1 anObjectMethod() can only be called on an instance of SomeClass.
  • 2 aStaticMethod() can be called without an instance.
Besides object and static methods, a class can also contain a special method: the constructor. This method will be called before a reference to the object gets returned. If you need to do anything to prepare the object before it’s going to be used, you can do it inside the constructor.
Listing 1.4. Defining a constructor method
class Foo { public function __construct() { // Prepare the object } } object1 = new Foo(); 1
  • 1 __construct() will be implicitly called before a Foo instance gets assigned to objectl.
You can prevent an object from being fully instantiated by throwing an exception inside the constructor, as shown in the following listing. You can read more about exceptions in section 1.9.
Listing 1.5. Throwing an exception inside the constructor
class Foo { public function __construct() { throw new RuntimeException(); 1 } } try { objectl = new Foo(); } catch (RuntimeException exception) { // `object1` will be undefined here }
  • 1 It won’t be possible to instantiate Foo because its constructor always throws an exception.
The standard way to instantiate a class is using the new operator, as we just saw. It’s also possible to define a static factory method on the class itself, which returns a new instance of the class.
Listing 1.6. Defining a static factory method
class Foo { public static function create(): Foo { return new Foo(); } } object1 = Foo.create(); object2 = Foo.create();
The create() method has to be defined as static because it should be called on the class, not on an instance of that class.

1.2. State

An object can contain data. This data will be stored in properties. A property will have a name and a type, and it can be populated at any moment after instantiation. A common place for assigning values to properties is inside the constructor.
Listing 1.7. Defining properties and assigning values
class Foo { private int someNumber; private string someString; public function __construct() { this.someNumber = 10; this.someString = 'Hello, world!'; } } object1 = new Foo(); 1
  • 1 After instantiation, someNumber and someString will contain 10 and ‘Hello, world!’ respectively.
The data contained in an object is also known as its state. If that data is going to be hardcoded, as in the previous example, you might as well make it part of the property definition or define a constant for it.
Listing 1.8. Defining constants
class Foo { private const int someNumber = 10; 1 private someString = 'Hello, world!'; }
  • 1 Your programming language may have a different syntax. For example, in Java you would use “final private int someNumber.”
On the other hand, if the initial value of a property should be variable, you can let the client provide a value for it as a constructor argument. By adding a parameter to the constructor, you force clients to provide a value when instantiating the class.
Listing 1.9. Adding a constructor argument
class Foo { private int someNumber; public function __construct(int initialNumber) { this.someNumber = initialNumber; } } object1 = new Foo(); // doesn't work 1 objec...

Indice dei contenuti