Naming member functions/methods with a single underscore, good style or bad? - function

In some languages where you cannot override the () operator, I have seen methods with a single underscore, usually for 'helper' classes. Something likes this:
class D10
{
public function _()
{
return rand(1,10);
}
}
Is it better to have the function called Roll()? Is a underscore fine? After all, there is only one function, and it removes the need to look up the name of the class.
Any thoughts?

I would say it is a bad style. You can not infer behaviour from the name of the function if it simply an underscore.
In order to know what it does you need to read the code, or documentation.
(On a side note, I don't think D10 is a good name for a class either).

I guess it's a matter of taste. But I don't like it.
I believe having full self-explanatory names is always a better practice.
You won't save much time using only one keystroke to call your function but you'll likely loose more time remembering what it does afterwards.
But again, it is very subjective.

It may be legal, and whoever you're working with might not mind (even more so if you're working alone) but if it were me it would make me crazy. Spelling out D10.roll() doesn't take up much of your time, and it makes your code that much easier to follow since the name is self-explanatory.
The bottom line, though, is that elegance is in the eye of the beholder; if everyone who's working on your code agrees that that's a simple and clear identifier, nobody is going to stop you.

To me, this is quite obviously bad style.
Method names are names, and are supposed to be descriptive. They're not "proper names" like you have for people*, places and so on, they're names that describe the actions taken by the code contained within.
* Although of course many names for people were almost literally descriptive originally, but that's not generally the indended use nowadays.

I don't think the structure is optimal to begin with. I would simply do this:
class Dice
{
public int D10()
{
return rand(1,10);
}
public int D6()
{
return rand(1,6);
}
// And so on...
}
Then it will be made clear that we're actually taking about dice here and we don't have to create one class for every possible dice.
If you really need to abstract away what dice you're using, I hope that you're using a language that handle functions as first class objects, in which case you would do this:
void RussianRoulette(SOMEFUNCTIONSIGNATURE dice)
{
if (dice() == 1)
print "BANG";
else
print "click";
}
RussionRoulette(Dice.D6); // Regular russian roulette
RussionRoulette(Dice.D100); // For the faint of heart
RussionRoulette(Dice.D1); // Die! :)

Related

Assign super to variable in AS3

I have this:
public class Base {
public function whoAmI() {
trace("base");
}
}
public class Extended extends Base {
public function Extended() {
this.whoAmI() //prints extended
super.whoAmI() //prints base
var test = super;
test.whoAmI() //prints extended
}
public override function whoAmI() {
trace("extended");
}
}
The problem is when I do var test = super, it seems like this is assigned to test instead of super.
Is it possible to do the assignment so that test.whoAmI() prints "base"?
Edit: In the comments it is being said that using super in the way I propose would break overriding. I don't think that's the case. The way I am thinking of it, super could be used the same way as this. I understand that is not the way super is implemented, but using it that way would not break overriding as people are claiming. So for example the same way this is possible:
var test = this;
test.whoAmI();
This should be possible:
var test = super;
super.whoAmI();
It is obviously the choice of the language implementer to not do things this way, and I don't understand the reason why. It doesn't break things, but I guess it does make them more complicated.
I am not suggesting type-casting this to the super class. Obviously that wouldn't work.
You are thinking of "this" and "super" as 2 different instances, 2 different things but they in fact point to the same object (obviously) so at the end it's always "this". Using super is just a special keyword that allows the instance to point to the overrided definitions up the inheritance chain, it does not point to a different object. So "super" does correctly its job, it points to the instance and allow you each time you use it to access overrided definitions and that's it. There's of course no point on trying to store that keyword in a variable since in that case it just return correctly the instance it points to which is always "this".
It's simply a case of misunderstood inheritance principle and I've seen it before, super is mistaken for some kind of instance wrapper up the inheriatnce chain around the object "this" while it's in fact and always the same object.
No, this is not possible.
If this were possible, then overriding methods wouldn't be possible!
For example, take this function...
public function test(a:Object):void {
trace(a.toString());
}
You'd only get [object Object] back if your idea was how things worked.
Ok I understand what you mean your question is more about language definition and specification.
Look at this exemple in c# that explain how you can manage more precisely overriding in c# :
http://www.dotnet-tricks.com/Tutorial/csharp/U33Y020413-Understanding-virtual,-override-and-new-keyword-in-C
But
let's explain a litlle how it's work.
when you extend a class, it's like if you create an object composed of all the object in the inheritance tree so if B extends A and C extends B you have two objects like this:
(B+A) and (C+B+A) with hierarchy between each other B->A and C->B->A. Super is just a way to ascend in the hierachy.
When you cast a C in A for example. In memory you always have an object (C+B+A) but interpreted as A. When you override you just say that a method in child has an higher priority than in parent.
You can try downcasting this manually to any of your class's predecessors. The pointer will still be equal to this but the methods called will use the class table of the class used to downcast.
public class Extended extends Base {
public function Extended() {
this.whoAmI() //prints extended
super.whoAmI() //prints base
var test:Base = this;
test.whoAmI() //should print base
}
public override function whoAmI() {
trace("extended");
}
}
Should your Base extend something, which methods are known or the superclass is dynamic, and there is code that adds methods to prototype of a class, you might use such a downcast to call a superclass's method that might not be there at compile time, but make sure you first call hasOwnProperty in case of a dynamic class to determine whether a method or property exists.

