Why does NDepend count Static fields as LOC for a method - ndepend

I have a type to define and assign some static readonly fields.
I got a violation for Methods too big (LOC)
I would like to know if I have an attribute for method, and used it in the rule (see below). Where is in my source code I need to use this attribute to discard "this and which" method?
Example code:
Sample rule:

Why does NDepend count Static fields as LOC for a method
It is because when you do a static field inline initialization, it adds a line of code to the class constructor. Actually, as soon as you have one static field inline initialization in a class, the C# compiler creates a static constructor for your class. So if you have N static field inline initialization, you have a method (the class constructor) that has N Lines of Code.
The large method that NDepend reports here is named BassAttributeNames..cctor(). Certainly the easiest way to adapt your code rule to avoid such match is to add the clause:
&& !m.IsClassContructor

Related

What are some use cases for static methods and properties in classes?

PowerShell classes can contain static methods and properties:
class stack {
[string]
$name
[DateTime]
static $date = (GET-DATE)
stack($name) {
$this.name = $name
}
static [void] hello() {
Write-Host 'hello'
}
}
A couple use cases I've found so far for static methods:
organize my functions within a common context of a class.
I believe I have read somewhere that static methods are much more performant than functions. I've never verified it myself, though.
And for static properties:
They define variables that can be called from any scope, especially from within other classes without needing to pass the variable into the class as an argument.
I have the feeling that my reasons for using static methods / properties are pretty underdeveloped. Static properties in particular seem like more laborious alternatives to simple variables, although the omni-scope availability is very nice if you do run into that use case.
So my questions:
What use cases have you found for static methods/properties?
Does it ever make sense to set a static property without a default value?
Since PowerShell was given, I will give a .NET-centric answer.
Ultimately the details will vary from language to language, but static class instances are typically instantiated only once the first time a static member is called on it. This means you will have a single instance created for any code which needs to call it. Conversely, being able to call the constructor of a non-static class means you can create as many instances as times you can call the constructor. For classes with both static and non-static members, the static members are still only created a single time in memory for the static instance.
Create static methods if the method does not rely on instance data to get the job done. For example, a string class might include static utility methods that still require a source string to be passed in. Let's look at the signature of the built-in String.IsNullOrEmpty static method:
[string]::IsNullOrEmpty
# OverloadDefinitions
# -------------------
# static bool IsNullOrEmpty(string value)
IsNullOrEmpty makes sense to define as static because it does not make sense to have it operate on an instantiated string object instead. Think about what the method does. It checks for:
A null value; or
A value of [string]::Empty
It is a utility method in order check the conditions above against another string. If this were not a static method, we cannot check for a null string as the instance doesn't exist(you can't call a method on a null-valued expression). Even if we could have a null string and call the method, we would first need to create a string object to use it, which would allocate memory for IsNullOrEmpty for every single string object. None of this is efficient considering it's a utility method that can easily have a valid string passed into it.
The main benefit here is that you do not need to allocate memory for every static method for every string object created. As explained above, the static methods are instantiated only once for the static instance.
The same goes for properties, although oftentimes static properties are read only. One example might be a System Properties class, and the OS version may be a static string. Consider the static property I used above, [string]::Empty. If this were not a static property, we run into the same pitfalls as defining IsNullOrEmpty as a non-static member: it will get allocated more often than it needs to be, and we need to first create a non-null instance to use it. The latter occurs with static classes behind the scenes, so you are free to use static members without worrying about initialization or instantiation.
Note: Create a static class if all the members are planned to be static, as it does not make sense to create an instance when it would hold no stateful information. Static classes in .NET are classes that cannot be directly instantiated, except for a single static constructor.
To summarize, it's mostly about memory management. Static members are only created once during the lifetime of the program, while instance (non-static) members are created for each instance of the object created with new.

Modern equivalent of the superiorto() function

I'm working on rewriting an old MATLAB package. As part of that rewrite I'm updating two classes (lets call them old_class1 and old_class2) defined using the class() function to classes defined with classdef.
The definition of old_class1 contains the line superiorto('old_class2'). This function is not allowed in a constructor defined with classdef, but I am unable to find any equivalent. How do I create functionality equivalent to superiorto() in a class defined with classdef?
superiorto is no longer available in MATLAB, but I was able to find a copy of old documentation that indicates it was used to determine which object's method was called when multiple different classes were given as function arguments. For example, given obj1=class1() and obj2=class2(), with the class1 constructor containing superiorto('class2'), would cause function(obj1,obj2) to callclass1.function, rather thanclass2.function`.
With modern classdef functionality, the same can be accomplished by setting the InferiorClasses property:
classdef (InferiorClasses = {?class2}) class1

ABAP CALL METHOD: meaning of 'static' and 'dynamic'

