Is anything good/bad/unnecessary about this use of a public member? - c#

Here is a synopsis of my code which is a moderately complex WinForms GUI.
The context of the dependencies is the model view presenter pattern.
public class StatSyncherFormView : Form, IView
{ ... }
public class Presenter
{
// Here is the member I made public
public readonly IView view;
public Presenter(IView view)
{
this.view = view;
}
}
static void Main()
{
IView view = new View();
Presenter presenter = new Presenter(view);
// Here is where I'm accessing the public member
Application.Run((Form)p.view);
}
1) I like the fact that view is only set by the constructor and won't be modified after. It makes me feel better in the context of multi threaded GUI development.
2) With public View {get; private set;} then I lose (immutability?).
3) With private readonly IView view I also need public View {get {return view;}} which feels (to me at least maybe someone can tell me otherwise) redundant.
My Question: I feel like (3) is the only way to avoid using a public member, but in this case I do not understand the benefit.
I realize this is minutiae, so Thanks in advance for anyone who takes the time to give me advice about this.

Just give the Presenter a Run() method.

This is really just a variant on the publicly-visible fields vs properties debate.
Following the standard guidelines (your option 3) is what most people will recommend, despite what you call "redundancy". BTW I'm not sure which of the following you mean by redundancy
a few extra characters to type, or
an extra getter method at runtime (which will probably be optimized away by the JITter).
In neither case is the "redundancy" significant.
Having said that, in your specific case Hans Passant's answer, which is to avoid the need for the property/field altogether, is probably the best.

The benefits of your third approach (which I like most) include:
You may add logic to the getter later without the need of recompiling calling code
Encapsulation: you have exactly one place in your code that gets the value from the actual field, allowing you to add logging or use any other debugging mechanism to troubleshoot unexpected behavior.
The encapsulation also means that you could actually change the field to hold some other type, as long as it can be converted to IView. This conversion can happen in the getter.

If you use public field, you cannot change it to property later without recompiling your assembly. So I think it is better to do it right at the first place by using property.

Related

What is the name of this bad practice / anti-pattern?

