What's the benefit of postfixing arrays with "List" for variables? - naming-conventions

I have seen numerous developers postfixing variable names with a "List" when it's an array. What's the point of this and would you encourage this style? For example:
// Java
String[] fileList;
String file;
// PHP
$fileList = array();
$file = '';
The idea applies to any language with support for arrays.

The idea? Readability - you can tell the variable is a collection in one glance. This can be achieved with pluralizing the variable name (ie. files).
If the fact that the data type is a list is significant (assuming several different collection types), then using that postfix is the right thing to do (as opposed to simply being a collection).
I personally tend to pluralize variable names, using a list postfix only if it adds information or can't be inferred from the name otherwise (say a list of lists).

I think this is mostly a matter of taste. I tend to name things to reflect what they are or what they do. So if I have a collection or array of File instances, the variable would most probably named files, or have a more specific name if the context allows it. Naming an array of Files fileList is in my humble opinion plain wrong, because, at least in Java, an array is not a List. But then, the compiler won't complain...
More complex collections like a Map get names like keyToValue. So if I had a map which assigns teachers to classrooms this would be called teacherToRoom in my code. I hate grepping through the code to find out what the variables are meant to do, so I try to be as specific as needed with the names.
In conclusion it's all about correct code, and variable names can not influence this outcome from the compiler perspective. But they can very well affect the outcome when it comes to humans working with the code, so it's best to do whatever works for the majority of people working on a codebase.

Related

Design patterns on initializing an object?

