Naming conventions and grammar - naming-conventions

I'm curious to know about rules for grammar-related/english-related naming properties (not about capitalization etc).
What is recomended way to name class property (for public API): DateEnd or EndDate?
DateEnd approach allows to find more easily and group related properties (intellisense & docs):
DateStart, DateEnd ...
But we don't use names like IdTask, TypeProperty. We use TaskId and PropertyType. And the last ones are more grammatically correct.
So why googling shows that both ways used ~ 50/50? microsoft use both in public APIs.

Following convention, and often grammar, is useful in making an API intuitive and memorable.
As you suggest, TaskId is more common than IdTask, so should be preferred.
Grouping related properties is a useful bonus if it doesn't make the property name too obscure.
Using the Exchange Web Services Task element as an example, reminder properties are grouped as they start with "Reminder", for example
ReminderDueBy
ReminderIsSet
In isolation, "HasReminder" might be used, but this can be changed to "ReminderIsSet" to allow grouping, without sacrificing grammar or readability.
Interestingly, this Microsoft example is inconsistent in that most dates are named for example "StartDate", "DueDate", but others don't follow the convention, for example "DateTimeSent" and "DateTimeCreated".

Related

Method and parameter naming conforming to Swift API Design Guideline

It's not obvious to me from reading the current API design guideline, which of the following version is better.
class MediaLoader {}
class MediaRequest {}
let mediaLoader = MediaLoader()
let mediaRequest = MediaRequest()
// Option 1
mediaLoader.add(request: mediaRequest)
// Option 2
mediaLoader.add(mediaRequest: mediaRequest)
// Option 3
mediaLoader.addRequest(mediaRequest)
// Option 4
mediaLoader.add(mediaRequest)
Which of the above conforms to the current API design guideline the best?
The answer really depends on the purpose and semantics of MediaLoader. If MediaLoader is only a collection of mediaRequests, then .add(mediaRequest) is the way to go because it would flow grammatically and be meaningful in context.
On the other hand, if a mediaRequest is merely one of many different things contributing to its purpose, then .add() alone would not convey enough context to properly read the statement. For example, if you could also add display channels or filters, then merely saying .add(something) would not be clear enough. This is when you would use an extended name that describes the relationship. e.g. .addRequest(), addChannel(), addFilter().
But not .add(request:...), because, using a name for the first parameter is not the ideal way to distinguish between relationships. It should be used instead to clarify the method by which the addition will be performed or the way the request will be accessed. This will leave the "nameless" variant for the most frequent and straightforward use case. e.g. .add(fromTemplate:webRequesTemplate) or .addRequest(fromTemplate:webTemplate).

NHibernate Criteria Restriction vs Expression

If I search for NHibernate Criteria API query examples in internet there are examples that use Restrictions and others use Expression. What are the differences between those two?
For example:
posts = session.CreateCriteria<Post>()
.Add(Expression.Eq("Id", 1))
.List<Post>();
posts = session.CreateCriteria<Post>()
.Add(Restrictions.Eq("Id", 1))
.List<Post>();
I think Restrictions were released in NH2 and is now the favoured way.
According to Resharper whenever I use Expression I get a hint to say Access to a static member of a type via a derived type
Also according to this post by Ayende:-
Prefer to use the Restrictions instead
of the Expression class for defining
Criteria queries.
In the source code for namespace NHibernate.Criterion.Expression is says that "This class is semi-deprecated use Restrictions"
Expression inherits from Restrictions but it is recommended to use Restrictions. Expression is apparently deprecated.
According to Ayende (old post about NH 2.0), documentation will usually refer to Restrictions.

What is the antonym of encapsulation?