I'm trying to explain to my team why this is bad practice, and am looking for an anti-pattern reference to help in my explanation. This is a very large enterprise app, so here's a simple example to illustrate what was implemented:
public void ControlStuff()
{
var listOfThings = LoadThings();
var listOfThingsThatSupportX = new string[] {"ThingA","ThingB", "ThingC"};
foreach (var thing in listOfThings)
{
if(listOfThingsThatSupportX.Contains(thing.Name))
{
DoSomething();
}
}
}
I'm suggesting that we add a property to the 'Things' base class to tell us if it supports X, since the Thing subclass will need to implement the functionality in question. Something like this:
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
if (thing.SupportsX)
{
DoSomething();
}
}
}
class ThingBase
{
public virtual bool SupportsX { get { return false; } }
}
class ThingA : ThingBase
{
public override bool SupportsX { get { return true; } }
}
class ThingB : ThingBase
{
}
So, it's pretty obvious why the first approach is bad practice, but what's this called? Also, is there a pattern better suited to this problem than the one I'm suggesting?
Normally a better approach (IMHO) would be to use interfaces instead of inheritance
then it is just a matter of checking whether the object has implemented the interface or not.
I think the anti-pattern name is hard-coding :)
Whether there should be a ThingBase.supportsX depends at least somewhat on what X is. In rare cases that knowledge might be in ControlStuff() only.
More usually though, X might be one of set of things in which case ThingBase might need to expose its capabilities using ThingBase.supports(ThingBaseProperty) or some such.
IMO the fundamental design principle at play here is encapsulation. In your proposed solution you have encapsulated the logic inside of the Thing class, where as in the original code the logic leaks out into the callers.
It also violates the Open-Closed principle, since if you want to add new subclasses that support X you now need to go and modify anywhere that contains that hard-coded list. With your solution you just add the new class, override the method and you're done.
Don't know about a name (doubt such exists) but think of each "Thing" as a car - some cars have Cruise Control system and others do not have.
Now you have fleet of cars you manage and want to know which have cruise control.
Using the first approach is like finding list of all car models which have cruise control, then go car by car and search for each in that list - if there it means the car has cruise control, otherwise it doesn't have. Cumbersome, right?
Using the second approach means that each car that has cruise control come with a sticker saying "I has cruise control" and you just have to look for that sticker, without relying on external source to bring you information.
Not very technical explanation, but simple and to the point.
There is a perfectly reasonable situation where this coding practice makes sense. It might not be an issue of which things actually support X (where of course an interface on each thing would be better), but rather which things that support X are ones that you want to enable. The label for what you see is then simply configuration, presently hard-coded, and the improvement on this is to move it eventually to a configuration file or otherwise. Before you persuade your team to change it I would check this is not the intention of the code you have paraphrased.
The Writing Too Much Code Anti-Pattern. It makes it harder to read and understand.
As has been pointed out already it would be better to use an interface.
Basically the programmers are not taking advantage of Object-Oriented Principles and instead doing things using procedural code. Every time we reach for the 'if' statement we should ask ourselves if we shouldn't be using an OO concept instead of writing more procedural code.
It is just a bad code, it does not have a name for it (it doesn't even have an OO design). But the argument could be that the first code does not fallow Open Close Principle. What happens when list of supported things change? You have to rewrite the method you're using.
But the same thing happens when you use the second code snippet. Lets say the supporting rule changes, you'd have to go to the each of the methods and rewrite them. I'd suggest you to have an abstract Support Class and pass different support rules when they change.
I don't think it has a name but maybe check the master list at http://en.wikipedia.org/wiki/Anti-pattern knows? http://en.wikipedia.org/wiki/Hard_code probably looks the closer.
I think that your example probably doesn't have a name - whereas your proposed solution does it is called Composite.
http://www.dofactory.com/Patterns/PatternComposite.aspx
Since you don't show what the code really is for it's hard to give you a robust sulotion. Here is one that doesn't use any if clauses at all.
// invoked to map different kinds of items to different features
public void BootStrap
{
featureService.Register(typeof(MyItem), new CustomFeature());
}
// your code without any ifs.
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
thing.InvokeFeatures();
}
}
// your object
interface IItem
{
public ICollection<IFeature> Features {get;set;}
public void InvokeFeatues()
{
foreach (var feature in Features)
feature.Invoke(this);
}
}
// a feature that can be invoked on an item
interface IFeature
{
void Invoke(IItem container);
}
// the "glue"
public class FeatureService
{
void Register(Type itemType, IFeature feature)
{
_features.Add(itemType, feature);
}
void ApplyFeatures<T>(T item) where T : IItem
{
item.Features = _features.FindFor(typof(T));
}
}
I would call it a Failure to Encapsulate. It's a made up term, but it is real and seen quite often
A lot of people forget that encasulation is not just the hiding of data withing an object, it is also the hiding of behavior within that object, or more specifically, the hiding of how the behavior of an object is implemented.
By having an external DoSomething(), which is required for the correct program operation, you create a lot of issues. You cannot reasonably use inheritence in your list of things. If you change the signature of the "thing", in this case the string, the behavior doesn't follow. You need to modify this external class to add it's behaviour (invoking DoSomething() back to the derived thing.
I would offer the "improved" solution, which is to have a list of Thing objects, with a method that implements DoSomething(), which acts as a NOOP for the things that do nothing. This localizes the behavior of the thing within itself, and the maintenance of a special matching list becomes unnecessary.
If it were one string, I might call it a "magic string". In this case, I would consider "magic string array".
I don't know if there is a 'pattern' for writing code that is not maintainable or reusable. Why can't you just give them the reason?
In order to me the best is to explain that in term of computational complexity. Draw two chart showing the number of operation required in term of count(listOfThingsThatSupportX ) and count(listOfThings ) and compare with the solution you propose.
Instead of using interfaces, you could use attributes. They would probably describe that the object should be 'tagged' as this sort of object, even if tagging it as such doesn't introduce any additional functionality. I.e. an object being described as 'Thing A' doesn't mean that all 'Thing A's have a specific interface, it's just important that they are a 'Thing A'. That seems like the job of attributes more than interfaces.

Is using get set properties of C# considered good practice?

my question is simple, is using the get set properties of C# considered good, better even than writing getter and setter methods? When you use these properties, don't you have to declare your class data members as public ? I ask this because my professor stated that data members should never be declared as public, as it is considered bad practice.
This....
class GetSetExample
{
public int someInt { get; set; }
}
vs This...
class NonGetSetExample
{
private int someInt;
}
Edit:
Thanks to all of you! All of your answers helped me out, and I appropriately up-voted your answers.
This:
class GetSetExample
{
public int someInt { get; set; }
}
is really the same as this:
class GetSetExample
{
private int _someInt;
public int someInt {
get { return _someInt; }
set { _someInt = value; }
}
}
The get; set; syntax is just a convenient shorthand for this that you can use when the getter and setter don't do anything special.
Thus, you are not exposing a public member, you are defining a private member and providing get/set methods to access it.
Yes, members should normally never be declared public in good design for several reasons. Think about OOP where you inherit the class later. Kind of hard to override a field. :-) Also it prevents you from keeping your internals from being accessed directly.
The simplistic get; set; design was introduced in C# 2.0. It's basically the same as declaring everything with a private member backing it (decompile it out in tool like Reflector and see).
public int someInt{get;set;}
is directly equal to
private int m_someInt;
public int someInt{
get { return m_someInt; }
set { m_someInt = value; }
}
The great part about having the simplified getter/setter is that when you want to fill in the implementation with a little bit more guts later, you do not break ABI compatibility.
Don't worry about getter/setters slowing down your code through indirection. The JIT has a thing called inlineing makes using the getter/setter just as efficient as direct field access.
Yes. Data members should be private and automatic properties allow it and give public access on right way.
But you should be careful. Understand the context is very important. In threaded application, update one property following an another related property can be harmful to consistency. In that case, a setter method updating the two private data members in a proper way makes more sense.
In your first example C# automatically generates the private backing fields so technically the data member is not declared as public only the getter/setter.
because with public data member , that data member can be changed or can be read out of class
and you cannot control read/write operation accessibility but with properties you can control
read/write stream for example consider this statement :
public MyVar{private get; public set;}
means value of MyVar can be changed only inside of class and can be read out of class(read privately and read publicly) and this is not possible with just public data members
In a "pure" object oriented approach, it is not considered OK to expose the state of your objects at all, and this appliese to properties as they are implemented in .NET and get_ set_ properteis of Java/EJB. The idea is that by exposing the state of your object, you are creating external dependencies to the internal data representation of your object. A pure object design reduces all interactions to messages with parameters.
Back to the real world: if you try to implement such a strict theoretical approach on the job, you will either be laughed out of the office or beaten to a pulp. Properties are immensely popular because they are a reasonable compromise between a pure object design and fully exposed private data.
It's quite reasonable, and your professor (without context) is wrong. But anyway, using "automatic properties", is fine, and you can do it whether they are public or private.
Though in my experience, whenever I use one, I almost inevitably end up needing to write some logic in there, and hence can't use the auto props.
your professor was quite right.
Consider this trivial example of why "getters" should be avoided: There may be 1,000 calls to a getX() method in your program, and every one of those calls assumes that the return value is a particular type. The return value of getX() may be sotred in a local variable, for example, and the variable type must match the return-value type. If you need to change the way that the object is implemented in such a way that the type of X changes, you're in deep trouble. If X used to be an int, but now has to be a long, you'll now get 1,000 compile errors. If you fix the problem incorrectly by casting the return value to int, the code will compile cleanly but won't work. (The return value may be truncated.) You have to modify the code surrounding every one of those 1,000 calls to compensate for the change. I, at least, don't want to do that much work.
Holub On Patterns

