Bond: How to change field and class names during code generation - c#

I have a bond file with a struct like this:
struct Foo
{
0: float myField1;
1: float myField2;
}
I am using this file to generate code for C++ and also for C#. But in the C# code, I want the field names to be capitalized: MyField1, MyField2.
Is there any way to do this?
Similarly, I might want Foo to be named Bar in my C# code (in order to be backward compatible with my pre-bond clients). But I don't see any documentation on how this can be done.

There is no way to rename types/fields when using the Bond code generator, gbc. The features simply don't exist.
If you want, you can write a C# class by hand and annotate it with Bond's attributes. This will get you a highly compatible struct. You do lose much of the benefit of having one, central location to describe the structs in the .bond file with this approach. That might be the right trade off to interface with your pre-Bond clients by annotating the existing classes.
An example of how you'd do this based on the structs in the question:
[Bond.Schema]
class Bar
{
[Bond.Id(0)]
public float MyField1;
[Bond.Id(1)]
public float MyField2;
}
This has some caveats:
You'll have to manually keep it in sync with the .bond file when you make changes.
The full schemas of these Foo and Bar structs differ slightly. The fields have different names ("myField1" vs. "MyField2"), which you'll be able to detect if you look at the SchemaDef of each struct. When using binary protocols, the field names don't matter: only the IDs do. When using the text-based protocols, the names do matter.

Related

C# attribute formatting conventions

Lately I've seen attribute tags formatted into two ways in C# (even in the official microsoft guide):
[foo]
public class bar {...}
and
[foo] public datatype bar;
Is there any advantage to where the tag is placed? Should the tag be placed in a certain position based on whether it is over a class or a datatype?
it's personal preference, it's not going to make any difference to the compiler, pick one and be consistent.
That said, I prefer the 1st format in both cases because it's possible to have multiple attributes on both classes and datatypes - and I find it easier to read spread out.
it would get messy quickly if you did that in-line.
take the following sample code for a class for example:
[Author("P. Ackerman", version = 1.1)]
[Author("R. Koch", version = 1.2)]
class SampleClass
{
// P. Ackerman's code goes here...
// R. Koch's code goes here...
}
putting it inline just makes it unreadable.

C# class instance attribute mechanism

Is there a sane way in C# to achieve the following construct (in pseudocode):
void Method(MyClass<Attribute1, Attribute2, ...> foo)
{
// here I am guaranteed that foo has the specified attributes
}
Where Attribute* are, for example, enum values, such that only instances of MyClass instantiated with the attributes required by the method can be passed to the method (and otherwise fail to compile)?
I tried looking at generics since I know that C++ templates can make this work so it seemed like a logical starting point, but I couldn't get it working elegantly (I tried using interfaces to constrain the types of the parameter in this fashion but it was very bulky and frankly unusable since I have at least 4 attributes).
I want to do this to avoid having lots of annoying checks at the beginning of each method. I am doing DirectX 11 graphics development so I am kind of constrained by the API which does not make it particularly easy to pass objects around in this "type-safe" manner (in DirectX every resource has a large "Description" structure which contains information about what the resource can and cannot do, is and is not, etc.. and is tedious and error-prone to parse, so I am trying to write a wrapper around it for my and my users' convenience).
I also cannot have different class types for every case because there are a lot of combinations, so this seems like the most comfortable way to write code like this, and I am hoping C# makes this possible.
I'm sure there is a name for this kind of language feature (if you know it please let me know, I would have googled but this is kind of hard to search for when you don't know the proper keywords...)
Generic type parameters in .NET must be types themselves. You can't create a generic type/method that is specific to a particular value of the Generic type parameter only.
If you do not want or cannot create a type that represents the attribute values you want your method being restricted to, you will have to do sanity checks in your method to ensure that the proper attribute values are used in the provided "foo" object.
Using specific types as representation of specific attribute values might be an answer for the problem you asked about, but it has the disadvantage of not supporting switch-case statements (see further below). Please also read the final note at the end of my answer.
Say, you want a type that represents textures. Textures can have different number of channels, and different bit depths. You could then declare a generic texture type like this:
class Texture<TChannels, TBPC>
where TChannels : INumOfChannels,new()
where TBPC : IBitsPerChannel,new()
INumOfChannels and IBitsPerChannel are just interfaces and can be empty.
The new() constraint prevents creation of a concrete Texture type by using the interfaces themselves.
For different channels and different BPCs, you will create empty types extending from the respective base interfaces, for example:
class FourChannels : INumOfChannels {};
class ThreeChannels : INumOfChannels {};
class BitsPerChannel_24 : IBitsPerChannel {};
class BitsPerChannel_32 : IBitsPerChannel {};
Using this, you can restrict your generic method to certain attribute combinations. In case your method should only deal with 4-channel and 32bpc textures:
void MyMethod<TChannels, TBPC>(Texture<TChannels, TBPC> foo)
where TChannels : FourChannels
where TBPC : BitsPerChannel_32
Now, every good thing also has dark sides. How would you do something like this (written as pseudo-code)?
switch (NumOfChannelsAttribute)
{
case FourChannels:
// do something
break;
case ThreeChannels:
// do something else
break;
}
You can't, at least not in an easy and simple way, because "FourChannel" and "ThreeChannel" are types, not integral values.
Of course, you can still use if constructs. For this to work you would need to implement a property in the generic texture type which provides the used attributes:
class Texture<TChannels, TBPC> where TChannels : INumOfChannels,new() where TBPC : IBitsPerChannel,new()
{
public Type ChannelsAttribute
{
get { return typeof(TChannels); }
}
public Type BitsPerChannelAttribute
{
get { return typeof(TBPC); }
}
}
In an if construct, you could utilize this as follows:
var myTex = new Texture<FourChannels, BitsPerChannel_32>();
if (myTex.ChannelsAttribute == typeof(FourChannels))
{
... do something with 4 channels
}
else
{
... though luck, only 4 channels are supported...
}
A final note and advice:
While this might work for your problem, resorting to these kind of 'tricks' usually is an indication of a flawed design. I think it is well-invested time if you revisit the design choices you made in your code, so you don't need to rely on crutches like this.
C# doesn't have such a feature. You mention you have tried using interfaces, but don't specify how. The way I'd suggest you try using them is by using generics with multiple constraints, eg
void Method(T foo) where T : IAttribute1, IAttribute2, IAttribute3, IAttribute4
{
}
Let's say one such attribute class is then ICpuMappable, then you can constrain types that can be used with Method1 with:
void Method1(T foo) where T : ICpuMappable
{
}
and you can know any foo passed to Method1 is CPU mappable.
You'll likely end up with lots of interfaces, but as many will be treated as "flags", they shouldn't be too difficult to maintain.