Using online dictionary tools doesn't really help. I think the way encapsulate is use in computer science doesn't exactly match its meaning in plain English.
What is the antonym of computer science's version of encaspulate? More specifically, what is an antonym for encapsulate that would work as a function name.
Why should I care? Here's my motivation:
// A class with a private member variable;
class Private
{
public:
// Test will be able to access Private's private members;
class Test;
private:
int i;
}
// Make Test exactly like Private
class Private::Test : public Private
{
public:
// Make Private's copy of i available publicly in Test
using Private::i;
};
// A convenience function to quickly break encapsulation on a class to be tested.
// I don't have good name for what it does
Private::Test& foo( Private& p )
{ return *reinterpret_cast<Private::Test*>(&p); } // power cast
void unit_test()
{
Private p;
// using the function quickly grab access to p's internals.
// obviously it would be evil to use this anywhere except in unit tests.
assert( foo(p).i == 42 );
}
The antonym is "C".
Ok, just kidding. (Sort of.)
The best terms I can come up with are "expose" and "violate".
The purpose behind encapsulation is to hide/cover/protect. The antonym would be reveal/expose/make public.
How about Decapsulation..
Though it aint a computer science term, but in medical science, Surgical removal of a capsule or enveloping membrane.. Check out here..
"Removing/Breaking encapsulation" is about the closest thing I've seen, honestly.
If you think of the word in the English sense, to encapsulate means to enclose within something. But in the CS sense, there's this concept of protection levels and it looks like you want to imply circumventing the access levels as well, so something like "extraction" doesn't really convey the meaning you're looking for.
But if you just think of it in terms of what the access levels are, it looks like you're making something public so, how about "publicizing"?
This is not such a simple question - Scott Meyers had an interesting article to demonstrate some of the nuances around encapsulation here.
I'll start with the punchline: If
you're writing a function that can be
implemented as either a member or as a
non-friend non-member, you should
prefer to implement it as a non-member
function. That decision increases
class encapsulation. When you think
encapsulation, you should think
non-member functions.
How about "Bad Idea"?
The true antonym of "Encapsulation" is "Global State".
The general opposite of encapsulation is coupling and we often talk about systems that are tightly coupled or loosely coupled.
The reason you'd want components to be encapsulated is because it makes it easier to reason about how they work.
Take the analogy of trains: the consequence of coupling the railcars is that the driver must consider the characteristics (inertia, length) of the entire train.
Obviously, though, we couple systems because we need them to work together.
Inverted encapsulation and data structures
There's another term that I've been digging for, which is how I came across this question, that refers to a non-standard style of data structures.
The standard style of encapsulation is exemplified by Java's LinkedList; the actual nodes of the list are designed to be inaccessible to the consumer. The theory is that this is an implementation detail and can change to improve performance, while existing code will continue to run.
Another style is the classic functional cons-list. This is a singly linked list, and the idea is that it's so simple that there's nothing to improve about the data structure, e.g.
data [a] = [] | a : [a] deriving (Eq, Ord)
-- Haskellers then work directly with the list
-- There's nothing to hide because it's so simple
typicalHaskell :: [a] -> b
typicalHaskell [] = emptyValue
typicalHaskell h : t = h `doAThing` (typicalHaskell t)
That's the definition from Haskell's standard prelude though the report notes that isn't valid Haskell syntax, and in practice [a] is defined in the guts of the compiler.
Then there's what I'm calling an "inverted" data structure, but I'm still looking for the correct term. This is, I think, really the opposite of encapsulation.
A good example of this is Python's heapq module. The data structure here is a binary heap, but there isn't a Heap class. Rather, you get a collection of functions that operate on generic Python lists and you're responsible for using those methods correctly to ensure the heap invariants are maintained.
How about "spaghetti"?

How do you name member variables in VB.NET?

