Object Design Style Guide
eBook - ePub

Object Design Style Guide

Matthias Noback

Compartir libro
  1. English
  2. ePUB (apto para móviles)
  3. Disponible en iOS y Android
eBook - ePub

Object Design Style Guide

Matthias Noback

Detalles del libro
Vista previa del libro
Índice
Citas

Información del 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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Object Design Style Guide un PDF/ePUB en línea?
Sí, puedes acceder a Object Design Style Guide de Matthias Noback en formato PDF o ePUB, así como a otros libros populares de Computer Science y Object Oriented Programming. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
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...

Índice