C# protected field to private, add property--why?

In Visual Studio 2008 Team System, I just ran Code Analysis (from the Analyze menu) on one of my C# projects. One of the warnings produced was the following:
Microsoft.Design : Because field 'Connection._domain' is visible outside of its declaring type, change its accessibility to private and add a property, with the same accessibility as the field has currently, to provide access to it.
It's referring to the following field:
public abstract class Connection
{
protected string _domain;
}
I don't understand the reasoning behind the suggestion. This is what I think it wants me to do:
public abstract class Connection
{
private string _domain;
protected string Domain { get { return _domain; } set { _domain = value; } }
}
Two questions:
Did I understand correctly what the suggestion wants me to do, code-wise?
Why does it want me to do this?
Yes, I think you understood correctly - although in later versions of C#, there's a more concise way to write it:
public string Domain { get; set; }
Why? It's all about encapsulation. If you do as it suggests, you can later change the definition of the Domain property without affecting any calling code that uses that property. Since your class is public, and might conceivably be called by code that you didn't write, that's potentially quite important.
This is because if you ever wanted to change the field to a property in the future you would break any other assemblies that depend on it.
It is good practice to keep all fields private and wrap them in properties so that you have the option of adding validation or other logic in the future without recompiling all consumers (or in this case inheritors) of your class.
Yep. That's the suggestion. You shouldn't have any accessibility higher than private exposed as direct instance fields.
It's one of the main principles of OOD - encapsulation also referred to as 'data-hiding'.
Yes, you did correct the problem code wise.
It is about encapsulation. _domain is data about your object. Rather then exposing it directly so that any client has unfiltered access, you should provide an interface for them to access it. Practically this might be adding validation to the setter so that it can't be set to any value. It might seem silly if you are the only one writing code because you know how your API works. But try to think about things on a large enterprise level, it is better to have an API so that your object can be seen as a box that accomiplishes a task. You might say you will never have the need to add something like validation to that object, but things are done that way to hold for the possibility of it, and also to be consistent.
Your translation is correct. The same argument for can be made for using 'protected' properties as can be made for using 'public' properties instead of exposing member variables directly.
If this just leads to a proliferation of simple getters and setters then I think the damage to code readablity outweighs the benefit of being able to change the code in the future. With the development of compiler-generated properties in C# this isn't quite so bad, just use:
protected string Domain { get; set; }
In answer to your question... yes.
However, I would just use the auto-property syntax:
public abstract class Connection
{
protected string Domain { get; set; }
}
Basically, properties provide more than returning or setting a member. They allow you to add logic that could verify a proper input format, range validation, etc.
The selected answer from the link puts it best, "Properties provide encapsulation. You can encapulate any needed validation/formating/conversion in the code for the property. This would be difficult to do for fields."
http://social.msdn.microsoft.com/Forums/en-IE/netfxbcl/thread/985f4887-92ae-4ec2-b7ae-ec8cc6eb3a42
In addition to the other answers mentioned here, public/protected members that begin with an underscore are not CLS-compliant, in that there is no requirement for .NET languages to support members with leading underscores, so someone inheriting from your class in a different .NET language may not be able to access that particular protected member.
I know, it probably doesn't apply to you, but it might be part of the reason for the code analysis warning.