I am generally not one to engage in subjective arguments over matters like variable naming, code formatting, etc. So I have no intention of starting an argument here.
I just came across this (old) blog post which recommends not prefixing member variable names:
Do not use a prefix for member
variables (_, m_, s_, etc.). If you
want to distinguish between local and
member variables you should use
"this." in C# and "Me." in VB.NET.
For C#, yeah, I get it: member variables can be lower camelCase, and public properties/methods can be PascalCase. But VB.NET is case-insensitive, so you can't really give a private member the same name as a public property except with a lower case first letter.
I've generally prefixed member variables with an underscore, but I've been told that's not idiomatic.
So really I'm just curious: how do you name your member variables in VB.NET? And is there a "standard" way?
I'm not asking because I believe there's a "right" way or because I particularly want to change my style, and certainly not because I have any desire to tell others they're "wrong." Like I said, I'm just curious.
It's personal preference, although there's widespread support for having some distinction. Even in C# I don't think there's one widely used convention.
Jeff Prosise says
As a matter of personal preference I typically prefix private fields with an underscore [in C#] ... This convention is used quite a lot in the .NET framework but it is not used throughout.
From the .NET Framework Design Guidelines 2nd Edition page 73.
Jeffrey Richter says
I make all my fields private and I prefix my instance fields with "m_" and my static fields with "s_" [in C#]
From the .NET Framework Design Guidelines 2nd Edition page 47. Anthony Moore (BCL team) also thinks using "m_" and "s_" is worth consideration, page 48.
I personally use m_ for member variables.
Although with automatic properties in VS 2010 I haven't needed to for any new code I've written recently.
I don’t like starting a line/name with an underscore since that always looks as if the line were indented by an additional space: it just makes the code unbalanced. Additionally, a lonely underscore is too inconspicuous for my taste: I prefer the identifiers to be clearly distinct.
Therefore, I periodically cycle between suffix underscore (e.g. example_) and prefix m_. I can’t decide which of those I prefer since I actually like neither. But the argument against prefix underscores partially also applies to suffix underscores.
But as you’ve remarked, some kind of distinction is necessary.
And as I’ve remarked elsewhere, I’ve had very bad experiences with case-only distinction in C# as well – it’s just too easy to confuse the names, and hence write into a private variable instead of the property. This matters if the property either checks or transforms the set value.
For that reason, I prefer to use some kind of prefix in C# as well.
I'm doing it like you.
Private _myVar as Object
Public Property MyVar() As Object
Get
Return Me._myVar
End Get
Set(ByVal value As Object)
Me._myVar = value
End Set
End Property
And in constructor
Public Sub New(myVar as object)
Me._myVar = myVar
End Sub
But I think that's a matter of taste.
The only time I use a prefix is with the private backing store for a public property. In these cases, the names are otherwise identical and most of the time the only place I'll ever reference the prefixed name is inside it's associated property. When I can finally use auto-implemented properties with VB.Net I won't even need to do that.
I do this in C# as well, on those instances when I can't just use an auto-implemented property. Better the _ prefix than varying the names only by case.
We use _ (underscore) to prefix our variables names. It's short and to the point...
Private _ID as integer
Public Property ID() As Integer
Get
Return _ID
End Get
Set(ByVal value As Integer)
_ID = value
End Set
End Property
Although a lot of the MS code seems to use m_* for private declarations, I save myself a character and just use _name for private members. My rules:
Private members are preceeded by an underscore
Public members (methods and properties) are PascalCase.
Parameters are camelCase.
Since I work in C#, having a parameter name with the same name as a property with different case is no problem. That won't work in VB, though.

"Is a" vs "Has a" : which one is better?

Portfolio A → Fund 1
Portfolio A → Fund 2
Portfolio A → Fund 3
I couldn't frame my sentence without not using is/has. But between 1 & 2,
1) has a:
class PortfolioA
{
List<Fund> obj;
}
2) is a:
class PortfolioA : List<Fund>
{
}
which one do you think is better from the point of extensibility, usability? I can still access my funds either way, albeit with a small syntactical change.
I vote with the other folks who say HAS-A is better in this case. You ask in a comment:
when I say that a Portfolio is just a
collection of funds, with a few
attributes of its own like
TotalPortfolio etc, does that
fundamentally not become an "is-a"?
I don't think so. If you say Portfolio IS-A List<Fund>, what about other properties of the Portfolio? Of course you can add properties to this class, but is it accurate to model those properties as properties of the List? Because that's basically what you're doing.
Also what if a Portfolio is required to support more than one List<Fund>? For instance, you might have one List that shows the current balance of investments, but another List that shows how new contributions are invested. And what about when funds are discontinued, and a new set of funds is used to succeed them? Historical information is useful to track, as well as the current fund allocation.
The point is that all these properties are not correctly properties of a List, though they may be properties of the Portfolio.
do not 'always' favor composition or inheritance or vice-versa; they have different semantics (meanings); look carefully at the meanings, then decide - it doesn't matter if one is 'easier' than the other, for longevity it matters that you get the semantics right
remember: is-a = type, has-a = containment
so in this case, a portfolio logically is a collection of funds; a portfolio itself is not a type of fund, so composition is the correct relationship
EDIT: I misread the question originally, but the answer is still the same. A Portfolio is not a type of list, it is a distinct entity with its own properties. For example, a portfolio is an aggregate of financial instruments with an initial investment cost, a total current value, a history of values over time, etc., while a List is a simple collection of objects. A portfolio is a 'type of list' only in the most abstract sense.
EDIT 2: think about the definition of portfolio - it is, without exception, characterized as a collection of things. An artist's portfolio is a collection of their artwork, a web designer's portfolio is a collection of their web sites, an investor's portfolio consists of all of the financial instruments that they own, and so on. So clearly we need a list (or some kind) to represent a portfolio, but that in no way implies that a portfolio is a type of list!
suppose we decide to let Portfolio inherit from List. This works until we add a Stock or Bond or Precious Metal to the Portfolio, and then suddenly the incorrect inheritance no longer works. Or suppose we are asked to model, say, Bill Gates' portfolio, and find that List will run out of memory ;-) More realistically, after future refactoring we will probably find that we should inherit from a base class like Asset, but if we've already inherited from List then we can't.
Summary: distinguish between the data structures we choose to represent a concept, and the semantics (type hierarchy) of the concept itself.
The first one, because you should try to favour composition over inheritance when you can.
It depends whether the business defines a Portfolio as a group (and only a group) of funds. If there is even the remote possibility of that it could contain other objects, say "property", then go with option 1. Go with option 2 if there is a strong link between a group of funds and the concept of Portfolio.
As far as extensibility and usefullness 1 has the slight advantage over 2. I really disagree with the concept that you should always favour one over the other. It really depends on what the actual real life concepts are. Remember, you can always^ refactor.
^ For most instances of always. If it is exposed publicly, then obviously not.
I would go with option (1) - composition, since you may eventually have attributes specific to the portfolio, rather than the funds.
The first one, because it is "consists of". => Composition
I will differ with what appears to be the common opinion. In this case I think a portfolio is very little more than a collection of funds... By using inheritance you allow the use of multiple constructors, as in
public Portfolio(CLient client) {};
public Portfolio(Branch branch, bool Active, decimal valueThreshold)
{
// code to populate collection with all active portfolios at the specified branch whose total vlaue exceeds specified threshold
}
and indexers as in:
public Fund this[int fundId] { get { return this.fundList[fundId]; } }
etc. etc.
if you want to be able to treat variables of type Portfolio as a collection of funds, with the associated syntax, then this is the better approach.
Portfolio BobsPortfolio = new Portfolio(Bob);
foreach (Fund fund in BobsPortfolio)
{
fund.SendStatement();
}
or stuff like that
IS-A relation ship represents inheritances and HAS-A relation ship represents composition. For above mentioned scenario we prefer composition as PortfolioA has a List and it is not the List type. Inheritances use when Portfolio A is a type of List but here it is not. Hence for this scenario we should prefer Composition.