Type id to the left or right of var id? - syntax

What is the reasoning behind the two common variable declaration syntax that many popular languages use, such as:
int foo = 0;
and
foo:int = 0;
One problem I have with the second option, is that it almost looks like you are doing, "int = 0;". Why do languages use a particular way? Is it easier to parse or something of the like?

I have studied the basics of compiler development and I do not think that parsers have any problem at all in both cases given actual solutions and techniques.
For me it's clearly a matter of readability from human eyes. I think it's easier to read
int foo = 0
than
foo:int = 0
In fact, I would say that it's even easier to simply write foo = 0, since one can recognize that 0 is an integer number :) I personally like this approach, instead of having type identifiers.

Related

Library to compare two .proto files for equal message ids

In my current project, I am persisting protobufs with enums. To ensure backwards compatibility, I need to make sure that these enums stay the same and I want to write unit tests for that.
Example:
legacy_mood.proto:
enum Mood {
HAPPY = 0;
SAD = 1;
}
mood.proto:
enum Mood {
EXCITED = 0;
HAPPY = 1;
SAD = 2;
}
I am looking for a way to compare these two protos, and in this case let the test fail, because the constant value from HAPPY and SAD changed.
I want to allow new values, so I really just want to check equivalence for elements that exist in the legacy proto, so EXCITED should be ignored in this case.
Before I implement this myself, is there a library for that? I've been googleing for a bit now, but couldn't find anything. Could be in Java, C++ or Python
In any of the language you mentioned, you can convert the Enum value A in message Foo to its string representation, and use the string name to get the Enum value B in message Bar, and make sure the two values are equal.
Python API: https://developers.google.com/protocol-buffers/docs/reference/python-generated#enum

Languages with auto-updatable variables

Is somewhere exists programming languages with auto-updatable variables.
For example:
a = 100
b = a * 3 + 1 // 301
c = sin(b) + a // 99.1428
After modifying 'a': a = 105, corresponding variables automatically recalculated:
b: 316
c: 104.3053
If such languages exists, what approaches are used to implement this behavior?
What you want is deferred evaluation. It's common in spreadsheet applications. I think the R language also allows for something like that.
You can implement it in almost any language.
The usual approach is that you define a terminator class (say Number) and override the operators (if the language supports it, like c++, C# or python) to return nodes in an tree. So a * 3 + 1 will be equivalent to something like (b = Sum(Mult(a, Number(3)), Number(1)). Once you have something like this you can change the value of a with an accessor and then request the top node to be reevaluated, which gives you the value you need.
There are probably a couple of implementations already out there. It's not hard to implement, but it'a bit tedious to define all the classes and implicit conversions needed. It get's more complicated if you want to optimize the evaluation.
You might want to take a look at Functional Reactive Programming in general, and Elm in particular, which provide that kind of computational style in a functional programming environment.

is there a proper way to do function/method calls in programming

So, I was coding and I essentially got this line of code
return parseInt(trim(elem.value.substring(1, elem.value.length)))
And I was thinking, is this proper or would a professor/employer slam me for allowing such a line of code.
I feel like, while nice a tidy, this is difficult to understand what the crap I was doing at first glance. This one isn't so bad b/c most of the calls are common enough (making sure it's an int, trimming the string so conversion works and removing unnecessary information from the beginning of the string)
But, is this ok? Or should I break it down and comment each line so it's easier to understand for future programmers?
Like...
var returnInt;
returnInt = elem.value.substring(1, elem.value.length); //remove $ symbol
returnInt = trim(returnInt); //trim whitespace
returnInt = parseInt(returnInt); //convert to int
return returnInt;
I wasn't sure how to search for this so I apologize if there's something on this.
The first format is fine, except that it can make runtime exceptions like NullPointerExceptions difficult to debug (because the stack trace returns a line number and there are multiple things it could be on one line). So if NPEs can occur, write it out in multiple lines.
And it's not necessary to end-of-line comment every line. It's pretty obvious what trim and parseToInt do to anyone but the most novice programmer, and a simple Google search would turn that up anyways.
It's okay as long as you format your code nicely. e.g. your line may look like:
return parseInt(
trim(
elem.value.substring(1, elem.value.length)))
quote:
Or should I break it down and comment each line so it's easier to understand for future programmers? Like...
var returnInt;
returnInt = elem.value.substring(1, elem.value.length); //remove $ symbol
returnInt = trim(returnInt); //trim whitespace
returnInt = parseInt(returnInt); //convert to int
return returnInt;
It's not easier. Excessive mutability is evil; and this won't work if your values have different type. (Oops, you are probably using dynamic-typed language, but then the name of var returnInt will be misleading, because at some program states is is indeed not an Int). Please, don't write code like this.
I don't care about what professors or employers would think about it. Unless it becomes really really long, I always inline such simple statements as they are more understandable and clear that way.
I think it looks more complicated when you break it down. And I hate useless assingments and equals signs. I only break statements when I do something really really complicated and it needs comments for other people and for me in the future.
In your example, all of the statements are pretty simple and clear. None of them needs comments or explanations to an average developer.

