how to represent class that contains no methods, only fields? - c#

My class contains no methods, only several fields, like host, port, labels, channels etc. etc.
I.e. its kind of config.
Should I use regular Class for representing configs? I want to make it obvious to reader that this instance is just a container for other values.
upd My config is pretty big and comes from xml, so it's a tree.

Yes, most likely you should be using class. There are rare case as pointed in other replies to use struct.
Name your class "ContainerForConfigurationProperties", than look at the resulting code. If it looks bad - refactor by changing class name till you are happy. Note that you may find that after coming up with good name some properties no longer fit into your class - it may mean that you class actually was container for several sets of properties - refactor by splitting the class.

If you use a class with public automatic-property getter/setters, then you can easily serialize/deserialize it (say to XML). Especially if the intent is to be consumed by other readers/developers, then using properties will shield them from changes when building against updated versions of your library. It also leaves the door open in the future if you want to implement anything in terms of tracking value changes, issuing events, performing validation, or just straight-up debugging with breakpoints.

Just call it a class, that's fine. It should be obvious what it's supposed to do, hold config info.
You may want to create an Interface in cases where you'll have a number of different config classes. For example, you might have an IConfig interface that has a few properties and then additional interface elements in more config interfaces (IHostConfig, ILabelConfig, etc.) that you can fit together to build your specific classes with a common, understandable, interface.

Related

How can I prevent methods from being added to a class?

