Why there are some many ways to create Strings in Ruby? [closed] - ruby

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I already seen this one Why are there so many slightly different ways to do the same thing in Ruby? but it doesn't help a bit. Having multiple slightly different semantics and syntax for the same thing is IMHO confusing and counterproductive. I was trying to find some spec, or rationale on why this is so, but they're nowhere to be found (unlike Java and Python where every language feature is well documented with motivation etc.).
It's not just String, it's everything. What I'm looking for is a generic explanation on why the japanese think that having 100 ways to do the same thing is better than one explicit way. Remember that we're talking about programming language, that's not a musical instrument, or a paint brush, it's a tool to get the job done and have fun along the way. It's not fun to read some code and wonder why she used %<hello kitty> instead of "hello kitty", especially when you're looking for a bug.
I see the benefit in standardization, which is a related concept. I hope everyone else does. Why doesn't Ruby support some 100 versions of customized HTTP protocol, for the same reason they support 100 ways to create a String?

The reason there's many different ways to create a string is because there's many reasons you might need a string. Since strings are the backbone of many applications, it makes sense that this facility is robust and varied.
Once you're used to it, you'll find the rigid quotation systems in other languages to be more of a nuisance than anything. HTML often requires using both single ' and double " quotes for embedded JavaScript or other attributes, and unless you want to render your string into unreadable pulp by spiking in backslashes \ before any of them you'll be better off with the %q[ ... ] type method of quoting.
Any good toolbox has a variety of tools. Don't complain that your wrench set is confusing because it has so many different sizes of wrench. Sometimes you'll need a specific one, and then you'll be grateful. Many of these methods have been borrowed from languages like Perl, and Perl is inspired by other things like bash.
Typical use cases:
double_quotes = "typical use case with #{variables}"
single_quotes = 'strict string literals'
alternate_double_quotes = %Q[<for html="tags('with both quotes', 'and #{variables}')">]
alternate_single_quotes = %q[<for html="tags('with both quotes')">]
inline_string = <<END
Useful for long blocks of freeform
text such as sample data or templates.
END
I've found that the %q[ ... ] method comes in handy when trying to express multi-line strings that contain quotes as is often the case with SQL:
execute(%q[
INSERT INTO examples (id, feature_code)
SELECT id, CONCAT('example_', feature_code)
FROM things
GROUP BY foo
ORDER BY bar
])
It is relatively easy to spot [ ... ] pairings but not as easy when you have many escaped quotes. It's easy to miss a closing quote unless you have a syntax highlighting editor.

Related

Should languages offer a syntactic alternative to method chaining? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
DOM, ThreeJS and now canvas have all had libraries written to provide method chaining (perhaps most familiar from jQuery). Chaining has also been used in core C libraries.
These fluent interfaces avoid unnecessary repetition of the object of interest. Compare:
var cx = cq(640, 480);
cx.drawImage(image, 0, 0);
cx.fillStyle("#ff0000");
cx.fillRect(64, 64, 32, 32);
cx.blur();
cx.appendTo("body");
to:
cq(640, 480)
.drawImage(image, 0, 0)
.fillStyle("#ff0000")
.fillRect(64, 64, 32, 32)
.blur()
.appendTo("body");
It could be argued that the former "traditional" style is over-verbose, and violates DRY.
To avoid repetition of the cx variable, some languages allows us to express a set of calls using a with statement:
with ( cq(640, 480) ) {
drawImage(image, 0, 0);
fillStyle("#ff0000");
fillRect(64, 64, 32, 32);
blur();
appendTo("body");
}
Whilst JavaScript's with statement is dangerous in the presence of typos, Scala's more restrictive with statement is safe to use, and Haxe also offers import of functions to the local scope through its using keyword. Unfortunately Java and C offer no such shortcut, forcing us to choose between traditional code or chaining.
Should language authors consider a safe with-like statement as an alternative to method chaining, or are there good reasons to avoid it? If such a feature is desirable, what form should it take?
One concern I have with method chaining is that the ambiguity about the subject of the later calls in the chain may prevent optimizations previously available when compiling code where repeated use of cx was explicit. For example, if the calls to cx's methods do not overlap, they could be parallelized, but it may be harder for the compiler to be sure of this in the chained example.
Another disadvantage, as rambo points out below, is that methods designed for chaining are unable to return any other value, which seems rather wasteful.
It's called Method Chaining. It frequently appears in the discussion of a Fluent Interface.
Perhaps the biggest drawback is that you cannot return a value, because you must return the implied object to allow chaining. Not all methods make sense without returning a value, and then you end up with an interface that has some chainable methods, and some not.
I don't think it indicates a missing language feature, because there's no serious loss of functionality without it. But language support for somethign like this might be interesting.
It's not a missing language feature, instead it is a language feature. If it was missing then it wouldn't be possible to do it in Javascript.
This is not syntax. Instead, it is a design pattern. And it's called chaining. In fact, there are libraries that implements chaining alone. DED|Chain for example is a library that implementes chaining for YUI2 which was not written with chaining in mind.
A specialized syntax like with (which is indeed implemented in js like you mentioned) is problematic regardless what you call it (you suggested using the name "on" but it will have all the problems that "with" has).
The problem is, inside a code block, it can be confusing to a human (the compiler is not confused) weather the method or variable refers to method of the object or if there was a typo and it accidentally refers to a global variable or a variable that is not part of the object but is in scope.
Of course, you could say that it is the job of the programmer to make sure that they don't use variable and method names that may cause confusion. In which case you can use with.

