Questions tagged [generics]
Meta technique, that allows to pospone the setting of the dependable type to the runtime.
156 questions
1
vote
4
answers
210
views
Ensuring type safety, honoring supertype contract
Due to type erasure, I can't do instanceof T in Java. With that in mind, how do (should) I write, for example, a generic TreeNode (or, more precisely, DefaultMutableTreeNode)? setUserObject() accepts ...
6
votes
3
answers
1k
views
What is the relationship between variance, generic interfaces, and input/output?
There is a blog post by Eric Lippert where he describes how to define variance. In a general sense, covariance is achieved when the direction of assignment compatibility is preserved. Contravariance ...
0
votes
1
answer
357
views
Changing the generic type when chaining operations
I have a class where I want to chain certain operations. The class look something like this
class MyClass<T> {
create<X>(fn: (_: T) => X): MyClass<X> {
...
...
-2
votes
3
answers
856
views
Are interfaces made useless by the template pattern?
Refer to the highest upvoted answer here for why you should make an IPizza interface with a IPizza.Prepare() method.
This is highly upvoted, But I think the answer is flawed. Sure a pizza can be ...
1
vote
1
answer
689
views
Circular references with generic classes
I'm trying to create an interaction system for a game I'm developing with Unity and C# and I've been struggling with it for a while now. It consists of interactors and interactables. The idea is that ...
3
votes
2
answers
1k
views
Is inheritance constraint on Generics redundant? If not what is its recommended use?
I've recently found myself using a generics with constraint that a type should inherit from a specific base class, but now I've just realised that this is redundant and unnecessary because the ...
0
votes
1
answer
138
views
Interface design for container that holds different instances derived from a common type
I'm currently designing an interface for a container that is supposed to store references of different instances that derived from a common supertype. An analogy of it would be as following:
Suppose ...
1
vote
1
answer
486
views
C# how to implement a factory class which doesn't require an argument passed to indicate objects type?
I currently working on a parser project in C# and have run into problem.
I have an entity folder within my project and within it I have:
Entity
IEntity.cs (defines a contract for entity classes)
...
0
votes
1
answer
5k
views
C# is it acceptable to create a generic class and use an enum as generic type?
Abstract
The case:
Application contains a lot of views with a list of data. Data views (lists of records) have pagination, filtering and sorting options.
The user must be able to select a "...
4
votes
2
answers
9k
views
Alternative To Generic Methods where Type is known at runtime
I've written a class that synchronizes a table between two databases using Dapper. The public and private Methods in the class are generic and the generic parameter is the POCO class that is being ...
0
votes
0
answers
102
views
c# class structuring and appropriate coding techniques
I have 2 classes that share some properties
public class SportsUser
{
public string errorCode { get; set; }
//the sportsuser and SportsAdminUser is from a different database hence the long and ...
6
votes
2
answers
1k
views
Is there a name for this construct with generics?
I wrote this valid piece code, which made me wonder if there was a name for it:
public class GenericObject<T> {
public T Obj { get; set; }
}
public class DerivedClass: GenericObject<...
18
votes
7
answers
8k
views
Should one prefer a generic version of a function, even if it's not re-used (yet)?
YAGNI might tell us, that in the below implementation the generic version is not needed, as long as the function is only used once.
But to me personally, it seems, the generic version is more readable ...
1
vote
1
answer
125
views
How do covariant parameterized types nested inside invariant parameterized types act?
Here is a concrete example of what I'm asking about:
MutableList[ImmutableList[Object]]
Where ImmutableList is covariant wrt its first parameter, but MutableList is invariant wrt its first parameter. ...
1
vote
0
answers
456
views
Simple Message Handler in Java with generics
I can easily put together a message handling set of generic apis in C# with the following quick and dirty code:
void Main()
{
var messageClient = new MessageClient(new TestMessageHandler(), new ...
0
votes
1
answer
218
views
How should I provide generic typing and allocation for a collection library in C?
I am in the process of implementing a persistent collection in C, specifically, an immutable hash trie. In order to increase acceptance and reusability, I have identified the following key areas that ...
-1
votes
1
answer
123
views
Is there a name for this pattern of composing a type safe return type from different levels of nested related entities?
I have a problem in my app where I have many entities that can all reference each other in different ways. For example, I have a Job (e.g. build house) that I might assign to a team called "Plumbers" ...
1
vote
0
answers
154
views
How to design the interface method for the following case?
I am making an SNMP agent. In order to pass information to this SNMP agent, I need to periodically extract data from two different sources (and there may be more sources in future.) I am trying to ...
1
vote
1
answer
372
views
Is designing a generic parameterized class with methods of it accepting higher order functions a functional technique that we can use in Java 8?
Recently I have asked this question: How do you rewrite the code which using generics and functionals in Java 8 and mixing oop and functional programming by using only object-oriented? on ...
-2
votes
1
answer
278
views
Design a generic hardware interface
I am trying design a generic hardware facade interface for different camera types.
below is my incomplete generic interface for camera devices
template <class Data,class Configuration>
class ...
1
vote
2
answers
215
views
Need good design: Anemic Model, Inheritance and Pattern Matching
I have Handler classes which accepts Queries and returns Results. Handlers is anemic. They accept input data bag and returns output data bag. Handlers can be many so I created common generic interface ...
1
vote
0
answers
145
views
Practice for modeling class - multiple container relationship
I have a class that could:
Have multiple types of containers
Have multiple types of implementations
and what I did to model so far is:
public interface ChildClass {
Container getContainer();
...
2
votes
3
answers
3k
views
Is there any advantage using generic type which implements interface over direct interface usage?
When I was looking this question, a question comes my mind.
Think about using an interface like :
public interface ICommandProcessor<T> where T : ICommand
{
void Process(T command);
}
When ...
1
vote
2
answers
535
views
Should I do a runtime type check inside generic constructors?
Given this generic class and constructor,
class A<E extends Number> {
A(E number, Comparable<E> comparable) {
//...
}
}
it is ensured that a call to the generic ...
0
votes
1
answer
69
views
When to use type contraints for sortable collections
I am implementing a Binary Search Tree and cannot decide if it would be good practice to constrain the generic type of the tree to a comparable item, i.e. IComparable<T>. Or, to just use the ...
0
votes
1
answer
2k
views
Do I need to unit test a generic method with all accepted types?
For a method whose signature looks like this:
public T Add<T>(T first, T second) where T : struct, IEquatable<T>, IComparable<T>
which can work with all of the integral types, do I ...
0
votes
0
answers
2k
views
Inherit a class that inherits a generic class to make it easier to read
I'm creating a simple Dependency Injection library for Unity (no constructors available) and I want to use a generic class that implements a generic call for each class that would inherit it allowing ...
1
vote
1
answer
245
views
Why doesn't Comparable<T> include any type bound? [closed]
Why do you think the definition of Comparable<T> lacks an upper bound on T?
That is, why is it not defined as:
Comparable<T extends Comparable<?>>
or
Comparable<T extends ...
5
votes
4
answers
19k
views
Is it possible to infer the the generic type from a generic method?
I'm making an HTTP API client class.
I want a Perform() method which takes a request object and returns an obejct that is expected from the API.
So a PostRequest object will describe how to get a ...
0
votes
2
answers
266
views
How best to avoid member implementation of class' Abstract/Interface instance variables
I'm sorry if the phrasing of the question is a bit unclear but let me try to clarify below. (If anyone can word it better, feel free to edit)
I have a Map instance variable, groups, which is defined ...
0
votes
1
answer
233
views
What design pattern would help me make my factory more generic
In my code I have 2 separate login types. I have a factory that decides which one to create based on an enum.
Each login type has a different type of credential.
Currently my factory method takes ...
-2
votes
1
answer
239
views
generate code or write generic code [closed]
I am writing drivers for different devices to work with my embedded system. Currently I write any new driver manually but for the future I would like to automate this using a settings file. I figure I ...
0
votes
1
answer
151
views
How to define a structure to store some generic "Variable" classes for easy access later
I'm running into a design problem. My code is in C# but the concepts could apply to any OO language.
I'm designing a framework to run experiments, and these experiments have several variables which ...
3
votes
1
answer
6k
views
Using generics on interfaces when implementation is not generic
Is it acceptable practice to put generics on an interface when the implementation will not be generic? Lets say that my project will have many classes that read data from the database. I may make a ...
0
votes
1
answer
518
views
Downcastings refactored using generics
I am willing to refactor some code that acts like a controller class executing work embedded in other classes. On one side it looks good as the controller is generic and what changes has been well ...
0
votes
1
answer
220
views
Is there a design for C# that removes the need for dynamic?
I have a web service that implements Repository Pattern and I was wondering if there is a design in C# that can remove the need for 'dynamic' when injecting it in my method.
public interface ...
0
votes
1
answer
2k
views
Should I avoid nested generic collections?
I recently came across a dictionary with lists for values passed as an argument:
Demo(Dictionary<string, List<string>> arg)
It got me thinking---normally I would abstract any list or ...
0
votes
2
answers
274
views
Pattern name for a class inheriting of a generic based on itself
I'm wondering if there is a name for the pattern of defining a generic class with one type argument where the type inherits the defining class.
For example
public class A<T> where T : A<T&...
1
vote
3
answers
548
views
Is there a programming language with objects and generics, but without inheritance?
The GO programming language has objects but no inheritance. It also has generics for the built-in types Array and Map. Is there a programming language with objects but no inheritance and with generics ...
9
votes
2
answers
684
views
Name of technique for inferring type arguments of a type parameter?
Setup: Let's assume we have a type called Iterator which has a type parameter Element:
interface Iterator<Element> {}
Then we have an interface Iterable which has one method which will return ...
-1
votes
2
answers
4k
views
C#, Static classes and Inheritance
As a beginner I'll try to explain my problem as good as I can:
I'm currently trying to program a "simple" ECS. My basic idea is that I have a base "Entity class" which includes all sorts of functions ...
1
vote
1
answer
197
views
Is this still considered an implementation of the strategy pattern?
In my project I have different types of entities.
I get the data for these entities in text files from a 3rd party.
I've written a class to read and parse these text files, using the strategy pattern.
...
37
votes
4
answers
12k
views
What is generics abuse?
While reviewing some code, I noticed the opportunity to change it to use generics. The (obfuscated) code looks like:
public void DoAllTheThings(Type typeOfTarget, object[] possibleTargets)
{
var ...
3
votes
1
answer
621
views
Why doesn't Swift's Numeric protocol inherit from the Comparable protocol?
I created a generic class MyClass<T: Numeric> {...} and got errors in my functions that tried to use > and <, along the lines of "Binary operator '>' cannot be applied to two 'T' operands."...
4
votes
1
answer
5k
views
Designing generic type inheritance hierarchy
I have now put another rephrased version of original question as requested by the user in the comments with class names mimicking real world scenario of postal office (though I dont know how real ...
3
votes
2
answers
1k
views
What is the benefit of using an interface that doesn't enforce anything (marker interface)?
The codebase I'm working on makes a lot of use of interfaces that don't actually enforce anything. They're in place more to make sure that a type 'is a' something. For example:
public class ...
0
votes
2
answers
2k
views
How to create a generic client to query an API and return different types based on API call?
I am building a repository that will request data from an API.
Originally, I had multiple methods in my repository such as GetOrders(), GetOrderItems() etc.
The majority of these functions had almost ...
1
vote
2
answers
179
views
Scan Relationships of Entity Framework Entity Generically
I have an application with a database that doesn't allow cascading deletes. When a user goes to delete an entity, I would like to display a popup saying something generic like, "This record has ...
1
vote
2
answers
431
views
How to combine these fill and create methods or utilize generics in factory?
Domain object "Contragent"
Let's say I have an hierarchy of classes:
public class BaseContragent
{
public int Id { get; set; }
}
public class PersonContragent : BaseContragent
{
public string ...
14
votes
2
answers
6k
views
Why use a generic method with a type constraint instead of the type itself?
In a different StackExchange question, I noticed someone using this prototype:
void DoSomething<T>(T arg) where T: SomeSpecificReferenceType
{
//Code....
}
Bearing in mind there is only a ...