NDepend -Finding dead methods - ndepend

I have two public methods A & B. I modified CQL to show me methods which are public and dead.
If B is only called by A and A is coming as dead method(not called or referenced anywhere in the application) can NDepend show both the methods as dead by doing some settings or by CQL?
In current scenario I am getting only A as dead method not B.

can NDepend show both the methods as dead by doing some settings or by CQL?
Yes, NDepend can do that thanks to Code Rule over LINQ Query (CQLinq) capabilities.
Around 200 default code rules are proposed, 3 of them being dedicated to unused/dead code detection:
Potentially dead Types (hence detect unused class, struct, interface, delegate...)
Potentially dead Methods (hence detect unused method, ctor, property getter/setter...)
Potentially dead Fields
If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because these rules detect not only unused types and methods, but also types and methods used only by unused dead types and methods (recursive, what you are asking for).

Related

Speed advantage of defining function bodies in classdef file?

In C++ (at least as of a decade ago), there was speed advantage in defining the body of a class method in the header file, where the class is defined. No function call overhead was suffered because, in the compilation process, the invocation of such functions was replaced by the code in the body of the function. Subsquently, all source level optimizations (and all optimizations beyond source level) could be brought to bear.
Is there an analogous advantage to putting the body of class methods in the classdef file itself rather than in a separate m-file? I'm speaking specifically about the case where one defines a #myclass/myclass.m, with method m-files in the directory #myclass. The two options I'm considering is to have the code for the body of a method mymethod put into the classdef in #myclass/myclass.m versus being in a separate file #myclass/mymethod.m.
However, an very related auxiliary question would be how those two options compare with having everything defined in a myclass.m file, with no folder #myclass.
Please note that I have previously posted this to usenet
Summarizing the comments as the answer to this question: Using an #classFolder folder containing separate method m-files is faster than having a single m file containing the entireties of the function definitions in the classdef. This is the case even though OOP in general has sped up in 2015b.
I find this a happy answer because I see great value in separating the code implementation of a class's methods from the class definition itself. That's the whole idea of separating interface from implementation. I can look at the classdef and see only a map of the class rather than have those key information elements completely dispersed by the deluge of code that accompanies implementation.
It's just too bad that this doesn't work so well for weakly typed languages. What's listed in the classdef is just member names (properties or methods) with no specification of what class they are. So not as much information as in a strongly typed language. In fact, very little info about what the class, its properties, and its methods really are. Furthermore, there is nothing to ensure that the actual method implementation even complies with the argument list in the classdef. These kind of details helped prevent development errors in a strongly typed language, especially when one's body of classes get large.

In GWT, why shouldn't a method return an interface?

In this video from Google IO 2009, the presenter very quickly says that signatures of methods should return concrete types instead of interfaces.
From what I heard in the video, this has something to do with the GWT Java-to-Javascript compiler.
What's the reason behind this choice ?
What does the interface in the method signature do to the compiler ?
What methods can return interfaces instead of concrete types, and which are better off returning concrete instances ?
This has to do with the gwt-compiler, as you say correctly. EDIT: However, as Daniel noted in a comment below, this does not apply to the gwt-compiler in general but only when using GWT-RPC.
If you declare List instead of ArrayList as the return type, the gwt-compiler will include the complete List-hierarchy (i.e. all types implementing List) in your compiled code. If you use ArrayList, the compiler will only need to include the ArrayList hierarchy (i.e. all types implementing ArrayList -- which usually is just ArrayList itself). Using an interface instead of a concrete class you will pay a penalty in terms of compile time and in the size of your generated code (and thus the amount of code each user has to download when running your app).
You were also asking for the reason: If you use the interface (instead of a concrete class) the compiler does not know at compile time which implementations of these interfaces are going to be used. Thus, it includes all possible implementations.
Regarding your last question: all methods CAN be declared to return interface (that is what you ment, right?). However, the above penalty applies.
And by the way: As I understand it, this problem is not restricted to methods. It applies to all type declarations: variables, parameters. Whenever you use an interface to declare something, the compiler will include the complete hierarchy of sub-interfaces and implementing classes. (So obviously if you declare your own interface with only one or two implementing classes then you are not incurring a big penalty. That is how I use interfaces in GWT.)
In short: use concrete classes whenever possible.
(Small suggestion: it would help if you gave the time stamp when you refer to a video.)
This and other performance tips were presented at Google IO 2011 - High-performance GWT.
At about the 7 min point the speak addresses 'RPC Type Explosion':
For some reason I thought the GWT compiler would optimize it away again but it appears I was mistaken.

Should naming of methods within interfaces be concrete or abstract?