Is using flags very often in code advisable?

I came across lot of flags while reading someone else code,
if (condition1)
var1 = true
else
var1 = false
then later,
if (var1 == true)
// do something.
There are lot of flags like this. I eager to know, is using flags very often in code advisable?
This:
if (condition1)
var1= true;
else
var1 = false;
Is a classic badly written code.
Instead you should write:
var1 = condition1;
And yes, flags are very useful for making the code be more readable and possibly, faster.
It's advisable if condition1 is something quite complicated - like if (A && (B || C) && !D) or contains a lot of overhead (if (somethingTimeConsumingThatWontChange())) then it makes sense to store that result instead of copy-pasting the code.
If condition1 is just a simple comparison then no, I wouldn't use a flag.
This is pretty subjective, and depends on the rest of the code. "Flags" as you call them have their place.
First of all, this code should read like this:
var1 = condition1;
if( var1 )
// No need to compare *true* to *true* when you're looking for *true*
As for the number of flags, there are more elegant ways of branching your code. For instance , when using javascript you can do stuff like this:
var methodName = someFunctionThatReturnsAString();
// assuming you name the method according to what's returned
myObject[ methodName ]();
instead of
if( someFunctionThatReturnsAString === 'myPreferedMethod' ){
myObject.myPreferedMethod();
}else{
myObject.theOtherMethod();
}
If you're using a strongly typed language, polymorphism is your friend. I think the technique is refered to as polymorphic dispatch
I remember this Replace Temp var with Query method from the refactoring book.
I think this refactoring will make the code more readable, but, I agree that it might affect performance when the query method is expensive ... (But, maybe the query method can be put in its own class, and the result can be cached into that class).
This is question is a bit generic. The answer depends on what you want to do and with which language you want it to do. Assuming an OO context than there could be better approaches.
If the condition is the result of some object state than the "flag" should propably be a property of the object itself. If it is a condition of the running application and you have a lot of these things it might could be that you should think about a state pattern/state machine.
Flags are very useful - but give them sensible names, e.g. using "Is" or similar in their names.
For example, compare:
if(Direction) {/* do something */}
if(PowerSetting) {/* do something else */}
with:
if(DirectionIsUp) {/* do something */}
if(PowerIsOn) {/* do something else */}
If it is readable and does the job then there's nothing wrong with it. Just make use of "has" and "is" prefix to make it more readable:
var $isNewRecord;
var $hasUpdated;
if ($isNewRecord)
{
}
if ($hasUpdated)
{
}
Bearing in mind that that code could be more readably written as
var1 = condition1
, this assignment has some useful properties if used well. One use case is to name a complicated calculation without breaking it out into a function:
user_is_on_fire = condition_that_holds_when_user_is_on_fire
That allows one to explain what one is using the condition to mean, which is often not obvious from the bare condition.
If evaluating the condition is expensive (or has side effects), it might also be desirable to store the result locally rather than reevaluate the condition.
Some caveats: Badly named flags will tend to make the code less readable. So will flags that are set far from the place where they are used. Also, the fact that one wants to use flags is a code smell suggesting that one should consider breaking the condition out into a function.
D'A
Call it flags when you work in a pre-OO language. They are useful to parameterize the behaviour of a piece of code.
You'll find the code hard to follow, soon, however. It would be easier reading/changing/maintaining when you abstract away the differences by e.g. providing a reference to the changeable functionality.
In languages where functions are first-class citisens (e.g. Javascript, Haskell, Lisp, ...), this is a breeze.
In OO languages, you can implement some design patterns like Abstract Factory, Strategy/Policy, ...
Too many switches I personally regard as code smell.
That depends on the condition and how many times it's used. Anyway, refactoring into function (preferably caching the result if condition is slow to calculate) might give you a lot more readable code.
Consider for example this:
def checkCondition():
import __builtin__ as cached
try:
return cached.conditionValue
except NameError:
cached.conditionValue = someSlowFunction()
return cached.conditionValue
As for coding style:
if (condition1)
var1= true
else
var1 = false
I hate that kind of code. It should be either simply:
var1 = condition1
or if you want to assure that's result is boolean:
var1 = bool(condition1)
if (var1 == true)
Again. Bad coding style. It's:
if (var1)
What i dont like about flags, is when they are called flags, with no comment whatsoever.
e.g
void foo(...){
bool flag;
//begin some weird looking code
if (something)
[...]
flag = true;
}
They attempt against code redeability. And the poor guy who has to read it months/years after the original programmer is gone, is going to have some hard time trying to understand what the purposse of it originally was.
However, if the flag variable has a representative name, then i think they are ok, as long as used wisely (see other responses).
Yes, that is just silly nonsensical code.
You can simplify all that down to:
if (condition1)
{
// do something
}
Here's my take.
Code using flags:
...
if (dogIsBarking && smellsBad) {
cleanupNeeded = true;
}
doOtherStuff();
... many lines later
if (cleanupNeeded) {
startCleanup();
}
...
Very unclean. The programmer simply happens to code in whatever order his mind tells him to. He just added code at a random place to remind himself that cleanup is needed later on... Why didn't he do this:
...
doOtherStuff();
... many lines later
if (dogIsBarking && smellsBad) {
startCleanup();
}
...
And, following advise from Robert Martin (Clean Code), can refactor logic into more meaningful method:
...
doSomeStuff();
... many lines later
if (dogTookADump()) {
startCleanup();
}
...
boolean dogTookADump() {
return (dogIsBarking && smellsBad);
}
So, I have seen lots and lots of code where simple rules like above could be followed, yet people keep adding complications and flags for no reason! Now, there are legit cases where flags might be needed, but for most cases they are one style that programmers are carrying over from the past.

