.NET: How do I mark a method as "Not yet used"? - c#

I'm using ASP.NET and I know that I can mark a method as:
Obsolete
Not for future use
But I'm asking if I can mark a method as "Not yet used", that means "I wrote it but actually it is unused, sooner or later someone will using it".
Thanks!

You can throw a NotImplementedException with a appropriate message in your method. This will ensure during runtime that the method is not called.
public void MyMethod(){
throw new NotImplementedException("This will be implemented soon");
}
If you want to use metainformation you can define your own Attribute to decorate your methods. (But I think you can also reuse the ObsoleteAttribute with a special message)

No, you cannot. And it doesn't make much sense to do so.
Visual Studio 2015 does show you the method usage inside your current project, which is an indicator for 'dead' methods:

I assume you want it for a future functionality that currently is not active because is not fully implemented (is the only case I can imagine that make sense).
If you don't want it to be used don't put it in the interface (you should use interfaces) or put it in a distinct one that only you have. You can also use the Obsolete decorator with a "this is not meant to be used yet" message.
If anyone can use it because it's public and released you should not care about how many references it has. Usually you can't know it if the references are from outside your solution. You should not delete such a method because that is a breaking change.
If it's private your IDE should warn you and you can delete it or comment its future usage; add a reference to the functionality it is meant for so you can delete it in case it is closed (someone decides that is not going to be implemented).

This is managed by the NotImplementedException and can be very usefull when implementing interfaces where you know the members you need in the future but don´t want to implement them right now. Any user of the method will get the exception, however if you need a compile-time flag you´d be off by using the Obsolete-attribute together with a meaningul message such as "This method is not yet implemented" and the exception inside.

Just because you can doesn't mean you should....
Why write code that's not yet used?
That's like taking thermal underwear to the Sahara in case of a cold snap, when you're only visiting during the day.
While you can throw a NotImplementedException this won't give you compile time safety - it will just throw this exception on run time.

You can express all of your sorrow about the unused method in the Documentation Comment for this method. Just don't throw any NotImplementedException's or else this method isn't going to be used ever.
This is kinda dumb though, you should remove it if it is not used. As practice shows, most of the 'Not yet, but maybe some day' code is not going to ever be used at all, so it makes perfect sense to remove it. If for some reason you later need the method, you can always check your source control for that.
If you would like to litter your solution even more though, you can always do something stupid like implement your custom [PleaseUseMe]Attribute

Related

What's the difference between NotSupportedException and NotImplementedException?

My classes that implements an interface, I've got to throw an exception if the class doesn't support values from parent class (done by setting the get property to false/true), so why should I use NotSupportedException, but not NotImplementedException?
When should I use NotImplementedException then? learn.microsoft.com say that it's always better to use NotSupportedException, is it true?
I've found sth like that: https://blog.excastle.com/2004/10/15/notimplementedexception-vs-notsupportedexception/, but it was written in 2004, I think many changed after that. Also, it is written in quite complicated way.
"Not Implemented" implies that it could be implemented it in the future. "Not Supported" makes no such implication as to whether you may implement it or if it even can be implemented.
NotImplementedException is generally used during development as a way to flag to yourself (or Testers, or any other developers) that some aspect hasn't been implemented yet but it is intended to be implemented. You wouldn't normally include this exception in a formal release.

Mark method as obsolete for a single project

Due to the way our codebase works, I was advised to not edit certain methods in a shared codebase. Instead, I decided to make a new method that calls the old one and also does the new work our team wanted that method to do. The issue I am foreseeing is not everyone on the team being aware of the new method and still using the old one from the shared codebase.
TLDR:
Shared codebase has SharedCode.Function.
I created OurCode.Function which does some stuff, and then calls SharedCode.Function.
I cannot edit SharedCode.Function or it's containing project.
Is it possible to mark SharedCode.Function as obsolete within our project as a compiler warning somehow or otherwise mark that OurCode.Function essentially replaces it?
EDIT:
Might be pertinent to mention- these are logging functions, so if a dev accidentally calls SharedCode.Function instead of OurCode.Function, the only result is that we capture less data than we desired, it will still compile and run fine. This is a major reason I want to try to make it a compiler warning, so that any dev that doesn't know to use the new function will find out to.
The shortest way is by adding the ObsoleteAttribute as an attribute
to the method. Make sure to include an appropriate explanation:
[Obsolete("Method1 is deprecated, please use Method2 instead.")]
public void Method1()
{ … }
I think the adapter pattern could work wonders in this particular scenario. Essentially you end up creating an abstraction between OurCode and SharedCode.
This isolates access to SharedCode functions so that only the adapter can use the shared code's functions. It may end up that some of the functions in the adapter simply provide a pass through, but some of those functions will have extra logic that needs to be applied (such as in the scenario you are asking about), and having the adapter makes it easy for you to enforce that.
All client code is forced to use the adapter since they cannot directly access the shared code.
If you had access to the source code, I would recommend using the Obsolete attribute that the others have pointed out. But since you don't have access to the code base, I think it could be extremely beneficial to have a layer of abstraction between your code and the non-accessible code.
Now obviously I do not have the full scope of your scenario as to whether or not this makes sense to actually implement, so don't drive blindly, but hopefully this gives you some ideas! :)
Reference the gang of four book or see the following resources:
https://martinfowler.com/bliki/RequiredInterface.html
https://www.dofactory.com/net/adapter-design-pattern
Understanding Adapter Pattern