Often when I create new classes, I first create a new interface. I name the methods of my interface exactly as I would like them to behave. A colleague of mine prefers to have these method names being more abstract, ie: areConditionsMet(). The reason, he wants to hide the 'implementation details'.
IMO implementation details are different from the expected behavior. Could anyone perhaps give more insight. My goal is to reach a common ground with my colleague.
Your method names should describe what the method does, but not how it does it. The example you gave is a pretty poor method name, but it's better than isXGreatherThan1AndLessThan6(). Without knowing the details about what it should do, I would say that it should be specific to the problem at hand, but general enough that the implementation could change without affecting the name itself, i.e., you don't want the name of the method to be brittle. An example might be isTemperatureWithinRange() - that describes what I'm checking but doesn't describe how it's accomplished. The user of the method should be confident that the output will reflect whether the temperature is within a certain range -- whether this is supplied as an argument or defined by the contract of the class, is immaterial.
Interfaces should represent some behavior or capability and not the way it is to be accomplished. Users of interfaces should not be interested in the way a target is achieved, they just want to know its done.
Implementation issues should not be included within the name of methods for that exact reason. The name of the table updated as a result of this method or the technology used has nothing to do in your domain object's method's name.
However from your question it is hard to say what is the exact case at hand.
If you could provide more details perhaps i could provide an additional help.
The names of your interface methods should leave the user of the interface in no doubt about what the method proposes to do from a functional perspective. If the implementation matches that, well and good.
Based on your updated comments:
Sounds to me like you need two methods: isModified() and hasProperties(). Leave it up to the user (or higher layer) of the domain object to determine if a particular criteria is fulfilled.
An interface should also be designed with the view that after it is released it will never be changed. By saying isDomainObjectModifiedAndHasProperties() you are setting in concrete that this is the criteria of fullfilment (regardless of any future unforseen implementation).

Are static inner classes a good idea or poor design?

I'm find I have several places that having public static inner classes designed that extend "helper" classes makes my code a lot more type safe and, in my opinion, readable. For example, imagine I have a "SearchCriteria" class. There are a lot of commonalities for the different things I search for (a search term and then a group of search term types, a date range, etc.) By extending it in a static inner class, I tightly couple the extension and the searchable class with the specific differences. This seems like a bad idea in theory (Tight Coupling Bad!) but the extension is specific to this searchable class (One Class, One Purpose).
My question is, in your experience, has the use of static inner classes (or whatever your language equivelent is) made your code more readable/maintainable or has this ended up biting you in the EOF?
Also, I'm not sure if this is community wiki material or not.
Sounds perfectly reasonable to me. By making it an inner class, you're making it easy to find and an obvious candidate for review when the searchable class changes.
Tight coupling is only bad when you couple things that don't really belong together just because one of them happens to call the other one. For classes that collaborate closely, e.g. when, as in your case, one of them exists to support the other, then it's called "cohesion", and it's a good thing.
Note that the class is not the unit of reuse. Therefore, some coupling between classes is normal and expected. The unit of reuse is usually a collection of related classes.
In Python, we have a variety of structures.
Packages. They contain modules. These are essentially directories with a little bit of Python machinery thrown in.
Modules. They contain classes (and functions). These are files; and can contain any number of closely-related classes. Often, the "inner class" business is handled at this level.
Classes. These can contain inner class definitions as well as method functions. Sometimes (not very often) inner classes may actually be used. This is rare, since the module-level coupling among classes is usually perfectly clear.
The only caveat with using inner classes is making sure you're not repeating yourself all over the place - as in - make sure, when you define an inner class, you're not going to need to use that functionality anywhere else, and, that that functionality is necessarily coupled with the outer class. You don't want to end up with a whole bunch of inner classes that all implement the exact same setOrderyByNameDesc() method.
The point in "loose coupling" is to keep the two classes separate so that if there are code changes in your "SearchCriteria" class nothing would have to be change in the other classes. I think that the static inner classes you are talking about could potentially make maintaining code a nightmare. One change in SearchCriteria could send you searching through all of the static classes to figure out which ones are now broken because of the update. Personally, I would stay away from any such inner classes unless it is really needed for some reason.

Encapsulation in the age of frameworks

