Skip to content
EntityQ1051282· pop 34· linked from 513 articles

programação genérica

Sign in to save

way of designing and writing programs where algorithms are written in terms of parametric types enabling easy reuse

Described at

An Overview of Generic Programming: Writing Code with Arbitrary Types | English

Generic programming has been around for quite some time. This blog post provides a brief overview of the basics of generic programming and its implications …

codepros.org

What Does Generic Programming Look Like?, Benefits of Generic Programming and Generic Program… Generic Programming is a specialized form of programming in some languages (primarily statically typed languages) where code is written to process objects of any arbitrary type. The distinction between generic programming and normal programming is when writing generic code the “type” (often denoted T ) of the data is not explicitly stated. The generic programming paradigm is challenging to master because it requires a high level of abstraction (ignoring the type of data in its entirety). Languages, like C++ (templates), Java, C , and soon Golang, have built-in support for generic programming and include a large standard library of generic collections and data structures. In the above examples, the logic is the same and is type agnostic. These examples both define generics, which manage an internal array of elements (non-type specific), and have cooresponding add methods for new array elements. The genericization of these list objects allows for both implementations to work within their ecosystem and reduce duplicated code for a List of any type of data. With Generic types (often denoted as T but not always), no assumptions can be made about the instance type being processed. Since no assumptions of type can be made in generic code it becomes possible for the same logic to work for many types in a consistent and repeatable way. The type agnostic nature makes generics a powerful language feature, but it also makes generic code difficult to read or to understand for unaccustomed engineers. Strictly speaking, some languages like C and Java have a base Object class ALL classes inherit from. In those situations, you can make assumptions about the type as long as you treat it as the base Object. Generic programming requires a different mindset from object oriented programming because the type of the data is not explicitly stated. Instead, the focus is on how an “unknown” type is able to be manipulated without the need to know the type. A great use case, and the most common use case for generics, is data structures. While in most languages interfaces are defined and implemented by classes explicitly this is not always the case. For example, both Go and TypeScript use implicit interfaces, not pre-declared directly on a type, and are later inferred through a type contract negotiation process. Implicit interface typing is a powerful tool. Interfaces define a contract a type must adhere to. The interface contract can then be used as the type in code, rather than the original type. This contract allows for many different types to be used, essentially genericizing the code substantially.3 If using an interface type is possible for your purposes, then it is generally the recommended method for generic programming. There are several reasons for this best practice: 1) Interfaces allow for code to use specific knowledge about a type (i.e. parameters or methods), and 2) The interface contract is type checked by the compiler at compile time. Reflection libraries are used to inspect the type of a variable or object and perform operations on it. Generally, reflection is able to access the metadata of any object and access properties, execute methods, and manipulate values. Reflection is, however, a double edged sword. So, why not use reflection instead of supporting generics in the language? Reflection libraries are just that – libraries. They are limited to accessing and manipulating metadata about a type. Reflection libraries suffer from serious performance implications and are NOT statically type checked by the compiler. Due to the lack of complier support, using reflection can lead to difficult bugs, performance issues, and a large amount of code where there is no type safety. It is also easy to misuse reflection. Reflection does not benefit from IDE support (because it only functions at runtime) or complier support. The lack of immediate

Excerpt from a page describing this subject · 18,976 chars · not written by Vinony

Wikidata facts

Show 4 more facts
Sources (3)

via Wikidata · CC0

Article · Português

Programação genérica é um paradigma de programação no qual os algoritmos são escritos em uma gramática estendida de forma a adaptar-se através da especificação das partes variáveis que são definidas na instância do algoritmo. Especificamente, a gramática estendida eleva um elemento não variável ou uma construção implícita na gramática base para uma variável ou constante, permitindo a utilização do código genérico. É diferente da forma normal de programação na medida em que invoca de certa forma as facilidades de metaprogramação da linguagem. Como isso ocorre em uma extensão da linguagem, novas semânticas são introduzidas e a linguagem é enriquecida no processo. É relacionada com a metaprogramação, mas não envolve a geração de código fonte, pelo menos visivelmente ao programador. É diferente também da programação por macros, já que esta refere-se somente a busca e substituição de termos, não fazendo parte da gramática da linguagem, implementada somente na fase de pré-processamento do código. Para efeitos práticos, o paradigma permite que um parâmetro assuma diferentes tipos de dados desde que certas regras sejam mantidas, como sub-tipos e assinaturas. Por exemplo, para criar uma lista usando programação genérica, uma possível declaração seria List<t></t>, no qual T é o tipo de dado. Para instanciar, poderia-se usar List<inteiro></inteiro> ou List<animal></animal>, já que o conceito de lista independe do tipo utilizado. Entre linguagens orientadas a objeto, C++, Linguagem D, , Eiffel e versões de Java (1.5 e acima) fornecem o paradigma genérico. Visual Basic .NET, C# e Delphi.Net começaram a fornecer o paradigma a partir do .NET 2.0. Muito antes de todas as linguagens mencionadas, programação genérica já havia sido implementada na década de 1970 em linguagens como CLU e Ada. Mas somente o conceito de templates do C++ que popularizou o conceito. A técnica permite que algoritmos sejam escritos independente dos tipos de dados utilizados. Os autores do conceituado livro de 1995 Design Patterns referem-se à programação genérica como tipos parametrizados, o que permite que um tipo possa ser definido sem especificar todos os outros tipos que ele utilizada. Os autores ainda descrevem que tal técnica é muito poderosa, especialmente quando combinada com o padrão Delegar.

Abstract from DBpedia / Wikipedia · CC BY-SA