Adding -Ex to the name of a type in .Net

I've noticed a pattern recently in our codebase at work, where most of our model class have a name such as User, and there is an inheriting type that has extra fields on it called UserEx. I've also noticed this in the C# async CTP where they put the additional static methods for Task in a class called TaskEx (due to technical restrictions, since they couldn't alter the existing library). Talking to someone at work, I learned that -Ex classes exist to optimize network transfers (you can pull only the bare minimum if you need). My question, then, is what does -Ex stand for? The only thing I can think of is possibly "Extra".
The other answers all got it correct: the Ex suffix stands for "extended". It's a way of introducing a new class or method without obsoleting or removing the old one, a common way of retaining backwards compatibility while introducing new features.
The Windows API does this all over the place, as explained here.
Hans hints at the problem with this approach in his explanation: it doesn't scale. What if you want to extend an "extended" function? Do you call it FunctionExEx? That looks stupid.
So stupid, in fact, that Microsoft's own coding guidelines for .NET (subjective though they are) specifically recommend against appending Ex to a type. Instead, if you must do this, you should use a number:
MyType
MyType2 // modified version
MyType3 // oh wait, we had to modify it again!
Blaming this on poor planning as dowhilefor tries to do is a bit premature. When writing real world applications and frameworks, you often need to ship. That means getting out a quick-and-dirty version of the function that works. Later, you decide this is a poor design and something needs to change. Rather than throwing up your hands and completely re-writing (producing giant delays and obsoleting all of the old code), you introduce a new type with a different name. Hindsight is always 20/20.
Ending a new class or method or type in Ex is a naming convention, and like any naming convention, it is subject to the whims of those implementing it.
There are no hard and fast rules, and it is no more or less correct than appending 2 to the end of the class (or Extra, or More, or DidntWantToMessWithThePublicApi).
As for why it is used, Microsoft has a long history of using it to provide a revision to an existing API without breaking older code. You can find examples of this in classes, in methods, and in structures. You can also find different examples, which instead use 2.
It stands for "Extension" or "Extended", as far as I know. It's a common suffix to when you need to add functionnality to something that you can't change. A good example was the various -Ex functions in the Win32 APIs, which were added because C does not support function overloading.
This practice is NOT industry-standard. I'll admit I do it myself, but it's mostly vestigial emulation of some of the old win32 kernel functions. for example, they initially had a "beginthread" C function and later created another new-and-improved "begintreadEx".
I would suggest that you start using the [Deprecated] attribute to signal to other coders (or yourself) to stop using the old function in favor of the new one. That has more intrinsic meaning.
Long story short -- you should name classes & functions based on what they are or do, and try to avoid pseudo-meaningful prefixes/suffixes that create confusion such as this. That is the industry-standard approach.
I thought possibly:
external
extricated
simply 'ex' (as in 'out of' or 'beyond')
Honestly, i think it means "We didn't plan this feature long enough, didn't thought about the changed requirements, and we have to deal with this now close to the deadline". Of course this is not always the case, but everytime i find a class with Ex i try to figure out why it was introduced and not properly added into the framework. For me its mostly like // HACK:
This only counts for our code, if it is in a framework i "hope" thats just naming convention.
What it could mean was already answered, my guess was always "Extended"

ILogger _logger.Debug("Something") - Any way for the compiler to remove it?