Class internal usage of public properties

Let's say I have a class that exposes one property. Is it considered to be a good aproach to use the private "holder variable" for internal use in the class? Or should I use the property for internal use also.
To explain, should I use:
public class foo
{
String _statusHolder;
public String myStaus
{
get { return _statusHolder; }
set{ _statusHolder = value; }
}
public void DisplayMyStatus()
{
Console.WriteLine(_statusHolder);
}
}
Or:
public class foo
{
String _statusHolder;
public String myStaus
{
get { return _statusHolder; }
set{ _statusHolder = value; }
}
public void DisplayMyStatus()
{
Console.WriteLine(myStaus);
}
}
I could see it as beeing more consistent and more readable to use the second approach. It would also be more effective if I would later do some modificatins in the set-statement. But are there any performance issues or is it considered bad-practise for some reason?
EDIT:
It seems that everybody is leaning towards using the property internally. My initial thoughts was the same, but as a novice programmer, you can never know.
Thanks everyone for the quick feedback!
Performance issues should be negligable, as the JITer or compiler will happily work out that your function call (the getter of the property) doesn't do anything exciting, and can be inlined.
The benefit is future changes to business logic that might be put in the getter, which your class will then automatically take advantage of, without refactoring too much.
Of course, the downside is, you might want to avoid that new business logic in some circumstances, so it is something that needs to be considered based on how likely a) logic will change, and b) that logic might need to be circumvented.
The other (potential) advantage of using the property internally is that you can easily move to, or from, automatic properties.
I tend to go with calling the properties cause once stuff gets tricky you can put in locking and business logic in the getter
For C# 3.0 I would go with something along these lines (and only explicitly create the backing field when its really needed)
public class foo
{
public String Status
{
get;
set;
}
public void DisplayMyStatus()
{
Console.WriteLine(Status);
}
}
Use the property if there is one. A property can have side effects like lazy initializing that you want to have regardless from where you access the variable.
Even if the property has no side effects now, other developers could add them later, and the places where the "raw" variable is used may be error-prone because the new code is not called.
And lastly, the property makes refactoring easier, for example, when the value later is no longer stored in a variable but is calculated inside the property accessor or comes from some other source variable.
Programming in Java, I prefer using the getter method because I can put a breakpoint there and/or see changes to it in logging output.