Is Ruby's `end` delimiter redundant? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Why do you need to write the end delimiter in Ruby? Can it not be interpreted from the indentation, like in Python or CoffeeScript?
class String
COLORS.each do |color,code|
define_method "in_#{color}" do
"<span style=\"color: ##{code}\">#{self}</span>"
end
end
end
Would look much better to me as
class String
COLORS.each do |color,code|
define_method "in_#{color}" do
"<span style=\"color: ##{code}\">#{self}</span>"
If not, will it be possible in the future or are there any workarounds? Is there any language that compiles into Ruby (like CoffeeScript compiles into JS)?
In Ruby spaces are not significant. So, one needs to clearly mark where block of code starts and ends.
If this looks like a syntactic overhead to you, then you should look at Python :) (I don't like it for exactly this reason: significant spaces)
The reason is just the taste of the language designers (starting from Matz). Many people just don't like indentation-based languages. Given that, it's nevertheless funny that some of those (like HAML or Coffeescript) prove to be rather successful in the greater Ruby world.
Nevertheless, Ruby itself will probably never be indentation based. If you want to use a general purpose language with that feature, you should take a look at either Coffeescript (which compiles to Javascript) or Python.
It's a language design choice. If you like space based block delimiters use Python.
I agree that it's redundant, but currently the only way around it would be to use braces instead (I'm guessing you'll agree that this is even more horrible):
class String
COLORS.each { |color,code|
define_method "in_#{color}" {
"<span style=\"color: ##{code}\">#{self}</span>" } }
end
It could be inferred from the indentation if Ruby paid attention to indentation. Most popular languages today, with Python being a big exception, don't have semantically significant indentation.
Some languages do exactly that (notably Haskell and Python) but the down-side is that it is much more awkward to normalize indentation like this as there's less redundant information. It also means that the use of tabs versus spaces would become a matter of significant holy war, as opposed to just personal preference (and discussion in the bar after work).

What are some class names that would signal a need for refactoring? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I came across a few articles like this one, which suggest that some words should never be used as part of a class name. When a class has one of those words in the name, it means the code should be refactored or redesigned.
Example:
Manager
Reason: Since almost all classes "manage" something and the meaning of "Manager" is very broad, people can put a lot of responsibilities to a "Manager" class while still being able to claim the class does "only one thing". As a result, naming a class with "Manager" does not say much about what the class actually does. The article mentioned earlier, "Naming Java Classes Without a 'Manager' ", showed this point:
For instance, take a class named "UrlManager" - you cannot tell whether it pool URLs, manipulates URLs or audits the use of them. All the name tells you is that this is not a URL, but it does somehow work with them. On the other hand, the name "UrlBuilder" gives a much better picture of what the class does.
Another example:
Helper
Reason: A class name like "ThreadHelper" makes people wonder why it's needed and why it cannot just be part of the "Thread" class. Is it actually an adapter or a decorator? If so, name it that way. Is class "Thread" taking too much responsibility already? If so, refactor and give the new class a meaningful name. "Helper" says nothing about what it's doing or how it's helping.
What are other words in a class name that would signal a need for refactoring or redesign and should be avoided? Why?
Edit: I would think those words are used a lot since
they generally have broad meanings
they can fit in almost all contexts
they stop designers thinking about better designs or names
people believe it's OK to use them
The book Clean Code listed more but no reasons were given:
Avoid words like Manager, Processor, Data, or Info in the name of a class.
It would be great if someone could provide possible reasons for them.
Related questions:
What’s the best approach to naming classes?
Utils. Check this Chris Missal's blog entry for why.
Any name that contains characters that are not 7bit ascii.
I really cannot understand or even edit Hindi characters.
class हिन्दी:হিন্দী ঠার
{
// argh..
}
My least favorite identifiers in general are:
Misspelled words. GEM had palette spelled as "pallete" in all its API calls. Maddening.
Identifiers where I can't tell if a character is a 1 or an l, or a 0 or an O.
George Carlin's seven dirty words.
Articles (The, A, An)
Pronouns and names (My, Their, John)
Numbers, except for spec versions (2, 3, 5000)
Fluffy adjectives (Fast, Smart, Good, Better)
Foreign language that the majority of the team doesn't understand (Ελληνικά)
I think this question is to be seen in the bigger picture of picking the right name for any medium. When my wife asks me to get that something from the closet, how am I supposed to know what closet she means?
Maybe objects of my class do create buttons, so why not call it a ButtonFactory? Maybe that object does manage the lifetime of temporary files, so let's call it TemporaryFileManager.
The problem arises when you don't have enough contextual information. This especially hard when creating reusable components: my TemporaryFileManager may be a subclass of a generic Manager class, and my ButtonFactory may be a special case of WidgetFactory.
As long as the name describes what the thing does in its context I'm alright. And that's what the mentioned article is about.
1) Anything less than 3 chars really gets on my nerves. It really hurts readability, since 3 chars at least usually gives you at least one vowel. Personally, I try to use at least 5 chars.
2) One pet peeve I have is class names ending in class (ex: personClass or buttonClass) since it kind of takes away from the fact that you're making an object, not a class. Making instances of a class similarly I find ok (ex: blueButton, redLabel), since it's easier to read, but the class thing can get really annoying.
Listing bad ideas could take quit awhile, just off the top of my head I could think of a lot of bad names: Reader, Writer, Factory, Item, Timer, Reciever, Sender, etc etc.
Basically, avoid names that give you no context for what the class is or its role in the bigger picture. It doesn't have to be sometime as over the top as IHelpToSendXMLDataToTheServer, but possibly XMLBroadcastUtil wouldnt be terrible. Some people even go as far as adding particular prefex, suffix to class names to designate which module it works with. However, I would argue this is part of the role of the namespace/package.
Everything suggested on How To Write Unmaintainable Code.
This
that's always a bad call.
Abstract
Template
Model
Factory
Object
These are all really generic, and some of them could be obvious from the class definition. Others are obviously better noted in a short bit of documentation (easy reference of which is one reason to like resharper)
Anything that may override standard classes (ex: Comparator, Iterable &c. in Java), unless you understand and specifically intend to cause this kind of behaviour.

