Should we create objects if we need them only once in our code? - coding-style

This is a coding style questions:-
Here is the case
Dim obj1 as new ClassA
' Some lines of code which does not uses obj1
Something.Pass(obj1) ' Only line we are using obj1
Or should we directly initiaize the object when passing it as an argument?
Something.new(new ClassA())

If you're only using the object in that method call, it's probably better to just pass in "new ClassA()" directly into the call. This way, you won't have an extra variable lying around, that someone might mistakenly try to use in the future.
However, for readability, and debugging it's often useful to create the temporary object and pass it in. This way, you can inspect the variable in the debugger before it gets passed into the method.

Your question asks "should we create objects"; both your examples create an object.
There is not logically any difference at all between the two examples. Giving a name to an object allows it to be referred to in more than one place. If you aren't doing that, it's much clearer to not give it a name, so someone maintaining the code can instantly see that the object is only passed to one other method.

Generally speaking, I would say no, there's nothing wrong with what you're doing, but it does sound like there may be some blurring of responsibilities between your calling function, the called function, and the temporary object. Perhaps a bit of refactoring is in order.

I personally prefer things to be consistent, and to make my life easier (what I consider making my life easier may not be what you consider making your life easier... so do with this advice what you will).
If you have something like this:
o = new Foo();
i = 7
bar(o, i, new Car());
then you have an inconsistency (two parameters are variables, the other is created on the fly). To be consistent you would either:
always pass things as variables
always pass things created on the fly
only one of those will work (the first one!).
There are also practical aspects to it as well: making a variable makes debugging easier.
Here are some examples:
while(there are still lines in the file)
{
foo(nextLine());
}
If you want to display the next line for debugging you now need to change it to:
while(there are still lines in the file)
{
line = nextLine();
display(line);
foo(line);
}
It would be easier (and safer) to have made the variable up front. It is safer because you are less likely to accidentally call nextLine() twice (by forgetting to take it out of the foo call).
You can also view the value of "line" in a debugger without having to go into the "foo" method.
Another one that can happen is this:
foo(b.c.d()); // in Java you get a NullPointerException on this line...
was "b" or "c" the thing that was null? No idea.
Bar b;
Car c;
int d;
b = ...;
c = b.c; // NullPointException here - you know b was null
d = c.d(); // NullPointException here - you know c was null
foo(d); // can view d in the debugger without having to go into foo.
Some debuggers will let you highlight "d()" and see what it outputs, but that is dangerous if "d()" has side effects as the debugger will wind up calling "d()" each time you get the value via the debugger).
The way I code for this does make it more verbose (like this answer :-) but it also makes my life easier if things are not working as expected - I spend far less time wondering what went wrong and I am also able to fix bugs much faster than before I adopted this way of doing things.
To me the most important thing when programming is to be consistent. If you are consistent then the code is much easier to get through because you are not constantly having to figure out what is going on, and your eyes get drawn to any "oddities" in the code.

Related

Is it better to give a function an additional parameter, or to make the parameter static?