Can I force subclasses to override a method without making it abstract?

I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer. However, the designer can't edit the subclass unless it can create an instance of the parent class. So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make another subclass, I won't get a compile-time error if I forget to implement them.
Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?
Well you could do some really messy code involving #if - i.e. in DEBUG it is virtual (for the designer), but in RELEASE it is abstract. A real pain to maintain, though.
But other than that: basically, no. If you want designer support it can't be abstract, so you are left with "virtual" (presumably with the base method throwing a NotImplementedException).
Of course, your unit tests will check that the methods have been implemented, yes? ;-p
Actually, it would probably be quite easy to test via generics - i.e. have a generic test method of the form:
[Test]
public void TestFoo() {
ActualTest<Foo>();
}
[Test]
public void TestBar() {
ActualTest<Bar>();
}
static void ActualTest<T>() where T : SomeBaseClass, new() {
T obj = new T();
Assert.blah something involving obj
}
You could use the reference to implementation idiom in your class.
public class DesignerHappy
{
private ADesignerHappyImp imp_;
public int MyMethod()
{
return imp_.MyMethod()
}
public int MyProperty
{
get { return imp_.MyProperty; }
set { imp_.MyProperty = value; }
}
}
public abstract class ADesignerHappyImp
{
public abstract int MyMethod();
public int MyProperty {get; set;}
}
DesignerHappy just exposes the interface you want but forwards all the calls to the implementation object. You extend the behavior by sub-classing ADesignerHappyImp, which forces you to implement all the abstract members.
You can provide a default implementation of ADesignerHappyImp, which is used to initialize DesignerHappy by default and expose a property that allows you to change the implementation.
Note that "DesignMode" is not set in the constructor. It's set after VS parses the InitializeComponents() method.
I know its not quite what you are after but you could make all of your stubs in the base class throw the NotImplementedException. Then if any of your subclasses have not overridden them you would get a runtime exception when the method in the base class gets called.
The Component class contains a boolean property called "DesignMode" which is very handy when you want your code to behave differently in the designer than at runtime. May be of some use in this case.
As a general rule, if there's no way in a language to do something that generally means that there's a good conceptual reason not to do it.
Sometimes this will be the fault of the language designers - but not often. Usually I find they know more about language design than I do ;-)
In this case you want a un-overridden virtual method to throw a compile time exception (rather and a run time one). Basically an abstract method then.
Making virtual methods behave like abstract ones is just going to create a world of confusion for you further down the line.
On the other hand, VS plug in design is often not quite at the same level (that's a little unfair, but certainly less rigour is applied than is at the language design stage - and rightly so). Some VS tools, like the class designer and current WPF editors, are nice ideas but not really complete - yet.
In the case that you're describing I think you have an argument not to use the class designer, not an argument to hack your code.
At some point (maybe in the next VS) they'll tidy up how the class designer deals with abstract classes, and then you'll have a hack with no idea why it was coded that way.
It should always be the last resort to hack your code to fit the designer, and when you do try to keep hacks minimal. I find that it's usually better to have concise, readable code that makes sense quickly over Byzantine code that works in the current broken tools.
To use ms as an example...
Microsoft does this with the user control templates in silverlight. #if is perfectly acceptable and it is doubtful the the tooling will work around it anytime soon. IMHO

Categories