Importance of commenting your code [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 14 years ago.
How do you explain your team mates the importance of commenting the code they write? I know some coders who write episodic comments while others leave a lot to be expected, what do you expect when you read comments?
There are some minimums:
All functions and classes should be commented
Try/Catch and exception handling is better to be commented
Constants hard coded in the code should be definitely
dummy objects and dummy classes, as well as TO-DO parts should be commented
When you get a code from a URL, the address should be cited in the comments for further consideration and copyright infringement problems
Also commits to the version control system should be well commented
Although comments should be kept to minimum, there is no need to comment a for loop definition when it is obvious,
I usually set ground rules for my programmers, they stick to it when it is well defined
The best comments are always concise, in a few words. It should say what's not obvious in the code. I see allot of people making obvious and therefore useless comments like:
if x==0 //if x equals 0 then...
oh really?! This is only "polluting" the code, because unless you're learning how to program, its pretty useless.
Even if the code is only yours, you should write comments as if you were about to share it with another programmer that is completely unaware of it. That way you make sure that you will always understand it, and in long term if somebody comes along and picks that code up, that person will be able to understand it and extend/use it.
I see comments as a boost of reusability. And I expect, like every other programmer, to fully understand a block of code with a single, simple and concise comment.
Write comments when you're writing code that's not intuitive. There's really no reason for commenting a method that just iterates an array, but when you fix a bug or have to hack something together to get around an issue, it's good to have a comment so you can quickly understand that code 6 months later (and not accidently undo it).
What do you mean by commenting code?
The actual code, or the function headers?
If you're actually talking about the code, it's a lost cause. You need to get them to write readable code and to break it into meaningful chunks. Commenting bad code doesn't make it into good code, it just leaves an inconsistent mess.
As for header documentation, you have to get them to capture the important things (e.g., surprises, directives) and compromise about trivial things (listing all parameters, repeating what the signature does). People hate documenting functions because most of the effort is spent writing trivial text that almost insults your intelligence (e.g., on getHandleToFile(), "this gets a handle to the file"). Since there are actually a lot less important details than one would expect, they'd be pleasantly surprised and would be more likely to invest the effort in those specific situations.
I think if you are writing code that others may someday have to follow, then it is prudent to leave good comments about what things are doing. If you are just writing something for yourself, the tendency is strong to leave minimal or none at all. That being said, I have had the "not so luxury" of having to go back to code I wrote 8 years ago and didn't comment adequately, in a language I don't use anymore (class ASP) and I can tell you, I wish I had left more comments!
I try to comment most of my public methods and classes, and in those comments you can read what the method does, what the meaning of the parameters is, and, if applicable, what the output will be.
I also sometimes put comments inside my methods, but, there I do not comment what I'm doing, but why I am doing it like that.
if the language you are writing in is not human readable, i suggest very granular method and procedure level comments.
if the language you are writing is human readable (C#, VB, etc..) i suggest that you use somewhat detailed comments at the method level and minimal comments at the procedure level.
Include comments for document generation on methods and classes.
Don't comment every line.
If you are doing something expected or that is not obvious from the code, explain why in comments.
The most important thing to do in commenting is to tell the truth. The number of times I've been investigating a bug only to find a section of code that is "less than obvious" along with a comment that says it's supposed to do the opposite to what it is doing. Who wins? You decide...
On a related note, any comment that is longer than the section it is documenting is normally too long.

What are your language "hangups"? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I've read some of the recent language vs. language questions with interest... Perl vs. Python, Python vs. Java, Can one language be better than another?
One thing I've noticed is that a lot of us have very superficial reasons for disliking languages. We notice these things at first glance and they turn us off. We shun what are probably perfectly good languages as a result of features that we'd probably learn to love or ignore in 2 seconds if we bothered.
Well, I'm as guilty as the next guy, if not more. Here goes:
Ruby: All the Ruby example code I see uses the puts command, and that's a sort of childish Yiddish anatomical term. So as a result, I can't take Ruby code seriously even though I should.
Python: The first time I saw it, I smirked at the whole significant whitespace thing. I avoided it for the next several years. Now I hardly use anything else.
Java: I don't like identifiersThatLookLikeThis. I'm not sure why exactly.
Lisp: I have trouble with all the parentheses. Things of different importance and purpose (function declarations, variable assignments, etc.) are not syntactically differentiated and I'm too lazy to learn what's what.
Fortran: uppercase everything hurts my eyes. I know modern code doesn't have to be written like that, but most example code is...
Visual Basic: it bugs me that Dim is used to declare variables, since I remember the good ol' days of GW-BASIC when it was only used to dimension arrays.
What languages did look right to me at first glance? Perl, C, QBasic, JavaScript, assembly language, BASH shell, FORTH.
Okay, now that I've aired my dirty laundry... I want to hear yours. What are your language hangups? What superficial features bother you? How have you gotten over them?
I hate Hate HATE "End Function" and "End IF" and "If... Then" parts of VB. I would much rather see a curly bracket instead.
PHP's function name inconsistencies.
// common parameters back-to-front
in_array(needle, haystack);
strpos(haystack, needle);
// _ to separate words, or not?
filesize();
file_exists;
// super globals prefix?
$GLOBALS;
$_POST;
I never really liked the keywords spelled backwards in some scripting shells
if-then-fi is bad enough, but case-in-esac is just getting silly
I just thought of another... I hate the mostly-meaningless URLs used in XML to define namespaces, e.g. xmlns="http://purl.org/rss/1.0/"
Pascal's Begin and End. Too verbose, not subject to bracket matching, and worse, there isn't a Begin for every End, eg.
Type foo = Record
// ...
end;
Although I'm mainly a PHP developer, I dislike languages that don't let me do enough things inline. E.g.:
$x = returnsArray();
$x[1];
instead of
returnsArray()[1];
or
function sort($a, $b) {
return $a < $b;
}
usort($array, 'sort');
instead of
usort($array, function($a, $b) { return $a < $b; });
I like object-oriented style. So it bugs me in Python to see len(str) to get the length of a string, or splitting strings like split(str, "|") in another language. That is fine in C; it doesn't have objects. But Python, D, etc. do have objects and use obj.method() other places. (I still think Python is a great language.)
Inconsistency is another big one for me. I do not like inconsistent naming in the same library: length(), size(), getLength(), getlength(), toUTFindex() (why not toUtfIndex?), Constant, CONSTANT, etc.
The long names in .NET bother me sometimes. Can't they shorten DataGridViewCellContextMenuStripNeededEventArgs somehow? What about ListViewVirtualItemsSelectionRangeChangedEventArgs?
And I hate deep directory trees. If a library/project has a 5 level deep directory tree, I'm going to have trouble with it.
C and C++'s syntax is a bit quirky. They reuse operators for different things. You're probably so used to it that you don't think about it (nor do I), but consider how many meanings parentheses have:
int main() // function declaration / definition
printf("hello") // function call
(int)x // type cast
2*(7+8) // override precedence
int (*)(int) // function pointer
int x(3) // initializer
if (condition) // special part of syntax of if, while, for, switch
And if in C++ you saw
foo<bar>(baz(),baaz)
you couldn't know the meaning without the definition of foo and bar.
the < and > might be a template instantiation, or might be less-than and greater-than (unusual but legal)
the () might be a function call, or might be just surrounding the comma operator (ie. perform baz() for size-effects, then return baaz).
The silly thing is that other languages have copied some of these characteristics!
Java, and its checked exceptions. I left Java for a while, dwelling in the .NET world, then recently came back.
It feels like, sometimes, my throws clause is more voluminous than my method content.
There's nothing in the world I hate more than php.
Variables with $, that's one extra odd character for every variable.
Members are accessed with -> for no apparent reason, one extra character for every member access.
A freakshow of language really.
No namespaces.
Strings are concatenated with ..
A freakshow of language.
All the []s and #s in Objective C. Their use is so different from the underlying C's native syntax that the first time I saw them it gave the impression that all the object-orientation had been clumsily bolted on as an afterthought.
I abhor the boiler plate verbosity of Java.
writing getters and setters for properties
checked exception handling and all the verbiage that implies
long lists of imports
Those, in connection with the Java convention of using veryLongVariableNames, sometimes have me thinking I'm back in the 80's, writing IDENTIFICATION DIVISION. at the top of my programs.
Hint: If you can automate the generation of part of your code in your IDE, that's a good hint that you're producing boilerplate code. With automated tools, it's not a problem to write, but it's a hindrance every time someone has to read that code - which is more often.
While I think it goes a bit overboard on type bureaucracy, Scala has successfully addressed some of these concerns.
Coding Style inconsistencies in team projects.
I'm working on a large team project where some contributors have used 4 spaces instead of the tab character.
Working with their code can be very annoying - I like to keep my code clean and with a consistent style.
It's bad enough when you use different standards for different languages, but in a web project with HTML, CSS, Javascript, PHP and MySQL, that's 5 languages, 5 different styles, and multiplied by the number of people working on the project.
I'd love to re-format my co-workers code when I need to fix something, but then the repository would think I changed every line of their code.
It irritates me sometimes how people expect there to be one language for all jobs. Depending on the task you are doing, each language has its advantages and disadvantages. I like the C-based syntax languages because it's what I'm most used to and I like the flexibility they tend to bestow on the developer. Of course, with great power comes great responsibility, and having the power to write 150 line LINQ statements doesn't mean you should.
I love the inline XML in the latest version of VB.NET although I don't like working with VB mainly because I find the IDE less helpful than the IDE for C#.
If Microsoft had to invent yet another C++-like language in C# why didn't they correct Java's mistake and implement support for RAII?
Case sensitivity.
What kinda hangover do you need to think that differentiating two identifiers solely by caSE is a great idea?
I hate semi-colons. I find they add a lot of noise and you rarely need to put two statements on a line. I prefer the style of Python and other languages... end of line is end of a statement.
Any language that can't fully decide if Arrays/Loop/string character indexes are zero based or one based.
I personally prefer zero based, but any language that mixes the two, or lets you "configure" which is used can drive you bonkers. (Apache Velocity - I'm looking in your direction!)
snip from the VTL reference (default is 1, but you can set it to 0):
# Default starting value of the loop
# counter variable reference.
directive.foreach.counter.initial.value = 1
(try merging 2 projects that used different counter schemes - ugh!)
In no particular order...
OCaml
Tuples definitions use * to separate items rather than ,. So, ("Juliet", 23, true) has the type (string * int * bool).
For being such an awesome language, the documentation has this haunting comment on threads: "The threads library is implemented by time-sharing on a single processor. It will not take advantage of multi-processor machines. Using this library will therefore never make programs run faster." JoCaml doesn't fix this problem.
^^^ I've heard the Jane Street guys were working to add concurrent GC and multi-core threads to OCaml, but I don't know how successful they've been. I can't imagine a language without multi-core threads and GC surviving very long.
No easy way to explore modules in the toplevel. Sure, you can write module q = List;; and the toplevel will happily print out the module definition, but that just seems hacky.
C#
Lousy type inference. Beyond the most trivial expressions, I have to give types to generic functions.
All the LINQ code I ever read uses method syntax, x.Where(item => ...).OrderBy(item => ...). No one ever uses expression syntax, from item in x where ... orderby ... select. Between you and me, I think expression syntax is silly, if for no other reason than that it looks "foreign" against the backdrop of all other C# and VB.NET code.
LINQ
Every other language uses the industry standard names are Map, Fold/Reduce/Inject, and Filter. LINQ has to be different and uses Select, Aggregate, and Where.
Functional Programming
Monads are mystifying. Having seen the Parser monad, Maybe monad, State, and List monads, I can understand perfectly how the code works; however, as a general design pattern, I can't seem to look at problems and say "hey, I bet a monad would fit perfect here".
Ruby
GRRRRAAAAAAAH!!!!! I mean... seriously.
VB
Module Hangups
Dim _juliet as String = "Too Wordy!"
Public Property Juliet() as String
Get
Return _juliet
End Get
Set (ByVal value as String)
_juliet = value
End Set
End Property
End Module
And setter declarations are the bane of my existence. Alright, so I change the data type of my property -- now I need to change the data type in my setter too? Why doesn't VB borrow from C# and simply incorporate an implicit variable called value?
.NET Framework
I personally like Java casing convention: classes are PascalCase, methods and properties are camelCase.
In C/C++, it annoys me how there are different ways of writing the same code.
e.g.
if (condition)
{
callSomeConditionalMethod();
}
callSomeOtherMethod();
vs.
if (condition)
callSomeConditionalMethod();
callSomeOtherMethod();
equate to the same thing, but different people have different styles. I wish the original standard was more strict about making a decision about this, so we wouldn't have this ambiguity. It leads to arguments and disagreements in code reviews!
I found Perl's use of "defined" and "undefined" values to be so useful that I have trouble using scripting languages without it.
Perl:
($lastname, $firstname, $rest) = split(' ', $fullname);
This statement performs well no matter how many words are in $fullname. Try it in Python, and it explodes if $fullname doesn't contain exactly three words.
SQL, they say you should not use cursors and when you do, you really understand why...
its so heavy going!
DECLARE mycurse CURSOR LOCAL FAST_FORWARD READ_ONLY
FOR
SELECT field1, field2, fieldN FROM atable
OPEN mycurse
FETCH NEXT FROM mycurse INTO #Var1, #Var2, #VarN
WHILE ##fetch_status = 0
BEGIN
-- do something really clever...
FETCH NEXT FROM mycurse INTO #Var1, #Var2, #VarN
END
CLOSE mycurse
DEALLOCATE mycurse
Although I program primarily in python, It irks me endlessly that lambda body's must be expressions.
I'm still wrapping my brain around JavaScript, and as a whole, Its mostly acceptable. Why is it so hard to create a namespace. In TCL they're just ugly, but in JavaScript, it's actually a rigmarole AND completely unreadable.
In SQL how come everything is just one, huge freekin SELECT statement.
In Ruby, I very strongly dislike how methods do not require self. to be called on current instance, but properties do (otherwise they will clash with locals); i.e.:
def foo()
123
end
def foo=(x)
end
def bar()
x = foo() # okay, same as self.foo()
x = foo # not okay, reads unassigned local variable foo
foo = 123 # not okay, assigns local variable foo
end
To my mind, it's very inconsistent. I'd rather prefer to either always require self. in all cases, or to have a sigil for locals.
Java's packages. I find them complex, more so because I am not a corporation.
I vastly prefer namespaces. I'll get over it, of course - I'm playing with the Android SDK, and Eclipse removes a lot of the pain. I've never had a machine that could run it interactively before, and now I do I'm very impressed.
Prolog's if-then-else syntax.
x -> y ; z
The problem is that ";" is the "or" operator, so the above looks like "x implies y or z".
Java
Generics (Java version of templates) are limited. I can not call methods of the class and I can not create instances of the class. Generics are used by containers, but I can use containers of instances of Object.
No multiple inheritance. If a multiple inheritance use does not lead to diamond problem, it should be allowed. It should allow to write a default implementation of interface methods, a example of problem: the interface MouseListener has 5 methods, one for each event. If I want to handle just one of them, I have to implement the 4 other methods as an empty method.
It does not allow to choose to manually manage memory of some objects.
Java API uses complex combination of classes to do simple tasks. Example, if I want to read from a file, I have to use many classes (FileReader, FileInputStream).
Python
Indentation is part of syntax, I prefer to use the word "end" to indicate end of block and the word "pass" would not be needed.
In classes, the word "self" should not be needed as argument of functions.
C++
Headers are the worst problem. I have to list the functions in a header file and implement them in a cpp file. It can not hide dependencies of a class. If a class A uses the class B privately as a field, if I include the header of A, the header of B will be included too.
Strings and arrays came from C, they do not provide a length field. It is difficult to control if std::string and std::vector will use stack or heap. I have to use pointers with std::string and std::vector if I want to use assignment, pass as argument to a function or return it, because its "=" operator will copy entire structure.
I can not control the constructor and destructor. It is difficult to create an array of objects without a default constructor or choose what constructor to use with if and switch statements.
In most languages, file access. VB.NET is the only language so far where file access makes any sense to me. I do not understand why if I want to check if a file exists, I should use File.exists("") or something similar instead of creating a file object (actually FileInfo in VB.NET) and asking if it exists. And then if I want to open it, I ask it to open: (assuming a FileInfo object called fi) fi.OpenRead, for example. Returns a stream. Nice. Exactly what I wanted. If I want to move a file, fi.MoveTo. I can also do fi.CopyTo. What is this nonsense about not making files full-fledged objects in most languages? Also, if I want to iterate through the files in a directory, I can just create the directory object and call .GetFiles. Or I can do .GetDirectories, and I get a whole new set of DirectoryInfo objects to play with.
Admittedly, Java has some of this file stuff, but this nonsense of having to have a whole object to tell it how to list files is just silly.
Also, I hate ::, ->, => and all other multi-character operators except for <= and >= (and maybe -- and ++).
[Disclaimer: i only have a passing familiarity with VB, so take my comments with a grain of salt]
I Hate How Every Keyword In VB Is Capitalized Like This. I saw a blog post the other week (month?) about someone who tried writing VB code without any capital letters (they did something to a compiler that would let them compile VB code like that), and the language looked much nicer!
My big hangup is MATLAB's syntax. I use it, and there are things I like about it, but it has so many annoying quirks. Let's see.
Matrices are indexed with parentheses. So if you see something like Image(350,260), you have no clue from that whether we're getting an element from the Image matrix, or if we're calling some function called Image and passing arguments to it.
Scope is insane. I seem to recall that for loop index variables stay in scope after the loop ends.
If you forget to stick a semicolon after an assignment, the value will be dumped to standard output.
You may have one function per file. This proves to be very annoying for organizing one's work.
I'm sure I could come up with more if I thought about it.

Resources