How to properly structure functions?

let's say we have a class with some methods in it, of which at least one is of rather complex nature:
class Example {
public function Example()
{
}
private function complexFunction():void
{
//Do this
//And do that
//And of course do that
//and do not forget that
}
private function otherImportantFunction():void
{
//Do something
}
//[...]
}
Now "complexFunction()" has grown pretty long and also a little complicated. So a nice thing to do to increase readability would be to split up "complexFunction()" in smaller sub-functions. I usually do it like this:
class Example {
public function Example()
{
}
private function complexFunction():void
{
doThis();
doThat();
andOfCourseDoThat();
andDoNotForgetThat();
}
private function doThis():void
{
//Do This
}
private function doThat():void
{
//Do That
}
private function andOfCourseDoThat():void
{
//And of course do that
}
private function andDoNotForgetThat():void
{
//And do not forget that
}
private function otherImportantFunction():void
{
//Do something
}
//[...]
}
But by now the class is already drowning in minor functions whose sole purpose is to get called once inside "complexFunction()". Do this "splitting-up" a little more often and it becomes hard to spot the important methods between all those helper-functions.
At least this is what happens to me all the time and clarity really suffers for it. That makes me wonder if you know a way to solve that dilemma? Surely there is way or 'best practice' to handle this?
I'm dreaming of a way to group functions together, or to subordinate the minor ones to the superior ones, without creating a whole new class for that purpose. Or is that how it's done?
You are right to split up the one large function into multiple functions. Provided it isn't something like AddOne() instead of value++. Especially functions you'll probably repeat more often can be of use.
When your class is getting filled with multiple functions (or long functions), it might be a good idea to reconsider what your class does. Try to keep your class destined for one subject. For example, a good idea for a class is to make it User-related. Things like creating or removing users can be done in there. Even matching users to, for example, cars they own can be done in there. But don't include functions in the User-class which save or remove Cars. Save that for a different class.
In that case, your Example-class would have instances of the User-class and the Car-class. If it looks like this, you're programming efficiently:
class Example {
function Example()
{
}
function complexFunction():void
{
Car newCar = new Car("KK-E8", Color.Red, true);
carManager.Add(newCar);
User newUser = new User("Moritz", "Krohn", Country.Germany, true);
userManager.Add(newUser);
newUser.addCar(newCar);
...
}
It happens that some classes tend to get large, even when you try to keep things organised. That is never a bad thing, neither are long functions. Just try to keep things seperated, try not to repeat code too much (create functions for that) and try to keep things related to eachother in seperate classes.
I personally find that it increases readability of complex code a lot if it is split into simple functions.
What I don't really get in the code presented is the way those simpler functions are combined into one function, this seems only to work for functions that don't return anything at all (they just seem to have some effects). A more natural way imho to build up a complex function from simpler ones, would be by way of function composition, case distinction or something alike...
Just because a function is "long" does not make it more complex, Some things just take many lines of code.
Take for example:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
loader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
loader.contentLoaderInfo.addEventListener(Event.OPEN, openHandler);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.contentLoaderInfo.addEventListener(Event.UNLOAD, unLoadHandler);
loader.contentLoaderInfo.addEventListener(MouseEvent.CLICK, clickHandler);
var request:URLRequest = new URLRequest(url);
loader.load(request);
Is it "long"? yes
Does it have a high Cyclomatic Complexity? no
You can plainly understand what is going on here and it very easy to follow.
And you will find functions/methods with low CC values will always be easier to read.
On the other hand methods with high(+20) CC value should be putting up a red flag.
Splitting a method into separate helper methods does not remove the issue at hand and is actually making things worse for the compiler since now it has to allocate resource devoted to those methods that will only ever be called once.
The rule of thumb is to avoid going above a CC value of 20.
When you get above 20 it is time to start rethinking your class design as it is becoming tightly coupled.
Perhaps the question you should be asking is .
How can I reduce the Cyclomatic Complexity of this?

AS3 Object indexing causing Flixel misbehaviour--what's wrong with this code?

I'm getting my feet wet with AS3, Flixel and component/entity systems (yes, all at the same time), and my entities (which subclass FlxSprite) aren't being added correctly (i.e., not at all). I've just spent a good two hours nailing down the offending line. If I remove it, the rest of the game chugs along happily.
What's wrong with this code?
public function addComponent(c:Component):void
{
var type:String = Object(c).constructor.toString();
FlxG.log("type=" + type);
this._components[type] = c; // The evil line
FlxG.log("now type=" + _components[type]);
c.setData(this);
}
components is an Object field being used as a map/dictionary. type gets set to [class PlayerComponent]. Based on googling, this is valid and should work as intended.
Based on the output from the console, it's just bailing after that line--not crashing entirely. What's going on? More details gladly offered upon request.
I'm not certain about Component - not my forte - but I do know that FlxGroup and its children (which include FlxState) have a method called add() which adds children to them.
So if you have an FlxSprite, the correct way (in flixel) to add it to the chain of things to update/draw is to use that; you can add it directly to your state or to a group that is a child of the state.
Function docs: http://flixel.org/docs/org/flixel/FlxGroup.html#add()

Stylistic Question: Use of White Space

I have a particularly stupid insecurity about the aesthetics of my code... my use of white space is, frankly, awkward. My code looks like a geek dancing; not quite frightening, but awkward enough that you feel bad staring, yet can't look away.
I'm just never sure when I should leave a blank line or use an end of line comment instead of an above line comment. I prefer to comment above my code, but sometimes it seems strange to break the flow for a three word comment. Sometimes throwing an empty line before and after a block of code is like putting a speed bump in an otherwise smooth section of code. For instance, in a nested loop separating a three or four line block of code in the center almost nullifies the visual effect of indentation (I've noticed K&R bracers are less prone to this problem than Allman/BSD/GNU styles).
My personal preference is dense code with very few "speed bumps" except between functions/methods/comment blocks. For tricky sections of code, I like to leave a large comment block telling you what I'm about to do and why, followed by a few 'marker' comments in that code section. Unfortunately, I've found that some other people generally enjoy generous vertical white space. On one hand I could have a higher information density that some others don't think flows very well, and on the other hand I could have a better flowing code base at the cost of a lower signal to noise ratio.
I know this is such a petty, stupid thing, but it's something I really want to work on as I improve the rest of my skill set.
Would anyone be willing to offer some hints? What do you consider to be well flowing code and where is it appropriate to use vertical white space? Any thoughts on end of line commenting for two or three words comments?
Thanks!
P.S.
Here's a method from a code base I've been working on. Not my best, but not my worst by far.
/**
* TODO Clean this up a bit. Nothing glaringly wrong, just a little messy.
* Packs all of the Options, correctly ordered, in a CommandThread for executing.
*/
public CommandThread[] generateCommands() throws Exception
{
OptionConstants[] notRegular = {OptionConstants.bucket, OptionConstants.fileLocation, OptionConstants.test, OptionConstants.executable, OptionConstants.mountLocation};
ArrayList<Option> nonRegularOptions = new ArrayList<Option>();
CommandLine cLine = new CommandLine(getValue(OptionConstants.executable));
for (OptionConstants constant : notRegular)
nonRegularOptions.add(getOption(constant));
// --test must be first
cLine.addOption(getOption(OptionConstants.test));
// and the regular options...
Option option;
for (OptionBox optionBox : optionBoxes.values())
{
option = optionBox.getOption();
if (!nonRegularOptions.contains(option))
cLine.addOption(option);
}
// bucket and fileLocation must be last
cLine.addOption(getOption(OptionConstants.bucket));
cLine.addOption(getOption(OptionConstants.fileLocation));
// Create, setup and deploy the CommandThread
GUIInteractiveCommand command = new GUIInteractiveCommand(cLine, console);
command.addComponentsToEnable(enableOnConnect);
command.addComponentsToDisable(disableOnConnect);
if (!getValue(OptionConstants.mountLocation).equals(""))
command.addComponentToEnable(mountButton);
// Piggy-back a Thread to start a StatReader if the call succeeds.
class PiggyBack extends Command
{
Configuration config = new Configuration("piggyBack");
OptionConstants fileLocation = OptionConstants.fileLocation;
OptionConstants statsFilename = OptionConstants.statsFilename;
OptionConstants mountLocation = OptionConstants.mountLocation;
PiggyBack()
{
config.put(OptionConstants.fileLocation, getOption(fileLocation));
config.put(OptionConstants.statsFilename, getOption(statsFilename));
}
#Override
public void doPostRunWork()
{
if (retVal == 0)
{
// TODO move this to the s3fronterSet or mounts or something. Take advantage of PiggyBack's scope.
connected = true;
statReader = new StatReader(eventHandler, config);
if (getValue(mountLocation).equals(""))
{
OptionBox optBox = getOptionBox(mountLocation);
optBox.getOption().setRequired(true);
optBox.requestFocusInWindow();
}
// UGLY HACK... Send a 'ps aux' to grab the parent PID.
setNextLink(new PSCommand(getValue(fileLocation), null));
fireNextLink();
}
}
}
PiggyBack piggyBack = new PiggyBack();
piggyBack.setConsole(console);
command.setNextLink(piggyBack);
return new CommandThread[]{command};
}
It doesn't matter.
1) Develop a style that is your own. Whatever it is that you find easiest and most comfortable, do it. Try to be as consistent as you can, but don't become a slave to consistency. Shoot for about 90%.
2) When you're modifying another developer's code, or working on a group project, use the stylistic conventions that exist in the codebase or that have been laid out in the style guide. Don't complain about it. If you are in a position to define the style, present your preferences but be willing to compromise.
If you follow both of those you'll be all set. Think of it as speaking the same language in two different ways. For example: speaking differently around your friends than you do with your grandfather.
It's not petty to make pretty code. When I write something I'm really proud of, I can usually take a step back, look at an entire method or class, and realize exactly what it does at a glance - even months later. Aesthetics play a part in that, though not as large of a part as good design. Also, realize you can't always write pretty code, (untyped ADO.NET anyone?) but when you can, please do.
Unfortunately, at this higher level at least, I'm not sure there are any hard rules you can adhere to to always produce aesthetically pleasing code. One piece of advice I can offer is to simply read code. Lots of it. In many different frameworks and languages.
I like to break up logical "phrases" of code with white space. This helps others easily visualize the logic in the the method - or remind me when I go back and look at old code. For example, I prefer
reader.MoveToContent();
if( reader.Name != "Limit" )
return false;
string type = reader.GetAttribute( "type" );
if( type == null )
throw new SecureLicenseException( "E_MissingXmlAttribute" );
if( String.Compare( type, GetLimitName(), false ) != 0 )
throw new SecureLicenseException( "E_LimitValueMismatch", type, "type" );
instead of
reader.MoveToContent();
if( reader.Name != "Limit" )
return false;
string type = reader.GetAttribute( "type" );
if( type == null )
throw new SecureLicenseException( "E_MissingXmlAttribute" );
if( String.Compare( type, GetLimitName(), false ) != 0 )
throw new SecureLicenseException( "E_LimitValueMismatch", type, "type" );
The same break can almost be accomplished with braces but I find that actually adds visual noise and reduces the amount of code that can be visually consumed simultaneously.
Commens on code line
As for comments at the end of the line - almost never. The're not really bad, just easy to miss when scanning through code. And they clutter up the line taking away from the code making it harder to read. Our brains are already wired to grok line by line. When the comment is at the end of the line we have to split the line into two concrete concepts - code and comment. I say if it's important enough to comment on, put it on the line proceeding the code.
That being said, I do find one or two line hint comments about the meaning of a specific value are sometimes OK.
I find code with very little whitespace hard to read and navigate in, since I need to actually read the code to find logical structure in it. Clever use of whitespace to separate logical parts in functions can increase the ease of understanding the code, not only for the author but also for others.
Keep in mind that if you are working in an environment where your code is likely to be maintained by others, they will have spent the majority of their time looking at code that was not written by you. If your style distinctly differs from what they are used to seeing, your smooth code may be a speed bump for them.
I minimize white space. I put the main comment block above the code block and Additional end of line comments on the Stuff that may not be obvious to another dveloper. I think you are doing that already
My preferred style is probably anathema to most developers, but I will add occasional blank lines to separate what seem like appropriate 'paragraphs' of code. It works for me, nobody has complained during code reviews (yet!), but I can imagine that it might seem arbitrary to others. If other people don't like it I'll probably stop.
The most important thing to remember is that when you join an existing code base (as you almost always will in your professional career) you need to adhere to the code style guide dictated by the project.
Many developers, when starting a project afresh, choose to use a style based on the Linux kernel coding-style document. The latest version of that doc can be viewed at http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=blob;f=Documentation/CodingStyle;h=8bb37237ebd25b19759cc47874c63155406ea28f;hb=HEAD.
Likewise many maintainers insist that you use Checkpatch before submitting changes to version control. You can see the latest version that ships with the Linux kernel in same tree I linked to above at scripts/checkpatch.pl (I would link to it but I'm new and can only post one hyperlink per answer).
While Checkpatch is not specifically related to your question about whitespace usage, it will certainly help you eliminate trailing whitespace, spaces before tabs, etc.
Code Complete, by Steve McConnell (available in the usual locations) is my bible on this sort of thing. It has a whole chapter on layout and style that is just excellent. The whole book is just chock full of useful and practical advice.
I use exactly the same amount of whitespace as you :) Whitespace before methods, before comment blocks. In C, C++ the brackets also provide some "pseudo-whitespace" as there is only a single opening/closing brace on some lines, so this also serves to break up the code density.
Your code is fine, just do what you (and others you might work with) are comfortable with.
The only thing I see wrong with some (inexperienced) programmers about whitespace is that they can be afraid to use it, which is not true in this case.
I did however notice that you did not use more than one consecutive blank line in your sample code, which, in certain cases, you should use.
Here is how I would refactor that method. Things can surely still be improved and I did not yet refactor the PiggyBack class (I just moved it to an upper level).
By using the Composed Method pattern, the code becomes easier to read when it's divided into methods that each do one thing and work on a single level of abstraction. Also less comments are needed. Comments that answer to the question "what" are code smells (i.e. the code should be refactored to be more readable). Useful comments answer to the question "why", and even then it would be better to improve the code so that the reason will be obvious (sometimes that can be done by having a test that will fail without the inobvious code).
public CommandThread[] buildCommandsForExecution() {
CommandLine cLine = buildCommandLine();
CommandThread command = buildCommandThread(cLine);
initPiggyBack(command);
return new CommandThread[]{command};
}
private CommandLine buildCommandLine() {
CommandLine cLine = new CommandLine(getValue(OptionConstants.EXECUTABLE));
// "--test" must be first, and bucket and file location must be last,
// because [TODO: enter the reason]
cLine.addOption(getOption(OptionConstants.TEST));
for (Option regularOption : getRegularOptions()) {
cLine.addOption(regularOption);
}
cLine.addOption(getOption(OptionConstants.BUCKET));
cLine.addOption(getOption(OptionConstants.FILE_LOCATION));
return cLine;
}
private List<Option> getRegularOptions() {
List<Option> options = getAllOptions();
options.removeAll(getNonRegularOptions());
return options;
}
private List<Option> getAllOptions() {
List<Option> options = new ArrayList<Option>();
for (OptionBox optionBox : optionBoxes.values()) {
options.add(optionBox.getOption());
}
return options;
}
private List<Option> getNonRegularOptions() {
OptionConstants[] nonRegular = {
OptionConstants.BUCKET,
OptionConstants.FILE_LOCATION,
OptionConstants.TEST,
OptionConstants.EXECUTABLE,
OptionConstants.MOUNT_LOCATION
};
List<Option> options = new ArrayList<Option>();
for (OptionConstants c : nonRegular) {
options.add(getOption(c));
}
return options;
}
private CommandThread buildCommandThread(CommandLine cLine) {
GUIInteractiveCommand command = new GUIInteractiveCommand(cLine, console);
command.addComponentsToEnable(enableOnConnect);
command.addComponentsToDisable(disableOnConnect);
if (isMountLocationSet()) {
command.addComponentToEnable(mountButton);
}
return command;
}
private boolean isMountLocationSet() {
String mountLocation = getValue(OptionConstants.MOUNT_LOCATION);
return !mountLocation.equals("");
}
private void initPiggyBack(CommandThread command) {
PiggyBack piggyBack = new PiggyBack();
piggyBack.setConsole(console);
command.setNextLink(piggyBack);
}
For C#, I say "if" is just a word, while "if(" is code - a space after "if", "for", "try" etc. doesn't help readability at all, so I think it's better without the space.
Also: Visual Studio> Tools> Options> Text Editor> All Languages> Tabs> KEEP TABS!
If you're a software developer who insists upon using spaces where tabs belong, I'll insist that you're a slob - but whatever - in the end, it's all compiled. On the other hand, if you're a web developer with a bunch of consecutive spaces and other excess whitespace all over your HTML/CSS/JavaScript, then you're either clueless about client-side code, or you just don't give a crap. Client-side code is not compiled (and not compressed with IIS default settings) - pointless whitespace in client-side script is like adding pointless Thread.Sleep() calls in server-side code.
I like to maximize the amount of code that can be seen in a window, so I only use a single blank line between functions, and rarely within. Hopefully your functions are not too long. Looking at your example, I don't like a blank line for an open brace, but I'll have one for a close. Indentation and colorization should suffice to show the structure.