I got a pretty common scenario, namely a self implemented ILogger interface. It contains several methods like _logger.Debug("Some stuff") and so on. The implementation is provided by a LoggingService, and used in classes the normal way.
Now I have a question regarding performance, I am writing for Windows Phone 7, and because of the limited power of these devices, little things may matter.
I do not want to:
Include a precompiler directive on each line, like #IF DEBUG
Use a condition like log4net e.g. _logger.DebugEnabled
The way I see it, in the release version, I just return NullLoggers, which contain an empty implementation of the interface, doing nothing.
The question is: Does the compiler recognize such things (may be hard, he can't know on compile time which logger I assign). Is there any way to give .NET a hint for that?
The reason for my question, I know entering an empty function will not cause a big delay, no problem there. But there are a lot of strings in the source code of my application, and if they are never used, they do not really need to be part of my application...
Or am I overthinking a tiny problem (perhaps the "string - code" ratio just looks awful in my code editor, and its no big deal anyway)..
Thanks for tips,
Chris
Use the Conditional attribute:
[Conditional("DEBUG")]
public void Debug(string message) { /* ... */ }
The compiler will remove all calls to this method for any build configurations that don't match the string in the conditional attribute. Note that this attribute is applied to the method not the call site. Also note that it is the call site instruction that is removed, not the method itself.
It is probably a very small concern to have logging code in your application that does not "run". The overhead of the "null" logger or conditionals is likely to be very small in the scheme of things. The strings will incur memory overhead which could be worrying for a constrained device, but as it is WP7 the minimum specs are not that constrained in reality.
I understand that logging code looks fugly though. :)
If you really want to strip that logging code out...
In .Net you can use the ConditionalAttribute to mark methods for conditional compilation. You could leverage this feature to ensure that all logging calls are removed from compilation for specified build configurations. As long as methods that you have decorated with the conditional attributes follows a few rules, the compiler will literally strip the call chain out.
However, if you wanted to use this approach then you would have to forgo your interface design as the conditional attribute cannot be applied to interface members, and you cannot implement interfaces with conditional members.

Why does the .Net framework guidelines recommend that you don't use ref/out arguments?

Apparently, they're "confusing". Is that seriously the reason? Can you think of any others?
Have you seen how many developers don't really understand ref/out?
I use them where they're really necessary, but not otherwise. They're usually only useful if you want to effectively return two or more values - in which case it's worth at least thinking about whether there's a way of making the method only do one thing instead. Sometimes using ref/out is the most appropriate approach - the various TryParse methods etc.
In my opinion, they are considered a code smell because in general there is a much better option: returning an object.
If you notice, in the .NET library they are only used in some special cases, namely tryparse-like scenarios where:
returning a class would mean boxing a value type
the contract of the method requires it to be fast, and so boxing/unboxing is not a viable option.
ref/out automatically means mutability, and functional programming with immutable values is all the rage these days. Try inserting a call to Dictionary.TryGetValue into a LINQ query. The API requires declaring variables and ruins any 'fluency' in the API.
That's not to say this is "the reason", but it is an example of "a reason".
(See also
http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!181.entry
for commentary on how functional languages deal with such APIs.)
Confusing is probably the best reason. Confusing means decreased maintainability and increased likelyhood on introducing subtle bugs. I see them in a similar view to the "goto" control flow statement. While it is not inherently bad on its own accord, it has lead to many many impossible to read / understand programs over the decades.
Stay away from anything that can make your code more confusing then it needs to be.
Having said that, those keywords exist probably because the framework developers saw need for such things. Use them if there is no suitable workaround, but avoid them when you can.
ref/out also don't work with "Func" delegates, so these style APIs are less composable/reusable with some other APIs that use delegates.
Just a thought, I find ref/out to be useful when the arguments capture the state of execution in target method rather than capturing returned data. Consider a scenario when you want to get an error message from a service that returns Customer object.
Customer GetCustomerById(int id, out string errorMessage);
If this method fails, you would probably return null Customer object or throw an exception. However, if I want to know the cause of error (validation? database?), I would use out argument. errorMessage argument here has nothing to do with data, simply used to capture what's wrong with the method execution.
Personally if I have a method that is expected to return two or more essential data/values, I would rethink the design of my code.
The reason I was told is the 1.0 GC had problems when ref/out was used. The GC in 2.0 (and probably not 1.1 either) doesn't have those problems so I would normally assume it is a now non-useful legacy.
#TraumaPony
It would be fine if you give us an source (URL or something) to this .NET framework guidlines.
You should be returning objects is probably the most likely reason that they suggest not using ref or out.
"ref" really only needs to be used when passing scalar values but I see people use it often for objects that are being passed by reference anyways.
Isn't code complexity reason enough? Compare:
int myValue;
ReadFromSomewhere(ref myValue);
To:
int myValue = ReadFromSomewhere();

Categories

Resources