I'm trying to find out if there's a way to stop functions/methods from being added (EDIT: by other developers) to a class for the case where the object is a Model or DTO which should not contain methods (to prevent 'abuse' of the Models/DTOs by others, who may try and add 'helper' methods etc).
Is there any way to achieve this?
Use reflection and write a unit test that fails if a model-class has methods.
Mark all you model classes with a custom attribute. Then make a unit test that uses reflection to load a given assembly, iterate all classes in that assembly and check that classes marked with the model attribute does not have methods. This should be fairly straight forward using reflection.
I believe you are trying to solve a procedural issue with code where you should be using communication.
Your colleagues (i assume) are operating on the code files with 'full trust' privileges. If they break that privilege you should open a dialogue. Use the change as an opportunity to educate them on the intended design. Perhaps they are correct and you will be educated!
I suggest simply making the intended design obvious in the class name and with a comment stating the intended nature. Perhaps quote the design document(s) that informed the class.
You cannot hinder anyone with full write-access to your code-base to do so. The only two things you may do to avoid it are create some CodeAnalysis-rule for FXCop as mentioned by Christian.K in the comments or by writing your DTO-class so that it is undoubtly a DTO that should not have any methods by using a unambigious name for the class and if this is not enough provide some code-comments that notifies the coder to do not so.
However you may need some kind of method if using collections e.g. where you will need some kind of comparision if two instances of your DTO are equal, so you have to provide at least an Equals- and GetHashCode-method.
You don't need to use a struct to prevent additions to a class. You can use the sealed keyword
public sealed class MyDTOObject { ... }
Now, you can not inherent a class and also prevent inheritance (which is essentially what you're asking). The very fact of inheriting MyDTOObject is creating a new class which is based off of not equal to, or restricted, or defined in any way by the implementation of MyDTOObject.
You can use an abstract class, to force derived classes to implement certain methods, but not the other way around.
If you want to prevent others from deriving from your class and implementing helper methods, you must use the sealed keyword, or mark the class internal.
You may prevent the class being extended or inherited by marking it final that way nobody would be able to extend your class and hence not being able to add any behavior. But stop and ask yourself whether you want to do that or not, because then you'd be signing an invisible contract that everything ever required by the class is written in the class and this class needs no further addition.
To be clear, I was talking in Java context.

To use or not to use a nested class when dealing with configuration settings

My program has a ReportConfiguration class that is used to store configuration information for the report. Logically, there are many areas that need to be configured, namely in how certain types of sections are displayed etc. A friend suggested that I take these sections and make them nested classes, such that:
public abstract class ReportConfiguration{
private class AssessmentTypeConfiguration{
}
}
public class MyConfiguration : ReportConfigration{}
Essentially, while I am going to be using these, I will be exposing these configuration classes to other developers who may want to extend some functionality, or write some tools that require the configuration to be modified. So I want them to be able to extend the configuration class, but there may be certain configuration options I do not want them to touch, or that just logically seem as if they should be nested.
The question: Is it even necessary to use separate classes, or just make one very large class with lots of properties for every configuration option?
I would recommend doing separate classes rather than one giant class for a few reasons:
It helps to group like information together so that it's easier to reason about
If you want to serialize and/or read the information they contain from a configuration file (or files), it'll be easier and probably more flexible to do so with smaller classes
If you're going with non-static classes (or ever want to), and are going to pass instances around, it makes more sense to pass limited information around rather than a giant object with everything under the sun
You say there are clearly separated configuration areas, so you should have clearly separated classes to match that. Otherwise, your single class might know too much, and classes should only be responsible for one thing.

Subclassing in protobuf.net

I have a system built around protobuf.net, the system exposes an abstract class (foo) which I expect the end user to implement. The abstract class is serialisable by protobuf.net. Currently, when I try to serialise an implementation of foo, I get an error:
Unexpected type found during
serialization; types must be included
with ProtoIncludeAttribute; found
bar passed as foo
This makes sense, I haven't told the system about bar, so when I pass a bar as a foo it gets confused. Is there a neat way to set things up such that it's simple for the programmer using my library to do things (preferably just marking fields as serialisable like normal protobuf.net usage?
Edit: Obviously, I cannot use protoinclude, as that requires modifying the source code of the base library.
In v1, the base will have to be decorated to know about the children. In v2 this restriction is removed; you can create a model at runtime and define everything you want. It can still read attributes too, this is all side-by-side (you can use different approaches on different types if you like).
You might, however, choose to hide the RuntimeTypeModel details away behind your own API if the caller doesn't want to know any gory details.
v2 is available to build from the trunk, and pretty much stable - there are some TODO items, though - mainly edge cases that need completing for full compatibility. Most people will not see these cases.

class definition and implementation in C# vs C++

With C++, I can have one class definition in a header file, and have a multiple implementation files by including the header file.
With C#, it seems that there is no such header file, as one class should contain both definition/implementation.
I wonder if the number of lines can be very big, because one can't separate the class into multiple files. Am I correct? I mean, in some cases, one can't change the class design to have smaller classes. In this case, is there a way to solve this problem?
You can separate a class into multiple files using the partial keyword
public partial class ClassNameHere
{
}
It is possible to split the definition of a class or a struct, or an interface over two or more source files using the Partial keyword modifier Link to msdn with the partial class
Partial classes only give you so much. There is still no way, that i know of, to split your class definition from implementation, such that each exists in a separate file. So if you like to develop based on a need-to-know paradigm then you are sort of stuck. Basically there are three levels a developer can work at...
1) Owns all the code and has access to, and maintains all of it.
2) Wishes to use some useful base class(s) which may form part of a framework, or may just be a useful class with some virtual methods, etc, and wishes to extend, or re-implement some virtual base class methods of interest. Now the developer should not need to go and look at the code in the base class(s) in order to understand things at a functional level. If you understand the job of a function, it's input and output parameters, there is no need to go and scratch inside source code. If you think there's a bug, or an optimization is needed, then refer to the developer from 1) who owns and maintains the base code. Of course there's nothing saying that 1) and 2) cannot be associated with the same developer, in which case we have no problem. In fact, this is more than often the case i suspect. Nevertheless, it is still good practice to keep things well separated according to the level at which you are working.
3) A developer needs to use an already packaged / sealed object / component dll, which exposes the relevant interfaces.
Within the context of c#, 1) and 3) have no problems. With 2) i believe there is no way to get round this (unless you change from exposing virtual base methods to exposing interface methods which can be reimplemented in a component owning the would-be base class). If i want to have a look at a class definition to browse over the methods, scaffolding functions, etc, i have to look at a whole lot of source code as well, which just gets in the way of what i am trying to focus on.
Of course if there is class definition documentation external to how we normally do it ( in headers and source files), then i must admit, that within the context of 2), there is not reason to ever look into a class definition file to gain functional knowledge.
So maybe clever Tom's came up with c#, decided to mix class definition with implementation in an attempt to encourage developers to have external documents for their class definitions, and interfaces, which in most IT companies is severely lacking.
Use a partial class as #sparks suggests, or, split into several classes. It's a good rule of thumb that, if you can't fit a class onto a couple of pages, it's complicated enough to need breaking apart.

How should i refactor this?