What are the pros and cons of putting as much logic as possible in a minimum(one-liners) piece of code?

Is it cool?
IMO one-liners reduces the readability and makes debugging/understanding more difficult.
Maximize understandability of the code.
Sometimes that means putting (simple, easily understood) expressions on one line in order to get more code in a given amount of screen real-estate (i.e. the source code editor).
Other times that means taking small steps to make it obvious what the code means.
One-liners should be a side-effect, not a goal (nor something to be avoided).
If there is a simple way of expressing something in a single line of code, that's great. If it's just a case of stuffing in lots of expressions into a single line, that's not so good.
To explain what I mean - LINQ allows you to express quite complicated transformations in relative simplicity. That's great - but I wouldn't try to fit a huge LINQ expression onto a single line. For instance:
var query = from person in employees
where person.Salary > 10000m
orderby person.Name
select new { person.Name, person.Deparment };
is more readable than:
var query = from person in employees where person.Salary > 10000m orderby person.Name select new { person.Name, person.Deparment };
It's also more readabe than doing all the filtering, ordering and projection manually. It's a nice sweet-spot.
Trying to be "clever" is rarely a good idea - but if you can express something simply and concisely, that's good.
One-liners, when used properly, transmit your intent clearly and make the structure of your code easier to grasp.
A python example is list comprehensions:
new_lst = [i for i in lst if some_condition]
instead of:
new_lst = []
for i in lst:
if some_condition:
new_lst.append(i)
This is a commonly used idiom that makes your code much more readable and compact. So, the best of both worlds can be achieved in certain cases.
This is by definition subjective, and due to the vagueness of the question, you'll likely get answers all over the map. Are you referring to a single physical line or logical line? EG, are you talking about:
int x = BigHonkinClassName.GetInstance().MyObjectProperty.PropertyX.IntValue.This.That.TheOther;
or
int x = BigHonkinClassName.GetInstance().
MyObjectProperty.PropertyX.IntValue.
This.That.TheOther;
One-liners, to me, are a matter of "what feels right." In the case above, I'd probably break that into both physical and logic lines, getting the instance of BigHonkinClassName, then pulling the full path to .TheOther. But that's just me. Other people will disagree. (And there's room for that. Like I said, subjective.)
Regarding readability, bear in mind that, for many languages, even "one-liners" can be broken out into multiple lines. If you have a long set of conditions for the conditional ternary operator (? :), for example, it might behoove you to break it into multiple physical lines for readability:
int x = (/* some long condition */) ?
/* some long method/property name returning an int */ :
/* some long method/property name returning an int */ ;
At the end of the day, the answer is always: "It depends." Some frameworks (such as many DAL generators, EG SubSonic) almost require obscenely long one-liners to get any real work done. Othertimes, breaking that into multiple lines is quite preferable.
Given concrete examples, the community can provide better, more practical advice.
In general, I definitely don't think you should ever "squeeze" a bunch of code onto a single physical line. That doesn't just hurt legibility, it smacks of someone who has outright disdain for the maintenance programmer. As I used to teach my students: always code for the maintenance programmer, because it will often be you.
:)
Oneliners can be useful in some situations
int value = bool ? 1 : 0;
But for the most part they make the code harder to follow. I think you only should put things on one line when it is easy to follow, the intent is clear, and it won't affect debugging.
One-liners should be treated on a case-by-case basis. Sometimes it can really hurt readability and a more verbose (read: easy-to-follow) version should be used.
There are times, however when a one-liner seems more natural. Take the following:
int Total = (Something ? 1 : 2)
+ (SomethingElse ? (AnotherThing ? x : y) : z);
Or the equivalent (slightly less readable?):
int Total = Something ? 1 : 2;
Total += SomethingElse ? (AnotherThing ? x : y) : z;
IMHO, I would prefer either of the above to the following:
int Total;
if (Something)
Total = 1;
else
Total = 2;
if (SomethingElse)
if (AnotherThing)
Total += x;
else
Total += y;
else
Total += z
With the nested if-statements, I have a harder time figuring out the final result without tracing through it. The one-liner feels more like the math formula it was intended to be, and consequently easier to follow.
As far as the cool factor, there is a certain feeling of accomplishment / show-off factor in "Look Ma, I wrote a whole program in one line!". But I wouldn't use it in any context other than playing around; I certainly wouldn't want to have to go back and debug it!
Ultimately, with real (production) projects, whatever makes it easiest to understand is best. Because there will come a time that you or someone else will be looking at the code again. What they say is true: time is precious.
That's true in most cases, but in some cases where one-liners are common idioms, then it's acceptable. ? : might be an example. Closure might be another one.
No, it is annoying.
One liners can be more readable and they can be less readable. You'll have to judge from case to case.
And, of course, on the prompt one-liners rule.
VASTLY more important is developing and sticking to a consistent style.
You'll find bugs MUCH faster, be better able to share code with others, and even code faster if you merely develop and stick to a pattern.
One aspect of this is to make a decision on one-liners. Here's one example from my shop (I run a small coding department) - how we handle IFs:
Ifs shall never be all on one line if they overflow the visible line length, including any indentation.
Thou shalt never have else clauses on the same line as the if even if it comports with the line-length rule.
Develop your own style and STICK WITH IT (or, refactor all code in the same project if you change style).
.
The main drawback of "one liners" in my opinion is that it makes it hard to break on the code and debug. For example, pretend you have the following code:
a().b().c(d() + e())
If this isn't working, its hard to inspect the intermediate values. However, it's trivial to break with gdb (or whatever other tool you may be using) in the following, and check each individual variable and see precisely what is failing:
A = a();
B = A.b();
D = d();
E = e(); // here i can query A B D and E
B.C(d + e);
One rule of thumb is if you can express the concept of the one line in plain language in a very short sentence. "If it's true, set it to this, otherwise set it to that"
For a code construct where the ultimate objective of the entire structure is to decide what value to set a single variable, With appropriate formatting, it is almost always clearer to put multiple conditonals into a single statement. With multiple nested if end if elses, the overall objective, to set the variable...
" variableName = "
must be repeated in every nested clause, and the eye must read all of them to see this.. with a singlr statement, it is much clearer, and with the appropriate formatting, the complexity is more easily managed as well...
decimal cost =
usePriority? PriorityRate * weight:
useAirFreight? AirRate * weight:
crossMultRegions? MultRegionRate:
SingleRegionRate;
The prose is an easily understood one liner that works.
The cons is the concatenation of obfuscated gibberish on one line.
Generally, I'd call it a bad idea (although I do it myself on occasion) -- it strikes me as something that's done more to impress on how clever someone is than it is to make good code. "Clever tricks" of that sort are generally very bad.
That said, I personally aim to have one "idea" per line of code; if this burst of logic is easily encapsulated in a single thought, then go ahead. If you have to stop and puzzle it out a bit, best to break it up.

Resources