I'm a little confused about the meaning of terms 'static' and 'dynamic' w.r.t. CALL METHOD in ABAP.
On the one hand, static refers to components of a class that can be accessed without instance. Dynamic refers to access via the content of a field at runtime.
So, (class)=>(meth) would be a dynamic call to a static method?!
What are the inverse terms then?
one meaning of dynamic is: (meth_name) meth_name expects a character-like field that must contain the name of a method when the statement is executed. Consequently, oref->meth is a static method call
A static component comp of a class can be accessed using the name class=>comp. Here, a component can be a method
Static have two meanings:
The methods (and attributes) of a class are either static or instance. In the latter case an instance of the class has to exist, to be able to call an instance method or access and instance attribute of the class. The syntax is different:
call an instance method: oref->method
call a static method: class=>method
Similarly for attributes:
static: class=>attribute
instance: oref->attribute
On the other hand the call of the method can be either static or dynamic.
Static call of a method:
oref->method (1) (or class=>method (2) )
Dynamic call of a method: oref->(method) (3) (or class=>(method) (4) )
To be exact:
(1) Static call of an instance method
(2) Static call of a static method
(3) Dynamic call of an instace method
(4) Dynamic call of a static method

What design pattern provides a static method to produce a class instance

I am trying to understand what design pattern I am stumbling towards... please bear with me the language I am using is Matlab and the OO is a bit weak in some areas, and I am relatively inexperienced in implementing design patterns.
I have a ComplexObject in which the constructor was becoming overly complicated. To begin with my constructor allowed 0, 1 or 2 arguments, that is an "empty" ComplexObject, a ComplexObject built from a ModelObject, or a ComplexObject built from ModelObject+ConfigObject. (The ModelObject and ConfigObject are basic file parsers).
I can't overload constructors in Matlab, so I essentially switch'ed on the class type of the input arguments to the constructor, after I while I changed some of this to static methods so that the constructor was just an empty class initializer, and static ComplexObject.createFromModel and ComplexObject.createFromModelAndConfig classes produced ComplexObjects.
I then decided that my ComplexObject code was being dominated by all this construction stuff and the business logic wasnt clear, so I wrote a ComplexObjectFactory class and basically moved the static methods into that class. Now since the static methods are in fact calling more private (static!?) methods to build the ComplexObject I have run into some confusion about calling conventions of these private static methods :(
Finally, I am now trying to add some code to write part of ComplexObject back to disk. Interestingly this is actually the same disk file that is used to build a ConfigObject... so I want something like ComplexObject.writeConfigFile... or should that be ComplexObjectFactory.writeConfigFile(myComplexObject). To further complicate things I want multiple types of "config" file formats down the track.
My current classes look something like:
classdef ComplexObjectFactory
methods (Static)
function product = createFromModel(modelObj)
product = ComplexObject()
ComplexObjectFactory.helper1(product)
end
function product = createFromModelAndConfig(modelObj, configObj)
product = ComplexObjectFactory.createFromModel(modelObj)
ComplexObjectFactory.helper2(product, configObj)
end
end
methods (Private, Static)
function helper1(product)
function helper2(product)
end
end
classdef ComplexObject
methods
function self = ComplexObject(varargin)
<init>
end
end
end
classdef ComplexObject
Not sure I completely understand your question, tell me if I'm off topic here.
Just like you wrote, design pattern that creates objects is called factory. Other functionality that you mentioned, like writing to disk should be the responsibility of the object itself.

Help with the Moles syntax for testing private method with generics

I've got a signature for a method that looks like this:
private IEnumerable BuildCustomerUpdatePlan(List localCacheChangedCustomers, List crmChangedCustomers){}
When I look at the moled object, the syntax (IntelliSense) of how to call the method and test itis absolutely confusing to me and every time I give it a shot, I get compilation errors. I've looked through the basic tutorials provided on MSFT's site, but I simply don't get how to test a private method using Moles or how to deal with the return type and multiple parameters.
Unfortuantely I've been unable to find other good HOWTO's or threads demonstrating a more complex sample than just working with a simple Add() method that spits out an INT and accepts an INT. :(
Tips?
In your testing project, first make sure you add a Moles assembly corresponding to the assembly-under-test. You'll also want to add an using statement of the assembly-under-test with .Moles appended so you can use the moled assembly.
Moles changes the names of the classes and methods to the form M[Original Class Name].[Original Method Name][typeof param1][typeof param2].... In your case a detour for that method could look like MClass.BuildCustomerUpdatePlanListList = (List x, List y) => { [code]};. That defines an anonymous method that takes two Lists as parameters and you'd put whatever code wanted in the function. Just make sure that you return an IEnumerable in that anonymous method.
Here's an example using Moles to detour Directory.GetFiles:
using System.IO.Moles;
[assembly: MoledType(typeof(System.IO.Directory))]
...
MDirectory.GetFilesStringString = (string x, string y) => new string[0];
Since the Directory class is a member of System.IO I use using System.IO.Moles; to specify that I want to use moled members of the assembly.
Moles requires you to specify the types Moled: [assembly: MoledType(typeof(System.IO.Directory))] does the job.
Finally, Directory.GetFiles takes two strings as parameters and returns a string array. To detour the method into returning the equivalent of no files found, the moled method just returns new string[0]. Curly braces are needed if you want multiple lines in the anonymous method and, if not detouring a void method, a return statement that matches the type the original method would return.