At my old C++ job, we always took great care in encapsulating member variables, and only exposing them as properties when absolutely necessary. We'd have really specific constructors that made sure you fully constructed the object before using it.
These days, with ORM frameworks, dependency-injection, serialization, etc., it seems like you're better off just relying on the default constructor and exposing everything about your class in properties, so that you can inject things, or build and populate objects more dynamically.
In C#, it's been taken one step further with Object initializers, which give you the ability to basically define your own constructor. (I know object initializers are not really custom constructors, but I hope you get my point.)
Are there any general concerns with this direction? It seems like encapsulation is starting to become less important in favor of convenience.
EDIT: I know you can still carefully encapsulate members, but I just feel like when you're trying to crank out some classes, you either have to sit and carefully think about how to encapsulate each member, or just expose it as a property, and worry about how it is initialized later. It just seems like the easiest approach these days is to expose things as properties, and not be so careful. Maybe I'm just flat wrong, but that's just been my experience, espeically with the new C# language features.
I disagree with your conclusion. There are many good ways of encapsulating in c# with all the above mentioned technologies, as to maintain good software coding practices. I would also say that it depends on whose technology demo you're looking at, but in the end it comes down to reducing the state-space of your objects so that you can make sure they hold their invariants at all times.
Take object relational frameworks; most of them allow you to specify how they are going to hydrate the entities; NHibernate for example allows you so say access="property" or access="field.camelcase" and similar. This allows you to encapsulate your properties.
Dependency injection works on the other types you have, mostly those which are not entities, even though you can combine AOP+ORM+IOC in some very nice ways to improve the state of these things. IoC is often used from layers above your domain entities if you're building a data-driven application, which I guess you are, since you're talking about ORMs.
They ("they" being application and domain services and other intrinsic classes to the program) expose their dependencies but in fact can be encapsulated and tested in even better isolation than previously since the paradigms of design-by-contract/design-by-interface which you often use when mocking dependencies in mock-based testing (in conjunction with IoC), will move you towards class-as-component "semantics". I mean: every class, when built using the above, will be better encapsulated.
Updated for urig: This holds true for both exposing concrete dependencies and exposing interfaces. First about interfaces: What I was hinting at above was that services and other applications classes which have dependencies, can with OOP depend on contracts/interfaces rather than specific implementations. In C/C++ and older languages there wasn't the interface and abstract classes can only go so far. Interfaces allow you to tie different runtime instances to the same interface without having to worry about leaking internal state which is what you're trying to get away from when abstracting and encapsulating. With abstract classes you can still provide a class implementation, just that you can't instantiate it, but inheritors still need to know about the invariants in your implementation and that can mess up state.
Secondly, about concrete classes as properties: you have to be wary about what types of types ;) you expose as properties. Say you have a List in your instance; then don't expose IList as the property; this will probably leak and you can't guarantee that consumers of the interface don't add things or remove things which you depend on; instead expose something like IEnumerable and return a copy of the List, or even better, do it as a method:
public IEnumerable MyCollection { get { return _List.Enum(); } } and you can be 100% certain to get both the performance and the encapsulation. Noone can add or remove to that IEnumerable and you still don't have to perform a costly array copy. The corresponding helper method:
static class Ext {
public static IEnumerable<T> Enum<T>(this IEnumerable<T> inner) {
foreach (var item in inner) yield return item;
}
}
So while you can't get 100% encapsulation in say creating overloaded equals operators/method you can get close with your public interfaces.
You can also use the new features of .Net 4.0 built on Spec# to verify the contracts I talked about above.
Serialization will always be there and has been for a long time. Previously, before the internet-area it was used for saving your object graph to disk for later retrieval, now it's used in web services, in copy-semantics and when passing data to e.g. a browser. This doesn't necessarily break encapsulation if you put a few [NonSerialized] attributes or the equivalents on the correct fields.
Object initializers aren't the same as constructors, they are just a way of collapsing a few lines of code. Values/instances in the {} will not be assigned until all of your constructors have run, so in principle it's just the same as not using object initializers.
I guess, what you have to watch out for is deviating from the good principles you've learnt from your previous job and make sure you are keeping your domain objects filled with business logic encapsulated behind good interfaces and ditto for your service-layer.
Private members are still incredibly important. Controlling access to internal object data is always good, and shouldn't be ignored.
Many times private methods I've found to be overkill. Most of the time, if the work you're doing is important enough to break out, you can refactor it in such a way that either a) the private method is trivial, or b) is an integral part of other functions.
In addition, with unit testing, having many methods private makes it very hard to unit test. There are ways around that (making test objects friends, etc), but add difficulties.
I wouldn't discount private methods entirely though. Any time there's important, internal algorithms that really make no sense outside of the class there's no reason to expose those methods.
I think that encapsulation is still important, it helps more in libraries than anything imho. You can create a library that does X, but you don't need everyone to know how X was created. And if you wanted to create it more specifically to obfuscate the way you create X. The way I learned about encapsulation, I remember also that you should always define your variables as private to protect them from a data attack. To protect against a hacker breaking your code and accessing variables that they are not supposed to use.