c# Public Nested Classes or Better Option?

I have a control circuit which has multiple settings and may have any number of sensors attached to it (each with it's own set of settings). These sensors may only be used with the control circuit. I thought of using nested classes like so:
public class ControlCircuitLib
{
// Fields.
private Settings controllerSettings;
private List<Sensor> attachedSensors;
// Properties.
public Settings ControllerSettings
{ get { return this.controllerSettings; } }
public List<Sensor> AttachedSensors
{ get { return this.attachedSensors; } }
// Constructors, methods, etc.
...
// Nested classes.
public class Settings
{
// Fields.
private ControlCircuitLib controllerCircuit;
private SerialPort controllerSerialPort;
private int activeOutputs;
... (many, many more settings)
// Properties.
public int ActiveOutputs
{ get { return this.activeOutputs; } }
... (the other Get properties for the settings)
// Methods.
... (method to set the circuit properties though serial port)
}
public class Sensor
{
// Enumerations.
public enum MeasurementTypes { Displacement, Velocity, Acceleration };
// Fields.
private ControlCircuitLib controllerCircuit;
private string sensorName;
private MeasurementTypes measurementType;
private double requiredInputVoltage;
... (many, many more settings)
// Properties.
public string SensorName {...}
... (Get properties)
// Methods.
... (methods to set the sensor settings while attached to the control circuit)
}
}
I have read that public nested classes are a "no-no" but that there are exceptions. Is this structure OK or is there a better option?
Thanks!
EDIT
Below is a crude hierarchy of the control circuit for which I am trying to write a library class for; I used code formatting to prevent text-wrap.
Control Circuit (com. via serial port) -> Attached Sensors (up to 10) -> Sensor Settings (approx. 10 settings per sensor)
Basic Controller Settings (approx. 20 settings)
Output Settings (approx. 30 settings)
Common Settings (approx. 30 settings)
Environment Settings (approx. 10 settings)
All of the settings are set through the controller but I would like an organized library instead of just cramming all ~100 methods, properties, and settings under one Controller class. It would be HUGELY appreciated if someone could offer a short example outlining the structure they would use. Thanks!
The contents of a class should be the implementation details of that class. Are the nested classes implementation details of the outer class, or are you merely using the outer class as a convenient name scoping and discovery mechanism?
If the former, then you shouldn't be making the private implementation details publically available. Make them private if they are implementation details of the class.
If the latter, then you should be using namespaces, not outer classes, as your scoping and discovery mechanism.
Either way, public nested classes are a bad code smell. I'd want to have a very good reason to expose a nested class.
I don't have too much problem with public nested classes (I'm not a fan of dogmatic rules, in general) but have you considered putting all of these types in their own namespace instead? That's the more common way of grouping classes together.
EDIT: Just to clarify, I would very rarely use public nested classes, and I probably wouldn't use them here, but I wouldn't completely balk at them either. There are plenty of examples of public nested types in the framework (e.g. List<T>.Enumerator) - no doubt in each case the designers considered the "smell" of using a nested class, and considered it to be less of a smell than promoting the type to be a top-level one, or creating a new namespace for the types involved.
From your comment to Eric's answer:
These sensors can ONLY be used with a specific circuit
This kind of relationship is commonly known as a dependency. The Sensor constructor should take a ControlCircuit as a parameter. Nested classes do not convey this relationship.
and you can't get/set any sensor settings without going through the controller circuit;
I think that means that all Sensor properties will delegate to (call) or somehow inform (fire an event on) the ControlCircuit when they're used. Or, you'd have some kind of internal interface to the sensor that only the control circuit uses, making Sensor an opaque class to the outside world. If that's the case, Sensor is just an implementation detail and could be nested private or internal (there's also no need to "save" a sensor instance if you can't do anything with it).
Also, I don't even want to expose a Sensor constructor (the controller will have a method for this)
The fact that the Sensor constructor now takes a control circuit is enough of a hint as to what depends on what that you could leave the constructor public. You can also make it internal.
A general comment that I have is that this design is very coupled. Maybe if you had some interfaces between control circuit, sensor and settings, it would be easier to understand each component independently, and the design would be more testable. I always find beneficial to make the roles that each component plays explicit. That is, if they're not just implementation details.
I would say the better option is moving those nested classes out of the class they're in and have them stand on their own. Unless I'm missing something you appear only to have them in the main class in order for some sort of scoping concept, but really, that's what namespaces are for.
I generally disagree with Eric on this.
The thing I usually consider is: how often should the end user use the type name ControlCircuitLib.Sensor. If it's "almost never, but the type needs to be public so that doing something is possible", then go for inner types. For anything else, use a separate type.
For example,
public class Frobber {
public readonly FrobType Standard = ...;
public readonly FrobType Advanced = ...;
public void Frob(FrobType type) { ... }
public class FrobType { ... }
}
In this example, the FrobType only acts as an opaque 'thing'. Only Frobber needs to know what it actually is, although it needs to be possible to pass it around outside that class. However, this sort of example is quite rare; more often than not, you should prefer to avoid nested public classes.
One of the most important things when designing a library is to keep it simple. So use whichever way makes the library and the using code simpler.
I like nested classes in cases like this because it shows the relationship. If you do not want users of the outer class to be able to create items of the inner class separately from the outer class, you can always hide the constructors and use factory methods in the outer class to create elements of the inner class. I use this structure a lot.
This structure seems completely reasonable to me. I wasn't aware until today that Microsoft has advised against doing this, but I'm still not aware why they've advised as such.
I've used this structure in a situation where the nested class only exists to support the containing class (i.e. it's part of its implementation), but other classes need to be able to see it in order to interact with the containing class (i.e. it's part of the class's API).
That being said, Eric generally knows what he's talking about, so out of respect for his knowledge and for the time being, I've converted those classes to use namespaces instead.
Currently, I'm not liking the results. I have a class named BasicColumn, which exists only to represent a column in a class called Grid. Previously, that class was always addressed as Grid.BasicColumn, which was great. That's exactly how I want it to be referred to. Now, with the Grid and the BasicColumn both in the Grids namespace, it's just referred to as BasicColumn with a 'using Grids' at the top of the file. There's nothing to indicate its special relationship with Grid, unless I want to type out the entire namespace (which has a few prefixes before Grid I've left out for simplicity).
If anyone can point out an actual reason why using public nested classes is somehow counterproductive or suboptimal, other than the irrelevant fact that Microsoft doesn't intend for them to be used that way, then I'd love to hear it.
While I feel Eric's answer is correct, it is important to realize it doesn't really fully address what your situation is.
Your case sounds very similar to one I frequently find myself in where you have a class which is really implementation details of another class, however, some details or functionality of that sub-component naturally lend themselves towards being exposed directly for some minor aspects that are not governed by the parent.
In these cases, what you can do is use interfaces. The nested classes need not be public as they really are internal details of the class they are nested within, but a subset of functionality (an interface) needs to be made publicly available and can be implemented by the class.
This allows for construction of the internal structures to be controlled by the class they are nested within while still allowing direct access to the type from a namespace for external references. (The caller will use SomeNamespace.IChildApi as the name rather than SomeNamespace.NestingClass.NestedClass.SecondNestedClass.ThirdNestedClass, etc.)

How to implement a "function" to be performed on an array in C#

Coming from a non-OO background in Matlab, I'm looking to perform some of the operations I am used to in a best-practice manner for C#.
I have a class, which imports data from a source, and formats it into, amongst other things, an array of ints. I am going to want to perform some operations on this array. To keep it simple, lets say I want to take the average of all the values. The way I see it, I have three options:
The array is part of MyClass, so I could extend MyClass to return the average of MyArray.double arrayAverage=MyClass.ArrayAve;
I could develop a static class, giving me access to the average by double arrayAverage= zotty.arrayMath.average(MyArray);
There is apparently some way in which I can inherit or interface so that I create a class specifically for performing such operations, which Id then be able to access by instantiating this new class, and passing it the array:
OperatorClass oc = new OperatorClass();
oc.data=MyClass.MyArray;
double arrayAverage = oc.ArrayAverage();
Extending the class seems risky, since it's also responsible for importing and formatting the data. I could become quite large if I add all the data processing to it too, and it wouldn't be straightforward for other people to add-to & work on alongside me.
Future code will require more complex operations on the array, and I've no idea what they will be at the moment. I will have use for some of the basic operations in future programs, which would be useful as part of the static class - the complex ones however would be redundant.
The separate class for performing the data processing allows the import/formatting class to remain isolated. It can provide both general and specific functions, but at the cost of instantiating another variable in the code, which seems to me to be a bit untidy.
I'd appreciate some input if you have thoughts on the matter!
You can simply expose the array as IEnumerable<int> and then use any LINQ method, such as Average:
MyClass myObject = ...
double a = myObject.Data.Average();
where
class MyClass
{
private int[] data;
public IEnumerable<int> Data
{
get
{
return this.data;
}
}
}
A benefit in your first option (doing the work inside MyClass) is that you are not exposing the internal workings of the class to its clients. Let's say at some point in the future you decide you need to change the collection from an array to a generic List. Keeping the processing internal to the class means you will not need to hunt around and change other classes that have a tight dependency on how MyClass is implemented (like the OperatorClass)
I highly recommend picking up this book from Didier Besset on creating object oriented numerical methods. The concepts have been very helpful to me over the years. Even though the examples are in Java, the code transfers easily to C#.
-Scott
You could write extension methods to do the processing that you want. This would put the processing in a different class from the data, and if your object hierarchy allows it will also allow the same methods to be used on other classes later. Note that if you go this path, you will need to provide enough information publicly for the extension methods to work (since they're not a part of the class, they can't access private or protected members).

C# - Creating a code file with common definitions/constants/enums etc?

In C++ I'd often create a code file containing constants, enums, #define-s, macros etc.
What's the best practice for that in C#? Do I create a static class and fill it with that data? or is there some other way ?
You don't need a static class for enums - they can be top-level (meaning: namespace level). Yes, you need a class for constants (and a static class would suffice), but I would tend to have multiple classes - one per intent. There is no need to cram them all together.
In C#, any #define only apply to that file, so there is not much point having a class for them (put them in the project / build-script instead). And macros don't exist.
If you have some items you want to define Globally, like a set of strings, I would use a static class with Static properties. I would do that if you are going to use it in more than 1 place.
If you are going to use a defined string for example in just once place, then I would put it in the class that is referencing it.
It is very important to use properties and not expose members. I have found with C++ developers I have worked with when they move to C# they expose members because they have no need for "the special logic of a property". While that may be true when you initially are writing the code. If you expose it as a member and need to do special logic then you have to refactor in a major way. While if you begin as a property then you can add the logic with no refactoring.
For Enums I tpyically define an Enum.cs file inside the folder that represents the namespace. Rather than define them inside a static class.
Macros:
Macros don't exist in C#.
#Defines:
defines are very restricted and only really used for conditional compilation. You should define them by using the project properties (or in your msbuild script) instead.
Enums:
Enums should each go in their own separate file. They don't need to be within a class, they just go directly in the name space.
Constants:
Personally I try to keep constants to a minimum, and private within a class where possible.
If you do have to make them public and globally available, use a static class (or a normal class if they relate directly to one nicely). Try to group them into classes by their use.
If you are talking about string constants, you could consider using a resource file instead if they are localizable strings.
Usually there is a class or struct for which your enum etc. particular applies. I put it in that file, under the class. It's easy to get to the definition from anywhere it's used in code. When possible, I try to put all similar entities for a namespace (or other logical grouping) in the same place.
I'd already object to that practice in C++.
Define that stuff where you need it and not in a single "dump" file. This kind of file tends to accumulate huge amounts of unused stuff over time. And it's hard to clean up because who knows, which parts of your code is using it...

Categories

Resources