How to name a class that wraps several primitive types? - c#

I have a naming problem for some of my classes. I need to wrap some primitive .net types into a class like the following. There will be about 20 of such classes.
(The naming is crap, of course. Just for a demonstrative purpose)
public class Int32Single
{
public int Value { get; set; }
}
public class Int32Double
{
public int Value1 { get; set; }
public int Value2 { get; set; }
}
public class DoubleSingle
{
public double Value { get; set; }
}
I can't use a generic approach for this.
How should I name such wrapper classes, where each class name should provide the necessary information which primite types are wrapped and in which quantity?
It might also be possible that I have class that contains mixed primite types.

This doesn't seem like a very good idea at all. You have both the Tuple class and a standard array available, that both make more sense in any conceivable use case. However, that doesn't answer your question, so...
The most intuitive name for a wrapper class would follow the convention of {type-name}Wrapper, or for example, Int32Wrapper. In your case, the wrapped object is a primitive type, so makes sense to call the class a "Tuple". Since you want to specify the size of the Tuple in your class name, {primitive-type-name}{size}Tuple seems like the most intuitive naming convention but this causes several problems.
The natural language used to describe Tuples create ambiguity (such as Single and Double because they conflict with the Type names). (e.g. DoubleDouble is bad)
Integers are used in the naming of some primitive types so this could cause ambiguity. (e.g. Int322Tuple is bad).
We can't move the size to the beginning such as 2Int32Tuple because integers are not valid characters to begin a class name. So, There are two approaches that I think could work.
I think your best bet to get around these constraints, is to use a {primitive-type-name}{text-represented-size}Tuple convention. (e.g. Int32TwoTuple or DoubleTwoTuple). This convention expresses the contents of the wrapper class without ambiguity, so it seems like a good approach. In addition the name begins with the primitive type name, so, if you have a lot of these classes, it will be easier for your IntelliSense to fill in the correct class name, and it will alphabetically be listed next to the primitive type that is being wrapped.

Generics can help you out here:
public class WrapTwo<T>
{
public T Value1 { get; set; }
public T Value2 { get; set; }
}
public class WrapOne<T>
{
public T Value1 { get; set; }
}
And have you considered the Tuple class?

OneInt32, TwoInt32s, TwoDoubles? Doesn't sound great.
Tuples? http://www.dotnetperls.com/tuple

I don't very fond of Tuples or arrays, because both don't tell much about their purpose. Well, I use them. But mostly as internal members of classes, local variables, or with 3rd party/legacy code.
Back to naming. Compare:
Tuple<int,int> a = Tuple.Create(10,10);
Int32Double b = new Int32Double(15, 15);
WrapTwo<int> c = new WrapTwo<int>(20, 20);
With
Point a = new Point(10, 10);
Vertex b = new Vertex(15, 15);
One can argue, that 'a' is not good name for variable (and suggest to use 'pointA' instead). But I think it's pretty good in context of geometry application.
Not just type name and creation code looks obscure, but consider type fields names:
a.X = 20;
b.Value1 = 20;
So, I think you need some self-descriptive type in context of your application domain.

Related

C# - Types of Properties, and when to use one over the other

I've been looking into C# Properties, and I'm a little confused over what you gain by some suggested examples, such as Microsoft's.
Their class property example is as follows:
public class SaleItem
{
string name;
decimal cost;
public SaleItem(string name, decimal cost)
{
this.name = name;
this.cost = cost;
}
public string Name
{
get => name;
set => name = value;
}
public decimal Price
{
get => cost;
set => cost = value;
}
}
What does their example give you, over declaring your class properties such as:
public class SaleItem
{
public string Name { get; set; };
public decimal Cost { get; set; };
public SaleItem(string name, decimal cost)
{
Name = name;
Cost = cost;
}
}
I think the usage of this and => is throwing me off, as I'm not too familiar with them, but I generally dont understand what the difference is between these two examples, or why you might choose one over the other.
Apologies if this is too general a topic, but anyone can clarify any maybe point me in the direction of some useful resources, it would be appreciated.
In example 1 you actually get to code out your Properties with relatively little effort. While example 2 is Auto-Implement ones.
I generally prefer Auto-Implement Properties (case 2). Actually implementing any logic is secondary to me. I generally use Proeprties and Auto-implement ones are the shortest way to write them. I avoid fields entirely nowadays.
I do not see any advantage in case 1. It might be their way to showcase some new mechanics. Some way to code out properties without all that Bracket overhead. It looks like Lambda, but someone else mentioned it is not.
If anything I have to critizise cas 1. One of the biggest dangers of Properties is to accidentally use the backing fields in class code. That should never happen. And having the the backing fields just lower case is not a viable way to avoid it. Indeed Micrsoft own standart is to start backing fields with a underscore "_" so there is no mixups.
"name" and "Name"? Easy to mix up. I can not remember how often I typed to fast and a uppercase starting letter was not recognised.
"_Name" and "Name"? A heck of a lot harder to mix up and instantly visible if you do.
The this keyword is used for the current instance of the class. With this approach you can access members from within constructors, instance methods, and instance accessors.
this keyword is used when you want to refer to a instance. Ans then can be invoked to perform some calculation related with that instance.
By using auto-implemented properties, you can simplify your code while having the C# compiler transparently provide the backing field for you.
public string Name { get; set; };
public decimal Cost { get; set; }
Properties can be written with a simple lambda syntax, instead of having to write a full body
public string Name
{
get => name;
set => name = value;
}
Expression-bodied are added to improve properties declaration. Instead of statement blocks it’s now possible to define body as lambda expression. The syntax is quite easy to use =>.