What do you call an object level equivalent of Mixin/Traits system, is there a Pattern name for it?

I previously asked about what Mixins were, and have begun to get the gist of what the pattern means. But it got me wondering if there is a common pattern name for doing something like Mixins at an Object level as opposed to the Class level.
Pseudo code (in some non existent language):
Class MyClass
{
function foo()
{
print("foo")
}
}
function bar()
{
print("bar")
}
object = MyClass.new()
object.xxxx(bar)
object.bar() #output: bar
I know stuff like this can be done in several languages, in one way or another, but I'm wondering what would be the "standard" name for the functionality xxxx represents, and what is the name for this pattern, if there is one.
Thanks!
Edit: Expanding on finnsson's answer I guess something like this might be another case of this would be:
object.xxxx(OtherClass)
object.otherfoo()
Would concatenate be appropriate?
Quote: "Concatenation: Under pure prototyping, which is also referred to as concatenative prototypes..." -wikipedia
This is common in prototype-based programming languages. I belive it's called "import" in ruby but it's some time since I last programmed ruby so I'm not sure.
In js/ruby you would write
object.bar = bar;
object.bar() // output: bar
and than it's no real pattern, since it's just an assignment (o.bar = bar) making perfect sense in a prototype-based language. I guess xxxx in your example could be called prototype or something similar (see http://en.wikipedia.org/wiki/Prototype-based_programming where a language calles this proto).