should i use extension method or member method in this case? - c#

for example,
class Aclass
{
void method1()
{
int[] a = new int[5]{1,2,3,4,5};
var b = a.Accumulated().ToArray(); // so that b = {1,3,6,10,15}
}
}
Currently Accumulated() is an extension method. However an equivalent approach I reckon is to define a private member method in Aclass so that MakeAccumulated(a).ToArray() gives {1,3,6,10,15}.
What is a good practice?

Aclass is a place for methods which make logical sense for Aclass objects; best practice is to not use it as a general store for helper functions. A good rule of thumb is that if a method never references member variables then it might be out of place in the class.
A function on int arrays probably has no place in Aclass. I'd put it in an extension method.

it's not a question of good practice but of preference. both are valid options. if you need the method only in instances of Aclass then I'd limit it to a class method, that's also more obvious to others inspecting the class.

I would choose the member function approach, cause extensions methods, I personally, choose for something I'm not able to extend, or have a problem to extend to (complexity, not mine code, serialization issues, whatever...). In your case, you have a class written by you, so just extend it, by following clear OOP design.
For extension methods, you need to define another class, for someone who is not very familiar with your code, or for you after 2 years, will be not very clear why it's done in that way.
Regards.

If .Accumulated() is only going to be called from instances of Aclass, make it a member of the class. It wouldn't be practical to have an application-wide extension method for int[] (or Ienumerable as someone else pointed out) if it's only used within an instance of one class. Keep in mind that extension methods are just for added extensibility.
public static string Hello(this string Value) { return Value + "Hello"; }
string s = "Hello".Hello();
...is the same as:
public static string Hello(string Value) { return Value + "Hello"; }
string s = Utilities.Hello("Hello");
Would you put .Hello() in a utility class if you're only going to use it within the instance of another class? If you use .Accumulated() elsewhere in the application, though, an extension method would work.

Related

C# Put Static Class Inside Dictionary

I was unclear in an earlier question I ask so I will try to be more explicit.
Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?
Here is how I would like to use it:
static class MyStatic : IInterface
{
static void Do(){}
}
static class MyStatic2 : IInterface
{
static void Do(){}
}
class StaticMap
{
static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
{
{Type.1, MyStatic}
{Type.2, MyStatic2}
};
}
// Client Code
class ClientCode
{
void Start()
{
StaticMap.dictionary[Type.1].Do();
}
}
There are some fundamental reasons why you can't do that directly:
Static method calls are bound at compile-time
Static calls are not inherited - they are tied to the class that defines them
There is no implicit base type (and therefore no polymorphism) between static methods, even if the name, inputs, and outputs are all the same
Since your signature is the same for every static method, you could store a Action in the dictionary instead:
static Dictionary<Type,Action> dictionary = new Dictionary<Type,Action>
{
{Type.1, MyStatic.Do}
{Type.2, MyStatic2.Do}
};
then you can call the Action directly:
void Start()
{
StaticMap.dictionary[Type.1]();
}
It's slightly repetetive because you have to specify the method name in the dictionary as well, but it's type safe.
A key question is whether you want to call a single method on each type or whether you need to call multiple methods belonging to each type.
If it's just a single method, then what D Stanley suggested is the answer. If you store a number of Actions, each representing a method with the same signature on a different static class, then you're accomplishing what you said.
However that raises a question - why the constraint that each method must belong to a separate static class? This approach would work just as well if some or all of the methods belonged to the same class.
If you need to call more than one method from each class then an Action no longer works. You'd have to store collections of Action, which a) means class instances, and b) is a lot more complicated than just using interfaces and class instances.
One way to manage instances is by using a dependency injection container to create class instances for you. Using that approach, you can create non-static classes without having to go through the hassle of explicitly making them singletons. But you can tell the container to only produce one of each and reuse it. For example, using Castle Windsor:
container.Register(Component.For<ISomeInterface,SomeClass>));
Now every time the container is asked to provide an instance of ISomeInterface it will always provide the same instance of SomeClass.
Because the dependency you're looking for varies by type (Dictionary<Type, Something>) it sounds like what you're looking for might be related to generics. But it would be necessary to take a step back from the smaller problem and understand a slightly larger picture of what you're trying to accomplish.
Instead of having the entire class as static, create a Singleton instance.
public class Foo
{
public static Foo _Foo;
public Foo()
{
_Foo = this;
}
}
Then you may add it to your list, and also inherit from Interfaces, etc.