Create overrideable enum in parent class

I want to create a nested structure where every class represents a country, inheriting the same parent class Country. Each child class should have an enum representing the different states States.
The goal is being able to select a country, then one of its states.
The Content will be saved into a dictionary Dictionary<Tuple<string, Type>, object> where the Types would be Country and Country.States.
I tried making an interface/abstract class with an enum called States to be implemented, but this does not work, as it is a type definition.
Is there any workaround?
public abstract class Country
{
public abstract enum States { get; }
}
public class CountryA : Country
{
public new enum States
{
StateA,
StateB,
StateC,
}
}
Your design is flawed, you need to create a single Country class with a property e.g. public string[] States { get; set; }.
Then create instances (objects) of your Country class, each with States set to the items that are needed:
var usa = new Country { Name = "USA", States = new[] { "Alabama", ... } };
var canada = new Country { Name = "Canada", States = new[] { ... } };
// etc
You have a few options:
You can create an enum at runtime (see here: Dynamically create an enum), but I don't think that'll suit your needs, as I imagine you're going down the enum route for ease of use in coding than anything else.
You could implement a typesafe enum pattern (see here: typesafe enum pattern), but that's even more coding just for the ability to use a design that mimics enums while your coding the rest of your logic.
My advice is to use a dictionary and build your 'states' at instantiation from a settings file or external data source. After all, countries and their states/cities/etc do change names from time to time. Locking yourself into a hard-coded situation like what you're aiming for isn't going to support such future changes.
Good luck!
[Edited following response from camilo-terevinto]
While I certainly agree that your design is most likely flawed, since you'd need hundreds of classes and enums, I disagree entirely with the other answers that "it is not possible".
It's certainly possible using generics (while keeping in mind you cannot restrict entirely to Enums):
public abstract class Country<TStates>
where TStates: struct, IConvertible, IFormattable, IComparable
{
public abstract TStates[] States { get; }
}
public enum UnitedStatesStates
{
WhoCares, WhoCares2
}
public class UnitedStatesCountry : Country<UnitedStatesStates>
{
public override UnitedStatesStates[] States { get; }
}
Now, I highly doubt this will be useful in the (not-so-long) term.
You are asking to make enum inheritable, this is possible to achieve if you don't use enum, but a class with static public members (which can be inherited and have different set of members per type). It behave nearly as enum:
public class Country1
{
public static State State1 { get; } = new State("State 1");
public static State State2 { get; } = new State("State 2");
...
}
It should be clear what Country1.State1 is, right? The State can be a more complex object than just a string. It doesn't require inheritance as you can see, because country define states as different members.
You can follow same principle to implement long chain of objects: Planet.Continent.Country.State.Province.Town.Street.Hause..
You say
Content will be saved into a dictionary Dictionary<Tuple<string, Type>, object> where the Types would be Country and Country.States.
Don't. Those are different types, that's a poor choice of a key. If you need to enumerate (to find) states, then just add another member to a Country:
public static IEnumerable<State> States
{
get
{
yield return State1;
yield return State2;
...
}
}
Then the searching for something can be a simple linq:
var stateAInCountry1 = ...Countries.OfType<Contry1>().Single().States.Single(o => o.Name == "A");
var countriesWithStateA = ...Countries.Where(o => o.States.Any(o => o.Name == "A"));
Not sure what problem are you solving by introducing a dictionary, but you can initialize additional data structure with proper key if you provided a way to iterate with easy.
It is not so clear to me, if there is anything else you want to achieve, besides being reminded by the compiler to define these different (!) enums.
Actually they have nothing in common to begin with, so neither the compiler nor you can draw any advantage of that contract.
What you could do is declare it as
public abstract string[] States {get;}
and obtain these strings from the individual enums you define in the derived classes. Then the common thing would probably be that you want the string result for informative purposes or something.

Why a Tuple, or a KeyValueItem, don't have a setter?

