interfaces en c#

53
C# Interfaces Germán Küber .Net Developer Microsoft Student Partner (MSP) @germankuber https://aka.ms/NetBaires http://germankuber.com.ar

Upload: mariano-german-villarreal-kueber

Post on 13-Apr-2017

64 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Interfaces en C#

C# InterfacesGermán Küber.Net DeveloperMicrosoft Student Partner (MSP)

@germankuberhttps://aka.ms/NetBaireshttp://germankuber.com.ar

Page 2: Interfaces en C#

¿ Por que Interfaces ?

Mantenibilidad Extensibilidad

Fácil de Testear

Page 3: Interfaces en C#

¿ Que es una interfaces ?Describen un grupo de funciones relacionadas que pueden pertenecer a cualquier clase o estructura.

Contrato Miembros públicos : Propiedades Métodos Eventos Índices

Page 4: Interfaces en C#

Escenario : Polígonos regularesLargo = 5

Largo = 5

Largo = 5Larg

o = 5

Largo = 5

Largo = 5

Largo

= 5

• 3 o mas lados• Todos los lados

iguales

Page 5: Interfaces en C#

PerímetroLargo = 5

Largo = 5

Largo = 5Larg

o = 5

Largo = 5

Largo = 5

Largo

= 5

Perímetro = Nº lados x largo de cada ladoPerimeter = 4 x 5

Perimeter = 20Perimeter = 3 x 5

Perimeter = 15

Page 6: Interfaces en C#

ÁreaLargo = 5

Largo = 5

Largo = 5Larg

o = 5

Largo = 5

Largo = 5

Largo

= 5

Área = L. Largo x L. Largo

Perimeter = 5 x 5Perimeter = 25

Área = (L. Largo x L. Largo)/ x Sqrt(3) / 4

Area = 5 x 5 x Sqrt(3) / 4 Area = 10.8 (apróximadamente)

Page 7: Interfaces en C#

Clases concretas?Clases abstractas?

Interfaces?

Page 8: Interfaces en C#

Clase abstracta : Puede tener implementaciones

Interfaces: No poseen implementaciones

Comparación: Implementación

Page 9: Interfaces en C#

Comparación: Herencia Clase Abstracta : Herencia simple

Interface: Herencia múltiple

Page 10: Interfaces en C#

Clase Abstracta : Puede tener modificadores de acceso

Interface: Automáticamente todos sus miembros son públicos

Comparación: Modificadores de Acceso

Contrato

Page 11: Interfaces en C#

CamposPropiedadesContructoresDestructores

MétodosEventosIndices

PropiedadesMétodosEventosIndices

Comparación: Miembros válidos

Clases Abstractas

Interfaces

Page 12: Interfaces en C#

Comparación

Clases Abstractas Interfaces

• Puede contener implementaciones

• Herencia simple

• No puede contener implementaciones• Herencia multiple

Page 13: Interfaces en C#

Mantenibilidad

Page 14: Interfaces en C#

Buenas prácticas

Programar orientado a abstracciones y no a tipos concretos

Page 15: Interfaces en C#

Interfaces

Programar orientado a interfaces y no a clases concretas

Page 16: Interfaces en C#

List<T> Array

ArrayListSortedList<TKey, TValue>

HashTableQueue / Queue<T> Stack / Stack<T>

Dictionary<TKey, TValue> ObservableCollection<T>

+Custom Types

Clases concretasColecciones

Page 17: Interfaces en C#

Interfaces

Interfaces de Colecciones

Page 18: Interfaces en C#

Extensibilidad

Page 19: Interfaces en C#

Diferentes Data Sources Relational Databases

Microsoft SQL Server, Oracle, MySQL, etc. Document / Object Databases (NoSQL)

MongoDB, Hadoop, RavenDB, etc. Text Files

CSV, XML, JSON, etc. SOAP Services

WCF, ASMX Web Service, Apache CXF, etc. REST Services

WebAPI, WCF, Apache CXF, JAX-RS, etc. Cloud Storage

Microsoft Azure, Amazon AWS, Google Cloud SQL

Page 20: Interfaces en C#

Patrón RepositorioCapa de abstracción para comunicar nuestra aplicación con el almacén de datos

Aplicación

Repositorio

Data Storage

Page 21: Interfaces en C#

WCF Service Repository

CSV File Repository

SQL Database Repository

Aplicación

Repositorios Intercambiables

Page 22: Interfaces en C#

Repositorio SimpleOperaciones