Many times I've come across a situation where I am calling a method many times with one parameter always exactly the same, and I need to add some additional parameter defined in my main method. I'm never sure what to do about the additional parameter. It seems like it might be a better idea to make the parameter static to make the code cleaner, but then, static variables are not very good. Still, adding parameters can in some cases lead to very long lists of parameters that are in a way unnecessary, and I imagine that there will be a speed disadvantage as well when your function is short, called often, and has a lot of parameters.
Here's the most recent code (kotlin) that has had me thinking about this problem, but I've ran into the problem a lot in different languages.
tailrec fun getAncestor(ind: Int, parent: IntArray): Int {
if (parent[ind] == ind) return ind else return getAncestor(parent[ind], parent);
}
Is it better to make parent a static variable and not have it as a parameter to the method? (Assume that every time that this method is called, the second parameter will be the same. I'm usually only writing short 100 line code files for competitive programming so there is no chance the method will be reused with a different second parameter)
In general if you're working on a project, you'll want to stay away from static variables because when the project starts scaling up and getting bigger, it'll be very hard to keep track of the static variables and this will make it very hard to debug.
In competitive programming, I suggest go for the quicker approach.
In my opinion, it depends on your preferred coding paradigm. For instance, if you'd like your code to conform to the functional paradigm, your code is fine how it is now (regarding the parameter), however, if you don't care about the functional programming, having that param extracted out, as a constant is alright. I see no reason why it should be bad. If you worry about the performance, you could declare it as lazy, but otherwise it'd fine, I guess.

Is it good in Rails view to define constant just to be used once?

To a partial in a HAML file, I am passing parameters whose value is long, or methods whose name is long, for example:
"Some quite long string"
quiteLongMethodNameHere(otherConstant)
To make them shorter, I wrapped them in a constant/variable:
- message = "Some quite long string"
- is_important = quiteLongMethodNameHere(otherConstant)
= render :some_component, msg: message, is_important: is_important
Is this a good practice? Or should I just put the value on the param without wrapping it inside variable/constant?
It's a case-by-case decision. You want to balance the sometimes-competing interests of clarity and conciseness. For me, it depends on the expressiveness of both forms. If the long method name is clear, precise, and expressive, then I would be less interested in using an intermediate variable to hold its result than if it were not.
In other cases where the long form is less expressive, I will often use intermediate variables as "living" documentation, even if they are used only on the next line of code. This more explicitly reveals your intention to the reader (who may someone else, or you at some future point in time).
I find intermediate variables are much better than code comments because code comments can more easily become obsolete, and having the clarification in code makes it available for debuggers, etc. The performance hit of creating an extra variable is minimal, and significant in only the most unusual of cases.
Another factor is if you are aggregating things (in arrays, hashes, etc.) that include these function calls and values, then using the intermediate variable makes the code neater, and possibly easier to understand, as you can customize the name to make the most sense in the context of that collection.
Regardless of the length of the string, it makes sense to assign it to a variable/constant, and not directly refer to it in a view file. If it is a text, it makes more sense to put it in a i18n file.
However, it is not good to do that in the main view file. If you are going to do it, do it in the controller file or a helper file.

How to display a value to the homescreen during a ti-89 titanium program

In relationship to this thread, this is also what i am kind of trying to do but i have had a bit more leeway in this.
My problem is i am currently working on a defining program (for my ti-89 titanium) to write out the definitions of variables. However, considering i had indefinite amounts of variables to add, i thought using the define function over and over again would waste memory and processing power. So my thinking was Save the variable to another variable to be defined in a later portion of the program.
prompt x
lbl x_d_r
x_d_r->q:Goto def
lbl def
define expr(q)[1]=x
where x_d_r has no assigned value. So the program was supposed to use the defined string as a list value to be x. However the obvious error came about.
So i played around on the home screen and program screen for a bit and came across entry(1) and ans(1). See back on the ti-83 (or 84) i could basically go (If i remember correctly)
disp q*1
x->ans(1)
However ans(1) on a ti-89 titanium is based upon the last answer submitted to the homescreen. Even then, ans(1) or entry(1) gets replaced in the program by just that. Lucky me, i found a way to avoid this.
Prgm
expr(char(120)&char(22)&char(97)&char(110)&char(115)&char(40)&char(49)&char(41))
EndPrgm
For those that do not know, this is simply expressing x->ans(1) which is a way for the code to transmit ans(1) within a program without removing the code to say so.
But it still does not work as a value needs to be sent to the home screen in order for it to record properly. This is one of those advantages that the ti-84 or ti-83 i wish it still had on the titanium. So i have spent some time searching for ways how i can display values of q to the home screen from within a program.
So far i learned that functions when used straight from the home screen return the value of q to the same place. However i have no way of implementing this in an actual program as the function does not wish to transmit the value to the home screen, and its rather useless within the program.
Secondly i have found this website which details methods of such ways to return values to the homescreen. While method 1 seems to hold promise, i do not seem to have any way of accessing that folder/program. Most likely because it is one that he made and has not shared its location on the pdf. I do like the expr("q"&":stop"), but q is not evaluated out so maybe i would have to rework it somehow.
While this was happening, i thought some other ideas could be using the paste key within a program but i have no idea how to implement stuff found from getkey let alone how the second and grab buttons factor in.
Or i could somehow have the ans(1) look to someplace else other than the home screen. Preferably to the i/0 screen but maybe to some other list or data matrix.
Anybody have any ideas on how to relay a value to the homescreen be it through function, pasting or something, and have the program i defined earlier define it as a value?
UPDATE+1
Ok i am beginning to question if maybe i am making it more complex than it needs to be...
After all, i am only going for just x->x_d_r[1], which is already defined elsewhere. So does it beat x->q:Goto def
Lbl def
Define expr(q)=x
(Or something like that which calls to a history recording program to define values?)
in terms of processing speed and memory count?
Got it. See here for what i was really trying to do.
So as an explanation of what the main problem was again, i wanted to be able to post a string value of q to be defined by another value of x.
The expr( function is quite a powerful tool on the ti-89 and like the person in that other forum, underestimated it. See what the person was trying to do was
InputStr "Function:",f(x)
expr(f)→f(x)
And was later answered by reworking it as
InputStr "function", n
expr(n & "->f(x)")
The expression tool just simply expresses what is in the parentheses. So during break periods in school today, i reworked in my head thinking "What if i tried rewriting the parenthesis out so it reads Expr("x->"&String(q))?
Lo-and-behold it works. Tested it with the fuller version of define to get
td()
Prgm
Prompt X
x_d_r->q
expr("x->"&string(q)&"[1]")
Disp x_d_r[1]
Delvar x_d_r
EndPrgm
Tried, tested and true. Works all the way. See what i think is happening is that anything that is not within the quotes is evaluated immediately in an expression while the the quoted objects are simply expressed and added later in response to the "&" key. Furthermore it makes sense if i was to describe it more with english; "Express x to be stored into the string of q's respective table".
While for variables sake i would have to look into ways to make x_d_r local only to the program without compensating the fact that the x_d_r portion is not considered a store value when executing x_d_r->q. But knowing what i know now i could probably do
expr("q"+"x_d_r"&->a)
expr("x->"&string(a)-"q"&"[1]")
In order to bypass that problem.

Pointless getter checks when updating an object

Hopefully this will not come across as a silly or pedantic question, but I'm curious.
Occasionally I'll be in a situation where an existing object's properties may need to be updated with new variables, and I'll do it like this (in no particular language):
public void Update(date, somevar){
if(date > this.Date){
this.Var = somevar;
}
}
The idea being that if the date passed to the function is more recent than the date in the current object, the variable is updated. Think of it as like a basic way of caching something.
Now, the interesting part is that I know somevar will never be "old" when compared to this.Var, but it may be the same. So as far as I can see, checking the date is pointless, and therefore a pointless operation for the program to perform.
So what this is really about is whether it's better - in whatever way - to perform a write to this.Var every time Update is called, or getting this.Date, comparing it, then possibly performing the write. And just to throw in something interesting here, what if Update were to be called multiple times?
If the example I've given makes no sense or has holes in it, I apologise; I can't think of another way of giving an example, but hopefully you can see the point I'm trying to make here.
Unless for some reason assignment is an expensive operation (e.g. it always triggers a database write), this isn't going to make your programme faster.
The point of putting checks in your setters is usually to enforce data integrity, i.e. to preserve programme invariants, and thus the correctness of your other code, which is rather more important.

Readability of heavy function call nesting?

I've often seen it argued that heavily nested function calls should not be used because they are unreadable. However, using temporary variables instead creates a lot of unnecessary verbosity and forces the reader to mentally link each temporary variable to what it represents. When looking at the way Lisp code is typically formatted, it occurred to me that nested function calls can actually be made quite readable if you format them to reflect the nesting. For example:
// Totally unreadable:
auto linesIter = filter!"a.length > 0"(map!strip(File(filename).byLine())))
// Perfectly readable. The only difference is formatting.
auto linesIter = filter!"a.length > 0"(
map!strip(
File(filename).byLine()
)
);
// Readable, but unnecessarily verbose:
auto rawLines = File(filename).byLine();
auto stripped = map!strip(rawLines);
auto filtered = filter!"a.length > 0"(stripped);
Writing something like the first example in nested function form is, IMHO, equivalent to doing the following in more procedural-style code:
for(i = 0; i < 10; i++) { for(j = 0; j < 10; j++) { if(x < 2) { z++; } else { y++; }}}
In both cases the real problem is poor formatting, not excessive nesting. How would you rate the readability/comprehensibility of the well-formatted nested function version vs. the temp variable version? Do you think heavy function call nesting is bad style even if it's formatted for maximum readability? If so, why?
I see nothing wrong with breaking large nested function calls in the way you have using formatting. It's readable, which was the intention.
With temporary variables, I try to avoid them. And the only reason for this is quite simply, I am utterly incapable of giving them good names. I try when they are absolutely necessary, and end up wasting 5 - 10 minutes thinking 'what would be the good name for blah blah that does cor blimey'? And almost always end up giving up and using buffer if it's an array, or temp if it's a scalar, etc.
That said, with your nested structure, the functions represent verbs, and not the products of the verb's action, which is what you'd get with temporary variables. With temporary variables, you do get a chance to give that product a name. But if it's a thing that is better described by the verb and direct object themselves (verb(directObject)) then that's the route you should take.
You say "using temporary variables instead creates a lot of unnecessary verbosity and forces the reader to mentally link each temporary variable to what it represents" -- but IMO that's just another way of saying that you've broken up the thing into steps that the reader can understand one at a time -- in other words, you've made it more readable.
I'm quite happy to add an extra variable to break a long line up into seperate steps (your example 3), but the key thing for me is whether you can break the thing up cleanly into genuine steps. One good indicator is whether you can find a good variable name; if you can't, maybe it's not a genuine seperate step that needs splitting out.
There's nothing much wrong with your example 2, but much longer than that and I would certainly break it up. You'll thank yourself when it comes to debugging...
IMHO, objects and names should be carefully chosen so that things are readable when you do the function-style coding of slamming everything onto one line like in your first example. If it is totally unreadable, somebody(s) chose bad names. Your goal is that if something looks off, often times it means there is a bug.
In the real world when you have to deal with those badly-chosen names, there isn't anything wrong with creating temporary constants (or even routines) with proper names to clean things up a bit. It beats a comment, because it compiles and is easier to modify.
I personally think that if there is no performance penalties readability is more important. Although i do not know anything about the Lisp syntax, looks like your examples makes the same number of calls? If thats the case, do it readable way. But if you are calling a heavy function (like opening a file and reading again and again) more times in a loop, you should avoid it. I hope this answer is useful.
I prefer not to use too many variables b/c they are often the source of bugs. If I can express something as a single expression I prefer it that way. I would probably go with your second example.

Resources