Pass local variable to method in same class for testability?

I have a method that accesses variables local to the class itself. I'm wondering if that's a design flaw because now my unit tests are dependent on those variables being set. Is it weird/wrong to pass those variables to the method, even though that method has direct access to those variables? (If the method accepts those variables as parameters, then the unit test can also pass its own variables to the method.)
For example, here are the variables local to the class:
private static List<string> _whitelistNames = GetWhitelistNamesFromConfig();
private static List<string> _blacklistNames = GetBlacklistNamesFromConfig();
And the method looks something like this:
private static bool ThisProcessorHandlesThisFoo(Foo foo)
{
if (_whitelistNames.Count > 0)
{
// We're doing this instead of Contains() so we can ignore case sensitivity.
bool found = ListContainsString(_whitelistNames, foo.Name, StringComparison.OrdinalIgnoreCase);
// Some logging here
return found;
}
if (_blacklistNames.Count > 0)
{
bool found = ListContainsString(_blacklistNames, foo.Name, StringComparison.OrdinalIgnoreCase);
// Some logging
return !found;
}
throw new InvalidOperationException("some message");
}
In order to do what I'm suggesting, I would need to change the method signature to this:
private static bool ThisProcessorHandlesThisFoo(Foo foo, List<string> whitelistNames, List<string> blacklistNames)
Then the calling code (in the same class) would have to pass the local variables to the method. This would allow my test code to send its own parameters. Am I missing something? Is there a better way to do this? (It just seems odd to pass parameters that the method already has access to. But perhaps this is a good decoupling technique.)
You shouldn't have to worry about this.
Your unit tests should be testing the interface to your class (public methods and properties), and should not depend on any implementation detail (like a private class property). This allows the implementation to change without breaking other code (and hopefully without breaking existing tests).
Those private static fields should be initialized when the class is instantiated (according to your code, they have initializers). Are they initialized when it's instantiated for your unit test? They should be... It's a generally accepted idea that when the constructor for an object is finished running, the class should be in a usable state, and you're indicating that this isn't always the case.
This is an example of where something like Dependency Injection could be useful. You then pass these kinds of things to the constructor of your class (or through another means), and allow the part of the program that creates it (either your normal program or your unit test) to "inject" them into the class.
You should not test private methods, test the public ones in the way that tests cover all the class' code branches(including ones in private methods).
I'd recommend you to change method signature(to ThisProcessorHandlesThisFoo(Foo foo, List<string> whitelistNames, List<string> blacklistNames)) rather than use fields. As per my experience, such approach makes classes much easier to read and maintain.

Is there any point to making public-facing methods for private methods in a class?