I needed a structure that contains a pair of values, of which ones value would be changed. So my first thought was to use a KeyValueItem or a Tupple<,> but then I saw that they have only a getter. I can't realize why? What would you use in my case? I could create my own class, but is there any other way?
They are immutable types. The idea of immutable types is that they represent a value, and so cannot change. If you need a new value, you create a new one.
Let's say the first value of your tuple needs to change, just do this:
myValue = Tuple.Create(newValue, myValue.Item2);
To understand why immutability is important, consider a simple situation. I have a class that say contains a min and max temperatures. I could store that as two values and provide two properties to access them. Or I could store them as a tuple and provide a single property that supplies that tuple. If the tuple were mutable, other code could then change these min and max values, which would mean the min and max inside my class will have changed. By making the tuple immutable, I can safely pass out both values at once, secure in the knowledge that other code can't tamper with them.
You can create your own implementation:
public class Pair<T, U> {
public Pair() {
}
public Pair(T first, U second) {
this.First = first;
this.Second = second;
}
public T First { get; set; }
public U Second { get; set; }
};
Tuples are read only in C#. This is explained in the answer here, mainly due to their nature from functional programming.
You should create your own MutableTuple implementation that allows modification.
Things to consider:
You might want to override Equals and GetHashCode
You might want it to be sortable on the First element of the tuple (IComparable).
Tuples historically come from functional programming, where everything is supposed to be immutable. You can learn more about functional programming here:
Functional Programming
What are the benefits of functional programming?
And to have benefits of the historical approach, Tuples in C# have been designed the same way. If you really want mutable tuples, you can easily implement that yourself:
public class MutableTuple<TFirst, TSecond>
{
public TFirst { get; set; }
public TSecond { get; set; }
}

C# Primitive Types or Complex Types as Method Signatures?

What are the pros and cons of using Primitve Types or Complex Types?
When should you use primitive types over complex types and vice versa?
i.e.:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public int IQ { get; set; }
}
public void FooPrimitiveTypes (string firstName, string lastName, int age, int IQ)
{
}
public void FooComplexTypes(Person person)
{
}
To pass each property separately are generally used when you are dealing with disjoint values. Also, sometimes used on constructors. Bad practice.
This way is preferred when the values are related.
Why #1 is a bad practice - suppose you needed to add height. I'd much rather update one class by adding another property, instead of 50 methods.
Does Foo conceptually deal with a Person? Does all (or at least most) of Person get used by Foo, or is it just using a few bits of information that happen to be in Person? Is Foo likely to ever deal with something that's not a Person? If Foo is InsertPersonIntoDB(), then it's probably best to deal with Person.
If Foo is PrintName(), then maybe PrintName(string FirstName, string LastName) is more appropriate (or alternatively, you might define a Name class instead and say that a person has a Name).
If you find yourself creating half initialized temporary Person objects just to pass to Foo, then you probably want to break down the parameters.
Something to note is that when you use primitives they are being passed by value... the object reference is also being passed by value but since all the underlying references to the values are references it is effectively pass by reference. So depending on what you are doing this pass by value or pass by reference could be of importance. Also in the first case modifications to the primitives will not affect the values of the variables in the calling scope however modifying the object passed in will affect the object in the calling scope.

Why can a class not have a static or constant property and an instance property of the same name?

I've never really questioned this before until now. I've got an input model with a number of fields, I wanted to present the string names of the properties through the input model so that my Grid can use them:
public class SomeGridRow
{
public string Code { get;set; }
public string Description { get;set; }
public const string Code = "Code";
}
Obviously, this gives the error:
The type 'SomeGridRow' already
contains a definition for 'Code'
Why can the CLR not cope with two properties of the same name which are, in my eyes, separate?
string code = gridRow.Code; // Actual member from instantiated class
string codeField = SomeGridRow.Code; // Static/Const
I'm now just using a child class called Fields within my inputs now, so I can use SomeGridRow.Fields.Code. It's a bit messy, but it works.
Because you can also access static (or, non-instance in this case) properties in the same way (inside the same class), and it would be a bit confusing, for example:
public class SomeGridRow
{
public string Code { get;set; }
public const string Code = "Code";
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
Because both this:
public class SomeGridRow
{
public string Code { get;set; }
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
And this:
public class SomeGridRow
{
public const string Code = "Code";
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
are valid ways to access properties, static or not. It doesn't answer the "why can't I?" question, but more of the why it's not allowed...it would be far too ambiguous IMO.
It probably could, but the designers of C# wanted to avoid ambiguities that can come from such use (abuse?) of language features.
Such code would end up being confusing and ambiguous to users (did I want the instance or the static method call?, Which one is right?).
In addition to the points already made about ambiguity, i would say that the naming needs to be relooked in such a case.
If two variables / fields having the exact same name in the same context i.e class but different values to me sounds more like a naming issue.
If they are exactly same, you dont need 2 fields.
If they are slightly different, you should have more accurate names.
In some other languages with a similar syntax, one can access a static member through an instance. So you could access both string.Empty and "abc".Empty.
C# doesn't allow this (though it does sort of from inside the class or a derived class, in that you can omit the class name for a static member and can omit this for an instance member), primarily to avoid confusion (I find it more handy than confusion tbh, but that's just me, I like switch fall-through too so what do I know).
Having introduced a stricter rule to allow for less ambiguity, it would be counterproductive to allow a new looser rule on the back of it that allowed for more. Think how many "why must I use this with property X but not property Y?" questions SO would have if it was allowed (we'd have to force this with property X to be clear we meant the instance member).

Categories