What's the recommended way to handle an object that may not be fully initialized?
e.g. taking the following code (off the top of my head in ruby):
class News
attr_accessor :number
def initialize(site)
#site = site
end
def setup(number)
#number = number
end
def list
puts news_items(#site, #number)
end
end
Clearly if I do something like:
news = News.new("siteA")
news.list
I'm going to run into problems. I'd need to do news.setup(3) before news.list.
But, are there any design patterns around this that I should be aware of?
Should I be creating default values? Or using fixed numbers of arguments to ensure objects are correctly initialized?
Or am I simply worrying too much about the small stuff here.
Should I be creating default values?
Does it make sense to set a default? If so this is a perfectly valid approach IMHO
Or using fixed numbers of arguments to ensure objects are correctly initialized?
You should ensure that your objects cannot be constructed in an invalid state, this will make your's and other users of your code much simpler.
in your example not initializing number in some way is a problem, and this method is an example of temporal coupling. You should avoid this, and the two ways you suggested are ways to do this. Alternatively you can have another object or static method responsible for building your object in a valid state instead
If you do have an object which in not fully initialised then any invalid methods should produce appropriate and descriptive exceptions which let the users know that they are using the code incorrectly, and gives examples of the correct usage patterns.
In c# InvalidStateException is usually appropriate and similar exceptions exist in Java. Ruby is beyond my pay grade unfortunately :)

Overextending object design by adding many trivial fields?

I have to add a bunch of trivial or seldom used attributes to an object in my business model.
So, imagine class Foo which has a bunch of standard information such as Price, Color, Weight, Length. Now, I need to add a bunch of attributes to Foo that are rarely deviating from the norm and rarely used (in the scope of the entire domain). So, Foo.DisplayWhenConditionIsX is true for 95% of instances; likewise, Foo.ShowPriceWhenConditionIsY is almost always true, and Foo.PriceWhenViewedByZ has the same value as Foo.Price most of the time.
It just smells wrong to me to add a dozen fields like this to both my class and database table. However, I don't know that wrapping these new fields into their own FooDisplayAttributes class makes sense. That feels like adding complexity to my DAL and BLL for little gain other than a smaller object. Any recommendations?
Try setting up a separate storage class/struct for the rarely used fields and hold it as a single field, say "rarelyUsedFields" (for example, it will be a pointer in C++ and a reference in Java - you don't mention your language.)
Have setters/getters for these fields on your class. Setters will check if the value is not the same as default and lazily initialize rarelyUsedFields, then set the respective field value (say, rarelyUsedFields.DisplayWhenConditionIsX = false). Getters they will read the rarelyUsedFields value and return default values (true for DisplayWhenConditionIsX and so on) if it is NULL, otherwise return rarelyUsedFields.DisplayWhenConditionIsX.
This approach is used quite often, see WebKit's Node.h as an example (and its focused() method.)
Abstraction makes your question a bit hard to understand, but I would suggest using custom getters such as Foo.getPrice() and Foo.getSpecialPrice().
The first one would simply return the attribute, while the second would perform operations on it first.
This is only possible if there is a way to calculate the "seldom used version" from the original attribute value, but in most common cases this would be possible, providing you can access data from another object storing parameters, such as FooShop.getCurrentDiscount().
The problem I see is more about the Foo object having side effects.
In your example, I see two features : display and price.
I would build one or many Displayer (who knows how to display) and make the price a component object, with a list of internal price modificators.
Note all this is relevant only if your Foo objects are called by numerous clients.

Proto-buf serialization with Obfuscation

I am looking for some guidance as to what is going on when using proto-buf net with obfuscation (Dotfuscator). One half of the project is a DLL and the other is an EXE elsewhere and using proto-buf NET they exchange data flawlessly. Until I obfuscate the DLL.
At that point P-BN fails without raising an exception, returning variously a 0 length byte array or a foreshortened one depending on what I have fiddled with. The class is fairly simple (VB):
<ProtoContract(Name:="DMailer")> _
Friend Class DMailer
Private _Lic As Cert
Private _Sys As Sys
Private _LList As List(Of LItem)
..
..
End Class
There are 3 props all decorated with ProtoMember to get/set the constituent class objects. Snipped for brevity.
Again, it works GREAT until I obfuscate the DLL. Then, Dotfuscator renames each of these to null, apparently since they are all Friend, and that seems to choke proto-buff. If I exempt the class from renaming (just the class name, not props/members), it seems to work again. It makes sense that P-BN would only be able to act on objects with a proper name, though when asked to serialize a null named object, it seems like an exception might be in order.
On the other hand, much of the charm of PB-N is supposed to be serialization independent of .NET names working from attributes - at least as I understand it. Yet in this case it only seems to work with classes with names. I tried using the Name qualifier or argument as shown above, to no avail - it apparently doesnt do what I thought it might.
So, I am curious if:
a) ...I have basically surmised the problem correctly
b) ...There is some other attribute or flag that might facilitate serializing
a null named object
c) ...if there are any other insights that would help.
If I exempt all 3 or 4 classes from Dotfuscator renaming (LList is not actually implemented yet, leaving DMailer, Cert and Sys), the DLL seems to work again - at least the output is the correct size. I can live with that, though obscured names would be better: Dotfuscator (CE) either exempts them or sets the names to Null - I cant seem to find a way to force them to be renamed.
Rather than exempt 3 or 4 classes from renaming, one alternative I am considering is to simply store the Serializer output for Cert and Sys as byte arrays or Base64 strings in DMailer instead of classes. Then have the receiver Deserialize each object individually. It is kind of nice to be able to unpack just one thing and have your toys right there as if by magic though.
(many)TIA
Interesting. I confess I have never tried this scenario, but if you can walk me through your process (or better: maybe provide a basic repro example with "run this, then this, then this: boom") I'll happily investigate.
Note: the Name on ProtoContract is mainly intended for GetProto() usage; it is not needed by the core serializer, and can be omitted to reduce your exposure. Also, protobuf-net isn't interested in fields unless those fields are decorated with the attributes, so that shouldn't be an issue.
However! there's probably a workaround here that should work now; you can pre-generate a static serialization dll; for example in a separate console exe (just as a tool; I really need to wrap this in a standalone utility!)
So if you create a console exe that references your unobfuscated library and protobuf-net.dll:
var model = RuntimeTypeModel.Create();
model.Add(typeof(DMailer), true); // true means "use the attributes etc"
// and other types needed, etc
model.Compile("MailSerializer", "MailSerializer.dll");
this should write MailSerializer.dll, which you can then reference from your main code (in addition to protobuf-net), and use:
var ser = new MailSerializer(); // our pre-genereated serializer
ser.Serialize(...); // etc
Then include MailSerializer.dll in your obfuscation payload.
(this is all v2 specific, btw)
If this doesn't work, I'll need to investigate the main issue, but I'm not an obfuscation expert so could do with your repro steps.
Since there were a few upticks of interest, here is what looks like will work:
a) No form of reflection will be able to get the list of properties for an obfuscated type.
I tried walking thru all the types to find the ones with ProtoContract on it, I could find them
but the property names are all changed to a,m, b, j, g.
I also tried Me.GetType.GetProperties with the same result.
You could implement a map from the output to indicate that Employee.FirstName is now a0.j, but distributing this defeats the purpose of obfuscation.
b) What does work to a degree is to exempt the class NAME from obfuscation. Since PB-N looks for the ProtoMember attributes to get the data, you CAN obfuscate the Property/Member names, just not the CLASS/type name. If the name is something like FederalReserveLogIn, your class/type has a bullseye on it.
I have had initial success doing the following:
1) Build a simple class to store a Property Token and value. Store everything as string using ConvertFromInvariantString. Taking a tip from PBN, I used an integer for the token:
<ProtoMember(propIndex.Foo)>
Property Foo As String
An enum helps tie everything together later. Store these in a Dictionary(Of T, NameValuePair)
2) add some accessors. these can perform the type conversions for you:
Public Sub Add(ByVal Key As T, ByVal value As Object)
If _col.ContainsKey(Key) Then
_col.Remove(Key)
End If
_col.Add(Key, New TValue(value))
End Sub
Public Function GetTItem(Of TT)(key As T) As TT
If _col.ContainsKey(key) Then
Return CType(_col(key).TValue, TT)
Else
Return Nothing
End If
End Function
T is whatever key type you wish to use. Integer results in the smallest output and still allows the subscribing code to use an Enum. But it could be String.
TT is the original type:
myFoo = props.GetTItem(Of Long)(propsEnum.Foo)
3) Expose the innerlist (dictionary) to PBN and bingo, all done.
Its also very easy to add converters for Point, Rectangle, Font, Size, Color and even bitmap.
HTH