• C => Create• R => Read• U => Update• D => Delete

Page 23: Interfaces en C#

Interface Repository

Page 24: Interfaces en C#

Clase sin Interface

public class Catalog{public string Save(){return "Catalog Save";

}

// Other members not shown}

Catalog catalog = new Catalog();catalog.Save(); // "Catalog Save"

Declaración

Uso

Page 25: Interfaces en C#

Implementación estándar de Interface

Catalog catalog = new Catalog(); catalog.Save(); // "Catalog Save"

ISaveable saveable = new Catalog(); saveable.Save(); // "Catalog Save"

Declaración

Usopublic interface ISaveable{string Save();

}

public class Catalog : ISaveable{public string Save(){return "Catalog Save";

}

// Other members not shown}

Page 26: Interfaces en C#

Implementación Explicita

Declaración Tipo Concreto

Variable interface

Castear a Interface

Page 27: Interfaces en C#

Declaración Implementación

Implementación Explicita

Page 28: Interfaces en C#

Fácil de Testear

Page 29: Interfaces en C#

Interfaces

Programar orientado a interfaces y no a clases concretas

Page 30: Interfaces en C#

Programa orientado a interfaces

No referenciar clases concretas

Page 31: Interfaces en C#

Compile-Time Factory

Page 32: Interfaces en C#

Dynamic Loading Se obtiene el tipo y el Assembly de la

configuración Carga Assembly por Reflection Creo una Instancia de Repository con Activator

Page 33: Interfaces en C#

Comparación Factory

Compile-Time Factory Dynamic Factory

• Tiene un parámetro• Quien llama decide que

repositorio quiere• Compile-Time Binding• La Factory necesita referencia al

conjunto de repositorios

• No tiene parámetro• La Factory retorna un repositorio

basándose en la configuración• Run-Time Binding• La Factory no tiene referencia real

a los repositorios

Page 34: Interfaces en C#

Unit Testing• Testear pequeñas porciones de código• Eliminar dependencias reales con

DataSources• Realizar pruebas de integración

Page 35: Interfaces en C#

¿ Que queremos Testear ?

Page 36: Interfaces en C#

Dependencias

Page 37: Interfaces en C#

Implementar ViewModel

View (UI Elements)

View Model

Repository

Data Storage

Page 38: Interfaces en C#

Buenas Prácticas

Page 39: Interfaces en C#

Interface Segregation Principle

• Tener interfaces granulares.• No obligar a los clientes a depender

de métodos que no utilicen

Page 40: Interfaces en C#

List<T> Interfaces

IEnumerable

IEnumerable<T>GetEnumerator

()GetEnumerator

()

Page 41: Interfaces en C#

List<T> Interfaces

ICollection<T>Count

IsReadOnly

Add() Clear()

Contains() CopyTo() Remove()

Page 42: Interfaces en C#

List<T> Interfaces

IList<T>Item /

Indexer IndexOf() Insert()

RemoveAt()

Page 43: Interfaces en C#

Interfaces Granulares Si necesito :

Iterar una Collection / Sequence

Data Bind a List Control Usar LINQ functions

Si necesito : Agregar/Eliminar Items de una

Collection Contar Items en una Collection Limpiar la Collection

Si necesito : Control sobre el orden de los

Items en una Collection Obtener ítem por índice

IEnumerable<T>

IList<T>

ICollection<T>

Page 44: Interfaces en C#

IPersonRepository

Page 45: Interfaces en C#

Segregation

Page 46: Interfaces en C#

¿Cuando Clases Abstractas y cuando

Interfaces?

Page 47: Interfaces en C#

Regular PolygonClase Abstracta

Page 48: Interfaces en C#

Person RepositoryInterface

s• Service Repository

• File Repository

• SQL Repository

Page 49: Interfaces en C#

Dependency Injection Código poco acoplado

Delegación de responsabilidad de obtener instancias

Patrones de diseño Constructor Injection Property Injection Method Injection Service Locator

Dependency Injection Containers Unity, StructureMap, Autofac, Ninject, Castle Windsor, and

many others

Page 50: Interfaces en C#

Dependency Injection

Page 51: Interfaces en C#

Mocking Crear objetos controlados

En memoria Solo implemento el

comportamiento que quiero

Ideal para pruebas unitarias

Mocking Frameworks RhinoMocks Microsoft Fakes Moq

Page 52: Interfaces en C#

¿ Por que Interfaces ?

Page 53: Interfaces en C#

¿ Preguntas ?