so in my application I've got several different customers being "serviced". Each customer has their own implementations of various classes that are all based on interfaces.
With the latest customer being added, I've noticed there will be a lot of duplication of code from another customer but the other customer is in no other way related to them.
I've already got a default implementation for several other customers and roll new ones as i need them.
My question is how do i refactor this and still keep the code clean? If i were a dev new to this code base i would want each customer to either use the default or their own implementation of these classes... but that's a lot of duplication.
Consider using an abstract base class with abstract or virtual members. Abstract members are essentially equivalent to interface members (they have no build-in behavior, they only guarantee the method exists) whereas virtual members have a default implementation which can be overridden by derived classes.
Your question is really too vague to answer in full, but here's how you can leverage inheritance.
If you want all classes to use the same implementation of a member then that member can be implemented in the base-class.
If you want each class to have its own implementation of a member then you can either use a base-class with abstract members, or an interface.
If you want some classes to use the same implementations and others to use different implementations then implementing the default behavior in the base-class and override it as needed.
My main point is that OOP there is a spectrum of how much or little functionality is in base/abstract/concrete classes. There's no silver-bullet answer, sometimes your base classes will be skeletons and sometimes they'll be fully fleshed-out; it all depends on the specific problem at hand.
Is there some way that you could create a base class, then a specific implementation for each customer and then using some type of Dependency Injection have that load classes or functionality as needed. You want to really have a DRY system so as to avoid headaches and typos or other similar human mistakes.
You may use either inheritance (put common logic to the base class) or aggregation (spread that logic among other classes and make use them from your customers).
I'd recommend the visitor pattern:
http://en.m.wikipedia.org/wiki/Visitor_pattern
As well as the mediator pattern:
http://en.m.wikipedia.org/wiki/Mediator_pattern
Reason being that it sounds like you may benefit from decoupling, or at least more-loose-coupling, the business logic from your classes, based on what you are saying.
It's a bit difficult to know what to suggest without a better understanding of the code... but some things that have worked for me in similar situations include:
Use a Strategy, for the duplicated code. I've had most success where the strategy is encapsulated within a class implementing a known interface (one class per alternate strategy). Often in such cases I use some form of Dependency Injection framework (typically StructureMap) to pass the appropriate strategy/strategies to the class.
Use some sort of template class (or template methods) for the common item(s).
Use a Decorator to add specific functionality to some basic customer.
STW suggested that I should offer some clarification on what I mean by "Strategy" and how that differs from normal inheritance. I imagine inheritance is something you are very familiar with - something (typically a method - either abstract or virtual) in the base class is replaced by an alternate implementation in the derived class.
A strategy (at least the way I typically use it) is normally implemented by a completely different class. Often all that class will contain is the implementation for a single replaceable operation. For example if the "operation" is to perform some validation, you may have a NullValidationStrategy which does nothing and a ParanoidValidationStrategy which makes sure every McGuffin is the correct height, width and specific shade of blue. The reason I usually implement each strategy in its own class is because I try and follow the Single Responsibility Principle which can make it easier to reuse the code later.
As I mentioned above, I typically use a Dependency Injection (DI) framework to "inject" the appropriate strategy via the class constructor, but a similar results may be obtained via other mechanisms - e.g. having a SetSomeOperationStrategy(ISomeOperation StrategyToUse) method, or a property which holds the strategy reference. If you aren't using DI, and the strategy will always be the same for a given customer type, you could always set the correct choices when the class is constructed. If the strategy won't be the same for each instance of a given customer type, then you probably need some sort of customer factory (often a factory method will be sufficient).
I'd go with the answer of spinon (got my vote at least), but it's to short so let me elaborate:
Use your interfaces for the default implementation and then use dependency injection. Most tools allow you to define a scope or some criteria how to resolve something.
I assume that you do know the client at some early point of the program. So for ninject you just might want to define a "Module" for each client and load that into the kernel, depending on the client.
So I'd create a "no customization" Module and create a "ClientX" Module for every special case that uses ´Bind.To()` instead.
You end up with
a base implementation that is clean/default
a single place change for a new client (got a new one? Great. Either it works with the default or just needs a single Module that maps the interfaces to other classes)
The rest of the code shouldn't mind and get the dependencies via injection (constructor, property, whatever is easiest to go for. Constructor would probably be the nicest way) and has no special treatment at all.
You could even use a conditional binding in Ninject link text to solve the binding issue without different modules at all (although, depending on the number of clients, this might get messy and should better be separated).
I was going to suggest aggregation, as #the_joric suggests, over inheritance, but your description makes it sound like your application is already reasonably well-factored - that there aren't a lot of small classes waiting to be extracted from your existing classes. Assuming that's the case, for any given interface, if you have a perfect class for the new customer already written and ready to go, I would say go ahead and use it. If you're worried about that, for some reason, then take that perfect class, make it abstract, and create empty subclasses for your existing customer and your new customer - and if it's not quite a perfect fit, then that's the way I would go.

Categories

Resources