Sorry if the question sounds confusing. What I mean is that if I have a class that has a method that does a bunch of calculations and then returns a value, I can either make that method public (which gives my other classes access), or I can make it private and make a public get method.
Something like this:
public publicmethod{
return privatemethod();
}
private privatemethod{
//do stuff
return value;
}
Is this a futile exercise or does it provide additional program security?
Well, there is no additional security here. However, such a usage can sometimes make sense.
For example, the private and public method may have different semantics.
// base class
public virtual BuyFood()
{
BuyPizza();
BuyCoke();
}
private void BuyPizza()
{
// ...
}
// derived class
public override void BuyFood()
{
BuyChopSuey();
}
private void BuyChopSuey()
{
// ...
}
So your implementation is just calling to a private method -- but what is important, you expose the semantics: your BuyFood operation is just BuyChopSuey(). Your code says: "in this class, buying food is just buying chop suey" in a clear way. You are able to add BuyTsingtaoBeer() into BuyFood() any time without changing the semantics of the both methods.
It is completely redundant. It does not provide anything except another name for the same thing and another indirection for readers to follow. Simply make a single implementation, and make it public. On the same note, getX() { return x; } setX(T newX) { x = newX; } does not encapsulate anything, at best it's future-proofing.
You may end up implementing a particular function required by an interface in a single line, largely delegating to (possibly private) methods which exist for other good reasons. This is different, and more justified (but again, if it's only return someMethod(); you should probably abolish the private implementation and assume the common name). A particular case if when you need two implement two methods which do the same thing (e.g. from separate interfaces).
I think either way is fine, it's more a matter of style assuming the method doesn't change the state of the class. If you have a class that has a bunch of properties and very few methods, it probably makes more sense to define another property. If you have a lot of methods in the class but few properties, then a method is more consistent with your overall class design.
If the method changes a bunch of other class variables than I'd expose it as a public method instead of a property.
I don't think either way, property or method, is necessarily more secure. It depends on what checks you do - is the caller allowed to perform the calculation? Are all variables used in the calculations within acceptable ranges? Etc. All of these checks can be performed whether you are using a property or a method.
Well, actually the question is What code do I want to be able to call this method?
Any code in general, even from other assemblies? Make the method public.
Any code from the same assembly? Make it internal.
Only code from this class? Make it private.
Having a private method directly aliased to a public method only makes the private method callable from the outside, which contradicts its private status.
If the method only does some calculation and doesn't use or change anything in the object, make it a public static method:
public static CalculationMethod(int input) {
//do stuff
return value;
}
That way any code can use the method without having the create an instance of the class:
int result = ClassName.CalculationMethod(42);
Instead of public consider internal, which would give access only to code in the same assembly.

C# Private members visibility

We have a Student class in our business model. something struck me as strange, if we are manipulating one student from another student, the students private members are visible, why is this?
class Program {
static void Main(string[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.SeePrivatePropertiesAndFields(s2);
}
}
public class Student {
private String _studentsPrivateField;
public Student() {
_studentsPrivateField = DateTime.Now.Ticks.ToString();
}
public void SeePrivatePropertiesAndFields(Student anotherStudent) {
//this seems like these should be private, even from the same class as it is a different instantiation
Console.WriteLine(anotherStudent._studentsPrivateField);
}
}
Can i have some thoughts on the design considerations/implications of this. It seems that you can't hide information from your siblings. Is there a way to mark a field or member as hidden from other instances of the same class?
There's an easy way to ensure this:
Don't mess around with private members of other instances of the same class.
Seriously - you're the one writing the Student code.
The easiest way to ensure this is to program to an interface, such as:
class Program
{
static void Main(string[] args)
{
IStudent s1 = new Student();
IStudent s2 = new Student();
s1.ExamineStudentsMembers(s1);
}
}
public interface IStudent
{
void ExamineStudentsMembers(IStudent anotherStudent);
}
public class Student : IStudent
{
private string _studentsPrivateMember;
public Student()
{
_studentsPrivateMember = DateTime.Now.Ticks.ToString();
}
public void ExamineStudentsMembers(IStudent anotherStudent)
{
Console.WriteLine(anotherStudent._studentsPrivateMember);
}
}
This will no longer compile due to ExamineStudentsMembers trying to access a private field.
If you are writing the class, you have complete control over it, so if you don't want one object to be able to modify another, don't write in that functionality.
Classes will often use private variables in other instances to implement efficient comparison and copy functions.
Private just means that the member (field/method/etc.) can be accessed only from the within the code of the parent type. From CSharpOnline
Private members of multiple instances are visible and can be invoked. This comes in handy when you are implementing a "copy constructor" or a "clone" method on your type, where the argument is an instance of the same type. If the designers would have made private fields inaccessible, then you may have to create a bunch of getter methods just for clone/copy to get at them. IMHO, I like it better the way it is. Within the same type, Reading another object's state isn't that bad as writing to it though (which could be a DONT-code-convention for you/your team.)
Accessing a sibling's private data may seem wrong when phrased like:
public void ExamineStudentsMembers(Student anotherStudent) {
//this seems very wrong
Console.WriteLine(anotherStudent._studentsPrivateMember);
}
However, it doesn't seem so odd for methods which require this sort of functionality. What methods require accessing a sibling's private data? Comparison methods (in particular equals) and objects in a data structure (say a tree or linked list).
Comparison methods often compare private data directly rather than just the public data.
For a class of nodes that make up a linked list, graph or tree, being able to access a sibling's private data is exactly what is needed. Code in the know (part of the class) can tinker around with the data structure, but code outside of the data structure cannot touch the internals.
It is interesting to note that these two cases are less common in day-to-day programming than when this language feature were first developed. Back in 1990s and early 2000s, in C++ it would have been much more common to build custom data structures and comparison methods. Perhaps it is a good time to reconsider private members.
i like the second point, you can look, but dont touch those private members.
it's funny you should say that, i knew a teacher once and he said he often had a problem deciding what classes it was ok to look at the members and which ones he could actually have a play with.
An object is just a piece of data; the class contains the functionality. A member method is just a nice trick the compiler plays; it's really more like a static method with an implied argument (sort of like extension methods). With that in mind, protecting objects from each other doesn't make any sense; you can only protect classes from each other. So it's natural that it works that way.
No, this is necessary, the method code is not specific to the instance, it is only specific to the type of the object. (virtual methods) or the declared type of the variable (for non-virtual methods). The non-static fields, on the other hand, are instance specific... That's where you have instance-level isolation.
The only difference between a static method and a non-static method is that the static method is not allowed to access other instance based (non-static) methods or fields. Any method that CAN be made static without modification will not be affected in any way by making it static, except to force compiler to throw errors anywhere it was called using instance-based syntax.
If you intend to examine a given student's information then I would change the method to be static:
public static void ExamineStudentsMembers(Student student)
{
Console.WriteLine(student._studentsPrivateMember);
}
You would then use Student.ExamineStudentsMembers(s1). Using s1.ExamineStudentsMembers(s2) would be invalid.
If this isn't the intended purpose I would rewrite the method as:
public void ExamineStudentsMembers()
{
Console.WriteLine(_studentsPrivateMember);
}
The above would then be used by writing s1.ExamineStudentsMembers()
Private members are to hide implementation details from clients. The clients should only see the interface (public methods / fields / properties).
The purpose is not to protect the programmer from himself.
This is also NOT a security feature because you can always access private fields via reflection.
It's really to separate interface & implementation (black box design), and clients programming against a contract (all public fields).
For example if you have a public get property, it could access some private field directly, or it could calculate the value from some other fields.
The purpose is, the client only knows the contract (the public property) and the implementation can be changed without affecting the client
Object scope does not ever imply security - ever! It is role of the OS to provide runtime security. It is a bug to design a system that relies on language specific object scope to limit runtime object instance data access. If this were not the case, then all non OO languages are, by definition, not secure.

Where should I put miscellaneous functions in a .NET project?

I found myself having to remove the first line of a string quite often while working on a text parser in C#. I put together a simple function to do that for me, but coming from a PHP background, I have no idea where to put it since I can't define a function outside a class. What's a customary way of doing that in .NET? Do I create a static class to store my function?
I generally make a Helper or Utility static class and then put corresponding helper functions in there.
Additionally, I try to keep the Helper and Utility classes grouped logically - putting the text parsing functions alongside the object conversion functions is nonsensical. The confusion is cleared up with a TextUtils class and a ConversionUtils class.
Yes, static helper classes are usually the way to do this.
Also, in C# 3 you can declare the method like this:
public static string RemoveFirstLine(this string s) {
...
}
to make it an extension method. Then you can call it on any string as if the method was declared on the string type itself.
Be careful!
Generic utility functions which are cross cutting should live in a higher utility namespace. String parsing, File manipulation, etc.
Extension objects should live in their own namespace.
Utility functions that apply to a specify set of business objects or methods should live within the namespace of those objects. Often with a Helper suffix, ie BusinessObjectHelper. Naming is important here. Are you creating a container for miscellaneous methods, or would it make more sense to group them into specialized objects, ie a parser?
I don't think there's a standard for this. I tend to make a static class called BlahUtil. For your example, I'd make it a static method on StringUtil. This helps me group related methods into sensible units, making it easier to discover them and share them across teams.
You can also then choose which of these methods are exposed as extension methods (since c# 3.0):
public static class StringUtil
{
public static string RemoveFirstLine(this string multiLineString)
{
// ...
}
}
If you are using C# 3.0, you might want to consider using an extension method!
public static class StringExtensions
{
public static string RemoveFirstLine(this string myString)
{
return myString.Remove("line..!");
}
}
Then in code you can do this:
string myString = "Hello World etc";
string removedLineString = myString.RemoveFirstLine();
Usually I create a Utilities class and define static helper methods.
I've done the static "helper" classes but after some analysis; this type of helper function always ends up as a distinct class implementation. In your case you'd have a "basic text parser" class and a derived class that overrides the "parse" method.
I'd create a static worker class for such functions. Maybe not the nicest way, but the one which keeps things simple... ;)
K
Use an extension method for a string. That's what they are for.
You can use a class with static methods. Something like ParserUtils.RemoveFirstLine(). On .NET 3.5 and above you can sometimes use extension methods when your utility functions are related to a class you cannot modify, like the String class. Intellisense will show the extension method on any string object in the project.
Extensions are the way to go in those case. It literally add your function to the occurence. Only thing is that it's not possible to do static method in 2008.

Categories