Finding variables that share common properties

I'm using Mathematica and have a set of variables (A,B,C,D,...) with properties A=(blue, big, rounded), B=(red, small, spiky), and so forth. Those properties can be common between variables. What would be the best, general way to find all variables that share a common property (of being, for instance, small)? Thanks.
Here's a list of possible properties:
In[1]:= properties={"red","green","blue","big","small","rounded","spiky"};
And here's a list of objects with some of those properties
In[2]:= list={{"blue","big","rounded"},{"red","small","spiky"},
{"red","big","rounded"},{"blue","small","spiky"}};
You can find all objects that have the property of, e.g., being "blue" using Select
In[3]:= Select[list, MemberQ[#,"blue"]&]
Out[3]= {{blue,big,rounded},{blue,small,spiky}}
This could be wrapped up into a function. Although how I would write that function would depend on the data structures and usage that you're planning.
Actually, I just reread you question you have a list of objects with some properties and you want to refer to those objects by name. So you probably want something more like
In[1]:= listProperties["A"]:={"blue","big","rounded"}
listProperties["B"]:={"red","small","spiky"}
listProperties["C"]:={"red","big","rounded"}
listProperties["D"]:={"blue","small","spiky"}
Above I defined some properties that are associated with certain strings. You don't have to use strings in the above or below, and you can create a better structure than that if you want. You could also make a constructor to create the above, such a constructor could also check if the list of properties supplied is of the right form - i.e. does not have contradictory properties, are all in a list of known properties etc...
We then define a function to test if an object/string has a certain property associated with it
In[2]:= hasProperty[obj_, property_]:=MemberQ[listProperties[obj],property]
You might want to return an error or warning message if listProperties[obj] does not have a definition/rule associated with it.
Use Select to find all "objects" in a list that have the associated property "blue":
In[3]:= Select[{"A","B","C","D"}, hasProperty[#,"blue"]&]
Out[3]= {A,D}
There are other ways (probably better ways) to set up such a data structure. But this is one of the simplest ways in Mathematica.

How to name an array that already has a plural name?

What do you name your arrays when the name of the item is already plural?
array names makes sense.
array collisionDatas not so much.
I almost always name it as Item name + s. My goal when naming a variable is to make sure that I reduce the effort needed to read and understand source code.
So if I have an array of children for example I name it childrens. I don't care at all if the childrens is an english word or not, I'm not writing a book! So later when a see something like:
foreach (Object x in childrens) I know I'm iterating on an array of children and not on an array of child objects.
Your question heavily depends on the programming language. Objective-C has strong naming conventions that people adhere to.
Try collisionDataArray.
Personally, I'm used to Cocoa and Objective-C nowadays, and over here long variable and class names are not unusual. For me, autocomplete is good enough, and the code ends up being quite readable.
I sometimes add the type in front, like:
array arrNames
array arrColisionData
I prefer to add the "arr" in the beginning so when you get them in an ordered list, they stay together.