Going from C# to Java [closed] - c#

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 9 years ago.
I've been working with C# and more generally the .Net framework for a couple of years now. I often heard about the similarity between C# & the Java language and would like to learn more about the second one.
Have you got any specific advice to learn Java when coming from C# ?
Any common errors a C# programmer would do when starting Java ?
Any documentation showing the habits you can keep and the ones you must change (still in a C# to Java optic, so something a bit more specific then a C# vs Java comparison) ?

Well, while C# and Java are superficially alike there are a number of small differences that might bite you. Generally I think the opposite direction—going from Java to C#—is less problematic. This is mainly due to C# being a more complex language so you might find many simplifications from common Java patterns but the other way around might be a little painful.
Things to look out for (partial list, not guaranteed to be exhaustive):
Different ...
Naming conventions. In Java only type names start with a capital letter (i. e. PascalCase), everything else uses camelCase. Not very hard to adhere to, though.
Also interfaces generally don't start with I. On the other hand you have to implement them with a different keyword. Doesn't really help in the middle of the code, though.
Class library :-)
While obvious, this has been the thing I spent most time on when learning a language. When dealing with a known paradigm the syntax differences are quickly sorted out, but getting to know the standard library / class library / framework takes some time in some cases :-)
Patterns. Well, not quite, it's still the same stuff. But C# supports some patterns at the language level, while you still have to implement them yourself in Java. No events, but the Observer pattern (very prevalent in Swing—whenever you see a Listener, you know what to do :-))
Exception handling. Java has so-called checked exceptions which means that an exception must either be caught or declared upwards. Usually this means that you have
catch (SomeException ex) {
ex.printStackTrace();
}
pretty often in your code1 :-)
Types. While .NET has normal objects and value types, they both are objects and support methods, properties, &c. Java has a dichotomy of primitive types, such as int, float, char, &c. and classes such as String. Doesn't matter much since they implemented auto-boxing, but sometimes it's still annoying to wrap int in Integer.
Polymorphism: All Java methods are virtual by default whereas c# methods are not.
Minor syntactic differences.
foreach (a in b) → for (a : b)
Different access keywords. Things like internal and protected internal don't exist. But unqualified members are visible to other classes in the same package (sort of internal, but then again not quite).
String comparison isn't done with == in Java. You have to use .equals(). While in C# == on strings is value equality, in Java == is always reference equality.
No ...
Properties. In Java this is generally done with the Foo getFoo()/void setFoo(Foo foo) pattern which C# generates silently behind your back when using properties but you have to do it explicitly in Java. Generally, to keep the language itself simpler many things in Java are just conventions. Still, most of the time you're better off adhering to them :-)
Operator overloading. Deemed a hazard to the righteous programmer they weren't implemented for fear of abuse. Don't need them too often anyway, not even in C#, but sometimes they are nice and then you're missing something.
Indexers. You always have to access list items through myList.get(5) instead of the array-like syntax myList[5]. Just a mild inconvenience, though.
LINQ (though there exist implementations2 but it's not as nicely integrated), or lambda functions3 (no delegates anyway, but anonymous classes), extension methods, or partial classes (yes, that's a painful one when dealing with Swing, unless you're very disciplined), and a few more things.
Multidimensional arrays. You can use jagged arrays (arrays of arrays), buttrue multidimensionality isn't there.
Generics are compile-time only, at runtime only Objects remain. Also wildcards in generics can be hard to resolve sometimes when the compiler complains about all of the four ? in your generics having different types. (Though to be fair: That was a case where I would have needed type information at runtime anyway so I reverted back to Objects).
General advice: Grab a friend with Java experience and let him glance over your code. While he probably can't tell you everything you should take care of when you directly ask him that question, he can spot strange things in code just fine and notify you of that. This has greatly helped me learning Java (although I learned Java first and then C#, so it might be different).
1 Yes, I know many catch blocks look different, but still, this is probably the archetypical one and not even that rare.
2 Quaere, JaQue, JaQu, Querydsl
3 There's lambdaj, though. Thanks for pointing that out, Esko.

I honestly think the biggest hurdle for many C# developers trying to learn Java is learning a new IDE. Visual Studio is great, and when you're coding in C# for a long period of time, you get used to it. When having to move over to Eclipse or Netbeans, you suddenly feel lost. How do I set a breakpoint? Where's the immediate window? How do I create a windows app? etc etc... I know this sounds crazy, but I'm telling you, people get very attached to their IDE's and have a tough time getting used to new ones...

Languages themselves are pretty similar, sans few keywords and Java lacking some features C# programmers got used to (properties, using, reified (non-type-erased) generics).
The main problem here is knowledge of frameworks, of which there are thousands for Java.

The main language is fine. Getting to know the libraries will be one thing which takes time. If you're doing web-applications, there is a LOT to learn... equivalent technologies to WCF and ASP.net.
You don't say what kind of area you work in... desktop, server, or web-server?

Biggest difference between C# and Java : In Java, all methods are virtual. Hence the reason why tools such as NUnit and such came from the Java world.

To be honest, if you're a competent C# programmer I don't believe there's much you do need to know apart from packaging and deployment of applications.
Here's a good link http://en.wikipedia.org/wiki/Comparison_of_Java_and_C_Sharp

The biggest thing you need to learn is how to Greenspun C#'s functional style features in Java. For example, you can expect to make a lot of interfaces with only one method to get around Java's lack of lambda functions and delegates.

I honestly recommend Java in a Nutshell. Most Java/any_other_lang introduction books are for totally novice readers explaining the concept of a loop for pages and recursion for a chapter... You can start writing Java programs within two days with this book. Of course it will take you a long time to understand what is going on under the hood and how to use all the available framework. But once the language itself is mastered, it is easy to get along even with google only resources.

Although, this is the other way around, I found the following link to be quite useful for comparing Java and C#.
C# From a Java Developer's Perspective

I made a transition from Java to C# and back to Java again. I think syntactically they are very similar and most of the trouble I had was learning the .NET APIs and learning how to use them effectively. Many times I was using 'syntactic sugar', writing my code as if it was in Java and then translating it to C#. I spent a lot of time on Microsoft's website reading and learning about the APIs which was a huge help.

Related

VB.NET for a C# Developer

I may be starting a new job which requires VB.NET but I am a C# developer and even though I may be able to understand the code, writing it from scratch seems to be a hassle for me for a while.
There are C#>VB.NET converter out there (online) and where you paste your C# code and it converts it into VB.NET code. My question is whether there is any person who experienced this and whether it is a good temp solution or I am gonna experience so much difficulties with that? Do they convert good?
And probably I am gonna run the codes on Asp.net.
An example converter: http://www.developerfusion.com/tools/convert/csharp-to-vb/
Thanks in advance.
Don't use converters - learn VB.NET and the differences between its syntax and C#.
There is a very good comparison cheat sheet here to get you started.
In practice, you will find that most of the time you are interacting with familiar .NET objects in the same way and you only have some syntax differences (though generics and delegate syntax are such a pain that one tends to shy away from them).
Microsoft has stated that they are trying to bring both language to feature parity, so anything you can do in C#, you should be able to do with VB.NET (with minor differences normally).
Update - don't forget that compiled code (in assemblies) should work identically in both languages (assuming CLS compliance), so you could write a library in C# for use with VB.NET and vice versa.
You can try the Telerik Code Converter
That being said, it would be a valuable exercise to convert the code manually. You'll gain a good amount of experience by doing a manual conversion and you'll learn some of the key differences between the 2 languages that may help you going forward.
I'd say your code will work, but you'll miss some special features for which there is no C# equivalent and which would make your code fit better with the language. Some examples:
In C#, you assign event handlers with +=, which will be translated to AddHandler. In VB, however, it's much more common to use WithEvents instance variables. This is especially relevant for ASP.NET, where C# often uses the AutoEventWireup feature, which done in VB through WithEvents instead.
In C#, you access XML through LINQ to XML method calls, which will be translated to the matching method calls in VB. However, in VB, it's more natural to use the integrated language support for XML.
This is good for converting the bulk of your code, but it's not a total solution. One thing you will have issues with is the converter knowing what to do with C#'s indexer brackets ([]) vs. method parentheses (()). VB uses parenthesis for indexers and methods and there's no way for it to know which to use.
I've gone through conversion hell with these things and finally decided that they were just too much trouble and that it was much easier to just convert it by hand. I come from a VB background, so this wasn't a huge deal for me.
For what you want to do, though, you need to learn VB.NET syntax. Writing everything in C# and converting it to VB.NET is not a good, long-term solution. You will eventually have to learn VB.NET. Your manager(s) will not be keen to the fact that you're not learning the core fundamentals of the language you were hire to program in.
Don't do it... There are converters, but you will find that once you learn the key differences that you will be fine. You will interact with the .NET libraries in the same way so much of the programming will be the same.
I just changed jobs recently and went the opposite direction. I'm glad I took the time to learn C#. Major dividends in the end and you'll be more versatile.

How to prepare for a Java evaluation from a C# programmer's point of view?

I've been offered to be dispensed of classes in computer science in college, as the teacher noticed I obviously knew the introduction to coding. I'm extremely fluent in C# and with most programming concepts, so the exam shouldn't be so hard. I can also code in other languages such as C++, C, Lua, PHP, VB, etc.
I'm not caring about passing or not, my point is rather that this exam will be my only grade for the term. Therefore I'd like to get it right.
Let's assume I have ~2 weeks to prepare, I'd like to know where to start from. I obviously don't need to learn any concept (i.e. what is a variable, how to use classes, what is inheritance, etc.), since these are the same in most languages (or in that case, C# and Java).
I'd assume I have to get familiar with the slight syntax changes (string -> String, bool -> boolean) and system differences (i.e. Scanner for input, imports vs usings).
I've found the following page for most syntax changes:
http://it.toolbox.com/blogs/codesharp/java-for-c-developers-21248
From what I know, the test will variables and values, basic operators, logical structures (i.e. if/else, for, while), functions and structs. As far as I can remember, classes aren't seen this term.
I was interested in knowing what tips the S/O community could give me. Thanks in advance!
Well, first it really depends on the difficulty of your exam. You could have an exam on general POO in java or on more specific points, like generics, Collections, Threads.
And a thing you need to see, it the way the inheritance works in java. Methods inheritance isn't really working the same way.
Resources :
A comparison of Microsoft's C# programming language to Sun Microsystems' Java programming language
This is just one of many examples, yet one of the biggest for me was creating getters/setters in Java compared to C#. C# has very nice shortcuts which you are probably use to.
Public string ExampleString { get; set; }
With Java you have to create methods instead.
private string _exampleString;
public string getExampleString()
{
return _exampleString;
}
public void setExampleString(string exampleString)
{
_exampleString = exampleString;
}
This is fundamentally the same way C# handles it, but you do not have the shortcut in Java. Ultimately to learn and get use to the differences your going to have to bite the bullet and write quite a few test programs. Especially if you need to know/understand Java UI, such as swing. Which I had to write my final project in swing when I took Java in school.
Code in Java? Sounds easy, but it is, basically try doing a few "basic" things in java, IE make a linked list, some data structures.
Try to code in Java, create something simple that you have already created in C# and than come to SO if you have any questions or queries and learn from the answers. I would suggest practicing would be of great help.
To get the feeling of programming in the language I would suggest Project Euler, which requires you to write solutions to smallish programming problems.
The best way to learn is to write programs, and you need to practice a lot to prepare.
If you are allowed to use eclipse or netbeans as part of the evaluation then the most important thing you could do is get used to using those tools. Either of those could have you coding productively in Java within the hour because they will advise you on syntax issues and give you lists of choices so you don't have to look things up so often.
For instance, what is the method to grab a sub-chunk of a string. If you have an object of class "String" and hit strObject.(ctrl-space) it will give you a list of all the methods on string along with the parameter numbers and types. Oh and it will give you all the docs for this method as well.
If not, I'd get used to the JDK description on the Java website, you'll be using it more than Java syntax itself.
As for the Syntax, Java is pretty straight-forward. If you are coding in a GUI it will probably just fix your syntax for you.
If it's an in-class written (non-code) test, you may have to get used to some little differences like public/protected/private/package indications (package is the trickiest).
Code some stuff, use Eclipse.
NB: Generics are hell in Java. Using a library that is "generified" correctly is simple, but coding generic classes and methods are often rather intense.

What Python features will excite the interest of a C# developer? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
For someone who’s been happily programming in C# for quite some time now and planning to learn a new language I find the Python community more closely knit than many others.
Personally dynamic typing puts me off, but I am fascinated by the way the Python community rallies around it. There are a lot of other things I expect I would miss in Python (LINQ, expression trees, etc.)
What are the good things about Python that developers love? Stuff that’ll excite me more than C#.
For me its the flexibility and elegance, but there are a handful of things I wish could be pulled in from other languages though (better threading, more robust expressions).
In typical I can write a little bit of code in python and do a lot more than the same amount of lines in many other languages. Also, in python code form is of utmost importance and the syntax lends its self to highly readable, clean looking code. That of course helps out with maintenance.
I love having a command line interpreter that I can quickly prototype an algorithm in rather than having to start up a new project, code, compile, test, repeat. Not to mention the fact I can use it to help me automate my server maintenance as well (I double as a SA for my company).
The last thing that comes to mind immediately is the vast amounts of libraries. There are a lot of things already solved out there, the built-in library has a lot to offer, and the third party ones are many times very good (not always though).
Being able to type in some code and get the result back immediately.
(Disclaimer: I use both C# and Python regularly, and I think both have their good and bad points.)
I'm primarily .NET developer and using Python for me personal projects.
What are the good things about python that developers love?
I can say for myself - Python is like a breath of fresh air.
1) It's simple to learn, took about a week for me in the evenings. I'm saying about Python + Django. Python syntax is quite simple.
2) It's simple to use. No troubles installing Python + Django on Windows at all.
3) It can be run on Windows and UNIX.
4) I need it for web, so I get cheaper hosting than ASP.NET.
5) All the advantages of Python language over C#. Like tuples - so useful!
The only thing I don't like is that my favorite IDE Visual Studio doesn't support it (I know about IronPython, don't you worry).
I'm a very heavy user of both C# and Python; I've built very complicated applications in both languages, and I've also embedded Python scripting in my major C# application. I'm not using either to do much in the way of web work right now, but other than that I feel like I'm pretty qualified to answer the question.
The things about Python that excite me, in particular:
The deep integration of generators into the language. This was the first thing that made me realize that I needed to take a long, serious look at Python. My appreciation for this has deepened considerably since I've become conversant with the itertools module, which looks like a nifty set of tools but is in fact a new way of life.
The coupling of dynamic typing and the fact that everything's an object makes pretty sophisticated techniques extremely simple to implement. It's so easy to replace logic with tables in Python (e.g. o = class_map[k]() instead of if k='foo': o = Foo()) that it becomes a basic technique. It's so normal in Python to write methods that take methods as parameters that you don't raise an eyebrow when you see d = defaultdict(list).
zip, and the methods that are designed with it in mind. It takes a while before you can intuitively grasp what dict(zip(k, v)) and d.update(zip(k, v)) are doing, but it's a paradigm-shifting moment when you get there. An entire universe of uninteresting and potentially error-laden code eliminated, just by using one function. Then you start designing functions and classes with the expectation that they'll be used in conjunction with zip, and suddenly your code gets simpler and easier. (Protip: Or itertools.izip. Or itertools.izip_longest.)
Speaking of dictionaries, the way that they're deeply integrated into the language. Understanding what a line of code like self.__dict__.update(**kwargs) does is another one of those paradigm-shifting moments.
List comprehensions and generator expressions, of course.
Inexpensive exceptions.
An interactive intepreter.
Function decorators.
IronPython, which is so much simpler to use than we have any right to expect.
And that's without even getting into the remarkable array of functionality in the standard modules, or the ridiculous bounty of third-party tools like BeautifulSoup or SQL Alchemy or Pylons.
One of the most direct benefits that I've gotten from getting deeply into Python is that it has greatly improved my C# code. I could generally understand code that had a variable of type Dictionary<string, Action<Foo>> in it, but it didn't seem natural to write it. (I use static dictionaries to replace hard-coded logic far more frequently today than I did a year ago.) I have no difficulty understanding what LINQ is doing now, or how IEnumerable<T> and return yield work.
So what don't I like about Python?
Dynamic typing really limits what you can do with static code analysis. Not only isn't there a tool like Resharper for Python, in a language where it's possible to write getattr(x, y)() there really can't be.
It has a bunch of inelegant conventions. How I would love to be able to go back in time and try to talk GVR out of the idea that lambda expressions should be introduced with the word lambda - it's pretty damning that something as fundamental as lambda expressions should be more concise in C# than they are in Python. The leading and trailing double-underscore convention is horrible, and the fact that people mutely acquiesce to it is testimony to Dostoevsky's observation that man is the animal who can get used to anything. And don't get me started on the fact that a module with the name of StringIO was allowed to get out the door.
Some of the features that make Python work on multiple platforms also make it kind of baffling. It's easy to use import, but it's really not easy to understand what the hell it's actually doing. (Where is it looking? What does __init__.py do? Etc.)
The amazingly rich library of standard modules is so amazingly rich that it's hard to know what's in it. It's often easier to write a function than it is to find out whether or not there's something in the standard library that does the same thing - I'm looking at you, itertools.chain.
Your question is kind of like a plumber asking why carpenters are always going on and on about hammers. After all the plumber doesn't have a hammer and has never missed it. Python (even IronPython) and C# target different types of developers and different types of programs. I am very comfortable in Python and enjoy the freedom to focus on the business rules without being distracted by the syntax requirements of the language. On the other hand I have written some fairly substantial code in C# and would be very concerned about the lack of type safety had I taken on the same task in Python. This is not to say that Python is a "toy" language. You can (and people have) write a complete medium or large application in Python. You have the freedom of dynamic typing, but you also have the responsibility to keep it all straight (frameworks help here). Similarly you can write a small application in C#, but you will bring along some overhead you do not likely need.
So if the problem is a nail use a hammer, if the problem is a screw use a screw driver. In other words spend some time to learn Python, get to know it's streangths (text processing, quick coding cycles, simple clean code, etc) and then when you are looking at tackling a new problem ask whether you would be better off in Python or C#. One thing is certain. So long as C# is the only programming language you know, it is the only one you will ever use.
Pat O
My language of choice is C#, and I didn't quite see the point for me to learn Python so far. This talk from PDC09 really piqued my interest: the guy demonstrates how you can use IronPython (or IronRuby) to make a C# app scriptable (in his demo, drop a Python script in a text box, and it works with/extends your C# code). I found this really fascinating: I don't even know where I would start to do something similar in C#, and this made me at least appreciate that it brings something different to the table, which could really enrich what I can develop!
I'm an asymmetrical user of both languages, in a sense that I use C# mostly professionally and Python for all my "fun" projects (not that work is never fun, but... you know...)
This difference of context may skew my perspective, including my opinion that they are two distinct types (pun intended) of languages for, generally, distinct purposes.
This said, it may not be a coincidence that Python is, at this point in time, [one of?] the languages of choice for all kinds of cutting edge, somewhat scholarly, technology/science oriented projects. (And BTW, this "scholarly" keyword here doesNOT imply, that Python is a university toy, plenty of "serious" applications in plenty of domains/industry are proof to the contrary). This may be due to several factors:
(I don't develop most points, readily well expressed in other responses)
the openness and quasi universal availability of Python (unlike C# !)
the lightweight / ease of use / low learning curve
the extensive, high quality, "standard" library and the extensiver (and occasionally bum quality, but on the whole available, open-sourced, etc.) additional library.
the wide array of open source projects in Python language
the relative ease to bind with C/C++ for reusing legacy code, but also for placing performance-critical portions of a project
the generally higher level of abstraction of may constructs of the language
the multi-paradigms (imperative, object oriented and functional)
the availability of practitioners in so many domain of science and technology
and, yes, the
"herd mentality effect" mentioned in a remark, possibly in a [self?] deriding way. The fact that a language attracts a broad, "closely knit" community, makes it attractive too, beyond the superficial ("look cool" and such) traits of herd mentality. Put in broader context, sometimes the best technology/language to use is not measured on the its intrinsic merits but on the overall "picture", including the user community.
I like all stuff with [] and {}. Selectors like this [-1:1]. Possibility to write less code, but more something meaningfull, that gives to write Models and other declarative things very DRY.
Like any programming language, it is just a tool in the box or a brush by which you may paint your creation. Any creative endeavour requires that the artist loves the tools he uses; otherwise, the outcome suffers. Some people like Python for the same reason others love Perl. Incidentally, I have found that most Python lovers loathe Perl's flexible and expressive syntax. As a Perl lover, I don't hate Python, but consider it to be overly structured and restrictive.
If you ask me, all of these throngs of people who seem to love Python were silently suffering under the tool choices before Python came into being. Some suffered under Perl, others under something else. In other words, I believe that when Python came along, it found a large group of silent sufferers longing for a tool like Python.
I can't program in Python because I can't "think" in Python. I can "think" in Perl, therefore, it is the tool I prefer. The silently suffering mass of, now, Python users seem to have found some long lost salvation. Now if they could only keep their evangelism to themselves :).
If you are familiar with the .NET CLR and prefer a statically-typed language, but you like Python's lightweight syntax, then perhaps Boo is the language for you.
Don't get me wrong, I am and will always be a devoted fan of C#.
But sometimes there are things I can't do in C#. lthough C# keeps reducing those gaps, Python is still the language I go to to fill them.
It's dynamic, flexible, powerful, and clean. Lovely language. Whenever I need to script or build dynamic or functional (as in functional programming) software, I go Python.
For me Python is the most elegant language I've used. The syntax is minimalist (significantly less punctuation than most) and intentionally modeled after the psuedo-code conventions which are ubiquitously used by programmer to outline their intentions.
Python's if __name__ == '__main__': suite encourages re-use and test driven development.
For example, the night before last I hacked together to run thousands of ssh jobs (with about 100 concurrently) and gather up all the results (output, error messages, exit values) ... and record the time take on each. It also handles timeouts (An ssh command can stall indefinitely on connection to a thrashing system --- it's connection timeouts and retry options don't apply after the socket connection is made, not matter if the authentication stalls). This only takes a few dozen lines of Python and it's really is easiest to create it as a class (defined above the __main__ suite) and do my command line parsing in a simple wrapper down inside __main__. That's sufficient to do the job at hand (I ran the script on 25,000 hosts the next day, in about two hours). It I can now use this code in other scripts as easily as:
from sshwrap import SSHJobMan
cmd = '/etc/init.d/foo restart'
targets = queryDB(some_criteria)
job = SSHJobMan(cmd, targets)
job.start()
while not job.done():
completed = job.poll()
# ...
# Deal with incremental disposition of of completed jobs
for each in sorted(job.results):
# ...
# Summarize results
... and so on.
So my script can be used for simple jobs ... and it can be imported as a module for more specialized work that couldn't be described on my wrapper's command line. (For example I could start up "consumer" subprocesses for handling other work on each host where the job was successful while spitting out service tickets or automated reboot requests for all hosts reporting timeouts or failures, etc).
For modules which have no standalone usage I can use the __main__ suite to contain unit-tests. Thus every module can contain its own tests ... which, in fact, can be integrated into the "doc strings" using the doctest module from the standard libraries. (Which, incidentally, means that properly formatted examples in the documentary comments can be kept in sync with the implementation ... since they are parts of the unit-test suite).
The main thing I like about Python is its very concise, readable syntax. Though using indentation as a block delimiter can seem strange at first, once you begin to code a lot in the language I find it begins to make sense. Though the core language is quite simple, its more advanced features, e.g. list comprehension, decorators and generators, are rather useful too.
In addition, the Python standard library is just fantastic; its documentation is very well written, and it contains a lot of very useful packages. I also find that there are plenty of good bindings for C libraries, such as PyGTK, Webkit and Qt, to name but a few.
One caveat is that Python, like most dynamic languages, is quite slow in comparison with compiled, statically-typed languages. However, you can easily extend it with C, allowing you to write code requiring better performance in C and the rest in Python.
It's a great language overall, and (for me at least) makes coding more productive and enjoyable.

How does Objective-C compare to C#? [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've recently purchased a Mac and use it primarily for C# development under VMWare Fusion. With all the nice Mac applications around I've started thinking about Xcode lurking just an install click away, and learning Objective-C.
The syntax between the two languages looks very different, presumably because Objective-C has its origins in C and C# has its origins in Java/C++. But different syntaxes can be learnt so that should be OK.
My main concern is working with the language and if it will help to produce well-structured, readable and elegant code. I really enjoy features such as LINQ and var in C# and wonder if there are equivalents or better/different features in Objective-C.
What language features will I miss developing with Objective-C? What features will I gain?
Edit: The framework comparisons are useful and interesting but a language comparison are what this question is really asking (partly my fault for originally tagging with .net). Presumably both Cocoa and .NET are very rich frameworks in their own right and both have their purpose, one targeting Mac OS X and the other Windows.
Thank you for the well thought out and reasonably balanced viewpoints so far!
No language is perfect for all tasks, and Objective-C is no exception, but there are some very specific niceties. Like using LINQ and var (for which I'm not aware of a direct replacement), some of these are strictly language-related, and others are framework-related.
(NOTE: Just as C# is tightly coupled with .NET, Objective-C is tightly coupled with Cocoa. Hence, some of my points may seem unrelated to Objective-C, but Objective-C without Cocoa is akin to C# without .NET / WPF / LINQ, running under Mono, etc. It's just not the way things are usually done.)
I won't pretend to fully elaborate the differences, pros, and cons, but here are some that jump to mind.
One of the best parts of Objective-C is the dynamic nature — rather than calling methods, you send messages, which the runtime routes dynamically. Combined (judiciously) with dynamic typing, this can make a lot of powerful patterns simpler or even trivial to implement.
As a strict superset of C, Objective-C trusts that you know what you're doing. Unlike the managed and/or typesafe approach of languages like C# and Java, Objective-C lets you do what you want and experience the consequences. Obviously this can be dangerous at times, but the fact that the language doesn't actively prevent you from doing most things is quite powerful. (EDIT: I should clarify that C# also has "unsafe" features and functionality, but they default behavior is managed code, which you have to explicitly opt out of. By comparison, Java only allows for typesafe code, and never exposes raw pointers in the way that C and others do.)
Categories (adding/modifying methods on a class without subclassing or having access to source) is an awesome double-edged sword. It can vastly simplify inheritance hierarchies and eliminate code, but if you do something strange, the results can sometimes be baffling.
Cocoa makes creating GUI apps much simpler in many ways, but you do have to wrap your head around the paradigm. MVC design is pervasive in Cocoa, and patterns such as delegates, notifications, and multi-threaded GUI apps are well-suited to Objective-C.
Cocoa bindings and key-value observing can eliminate tons of glue code, and the Cocoa frameworks leverage this extensively. Objective-C's dynamic dispatch works hand-in-hand with this, so the type of the object doesn't matter as long as it's key-value compliant.
You will likely miss generics and namespaces, and they have their benefits, but in the Objective-C mindset and paradigm, they would be niceties rather than necessities. (Generics are all about type safety and avoiding casting, but dynamic typing in Objective-C makes this essentially a non-issue. Namespaces would be nice if done well, but it's simple enough to avoid conflicts that the cost arguably outweighs the benefits, especially for legacy code.)
For concurrency, Blocks (a new language feature in Snow Leopard, and implemented in scores of Cocoa APIs) are extremely useful. A few lines (frequently coupled with Grand Central Dispatch, which is part of libsystem on 10.6) can eliminates significant boilerplate of callback functions, context, etc. (Blocks can also be used in C and C++, and could certainly be added to C#, which would be awesome.) NSOperationQueue is also a very convenient way to add concurrency to your own code, by dispatching either custom NSOperation subclasses or anonymous blocks which GCD automatically executes on one or more different threads for you.
I've been programming in C, C++ and C# now for over 20 years, first started in 1990. I have just decided to have a look at the iPhone development and Xcode and Objective-C. Oh my goodness... all the complaints about Microsoft I take back, I realise now how bad things code have been. Objective-C is over complex compared to what C# does. I have been spoilt with C# and now I appreciate all the hard work Microsoft have put in. Just reading Objective-C with method invokes is difficult to read. C# is elegant in this. That is just my opinion, I hoped that the Apple development language was a good as the Apple products, but dear me, they have a lot to learn from Microsoft. There is no question C#.NET application I can get an application up and running many times faster than XCode Objective-C. Apple should certainly take a leaf out of Microsoft's book here and then we'd have the perfect environment. :-)
No technical review here, but I just find Objective-C much less readable.
Given the example Cinder6 gave you:
C#
List<string> strings = new List<string>();
strings.Add("xyzzy"); // takes only strings
strings.Add(15); // compiler error
string x = strings[0]; // guaranteed to be a string
strings.RemoveAt(0); // or non-existant (yielding an exception)
Objective-C
NSMutableArray *strings = [NSMutableArray array];
[strings addObject:#"xyzzy"];
[strings addObject:#15];
NSString *x = strings[0];
[strings removeObjectAtIndex:0];
It looks awful. I even tried reading 2 books on it, they lost me early on,
and normally I don't get that with programming books / languages.
I'm glad we have Mono for Mac OS, because if I'd had to rely on Apple
to give me a good development environment...
Manual memory management is something beginners to Objective-C seems to have most problem with, mostly because they think it is more complex than it is.
Objective-C and Cocoa by extension relies on conventions over enforcement; know and follow a very small set of rules and you get a lot for free by the dynamic run-time in return.
The not 100% true rule, but good enough for everyday is:
Every call to alloc should be matched with a release at the end of the current scope.
If the return value for your method has been obtained by alloc then it should be returned by return [value autorelease]; instead of being matched by a release.
Use properties, and there is no rule three.
The longer explanation follows.
Memory management is based on ownership; only the owner of an object instance should ever release the object, everybody else should always do nothing. This mean that in 95% of all code you treat Objective-C as if it was garbage collected.
So what about the other 5%? You have three methods to look out for, any object instance received from these method are owned by the current method scope:
alloc
Any method beginning with the word new, such as new or newService.
Any method containing the word copy, such as copy and mutableCopy.
The method have three possible options as of what to do with it's owned object instances before it exits:
Release it using release if it is no longer needed.
Give ownership to the a field (instance variable), or a global variable by simply assigning it.
Relinquish ownership but give someone else a chance to take ownership before the instance goes away by calling autorelease.
So when should you pro-actively take ownership by calling retain? Two cases:
When assigning fields in your initializers.
When manually implementing setter method.
Sure, if everything you saw in your life is Objective C, then its syntax looks like the only possible. We could call you a "programming virgin".
But since lots of code is written in C, C++, Java, JavaScript, Pascal and other languages, you'll see that ObjectiveC is different from all of them, but not in a good way. Did they have a reason for this? Let's see other popular languages:
C++ added a lot extras to C, but it changed the original syntax only as much as needed.
C# added a lot extras compared to C++ but it changed only things that were ugly in C++ (like removing the "::" from the interface).
Java changed a lot of things, but it kept the familiar syntax except in parts where the change was needed.
JavaScript is a completely dynamic language that can do many things ObjectiveC can't. Still, its creators didn't invent a new way of calling methods and passing parameters just to be different from the rest of the world.
Visual Basic can pass parameters out of order, just like ObjectiveC. You can name the parameters, but you can also pass them the regular way. Whatever you use, it's normal comma-delimited way that everyone understands. Comma is the usual delimiter, not just in programming languages, but in books, newspapers, and written language in general.
Object Pascal has a different syntax than C, but its syntax is actually EASIER to read for the programmer (maybe not to the computer, but who cares what computer thinks). So maybe they digressed, but at least their result is better.
Python has a different syntax, which is even easier to read (for humans) than Pascal. So when they changed it, making it different, at least they made it better for us programmers.
And then we have ObjectiveC. Adding some improvements to C, but inventing its own interface syntax, method calling, parameter passing and what not. I wonder why didn't they swap + and - so that plus subtracts two numbers. It would have been even cooler.
Steve Jobs screwed up by supporting ObjectiveC. Of course he can't support C#, which is better, but belongs to his worst competitor. So this is a political decision, not a practical one. Technology always suffers when tech decisions are made for political reasons. He should lead the company, which he does good, and leave programming matters to real experts.
I'm sure there would be even more apps for iPhone if he decided to write iOS and support libraries in any other language than ObjectiveC. To everyone except die-hard fans, virgin programmers and Steve Jobs, ObjectiveC looks ridiculous, ugly and repulsive.
One thing I love about objective-c is that the object system is based on messages, it lets you do really nice things you couldn't do in C# (at least not until they support the dynamic keyword!).
Another great thing about writing cocoa apps is Interface Builder, it's a lot nicer than the forms designer in Visual Studio.
The things about obj-c that annoy me (as a C# developer) are the fact that you have to manage your own memory (there's garbage collection, but that doesn't work on the iPhone) and that it can be very verbose because of the selector syntax and all the [ ].
As a programmer just getting started with Objective-C for iPhone, coming from C# 4.0, I'm missing lambda expressions, and in particular, Linq-to-XML. The lambda expressions are C#-specific, while the Linq-to-XML is really more of a .NET vs. Cocoa contrast. In a sample app I was writing, I had some XML in a string. I wanted to parse the elements of that XML into a collection of objects.
To accomplish this in Objective-C/Cocoa, I had to use the NSXmlParser class. This class relies on another object which implements the NSXMLParserDelegate protocol with methods that are called (read: messages sent) when an element open tag is read, when some data is read (usually inside the element), and when some element end tag is read. You have to keep track of the parsing status and state. And I honestly have no idea what happens if the XML is invalid. It's great for getting down to the details and optimize performance, but oh man, that's a whole lot of code.
By contrast, here's the code in C#:
using System.Linq.Xml;
XDocument doc = XDocument.Load(xmlString);
IEnumerable<MyCustomObject> objects = doc.Descendants().Select(
d => new MyCustomObject{ Name = d.Value});
And that's it, you've got a collection of custom objects drawn from XML. If you wanted to filter those elements by value, or only to those that contain a specific attribute, or if you just wanted the first 5, or to skip the first 1 and get the next 3, or just find out if any elements were returned... BAM, all right there in the same line of code.
There are many open-source classes that make this processing a lot easier in Objective-C, so that does much of the heavy lifting. It's just not this built in.
*NOTE: I didn't actually compile the code above, it's just meant as an example to illustrate the relative lack of verbosity required by C#.
Probably most important difference is memory management. With C# you get garbage collection, by virtue of it being a CLR based language. With Objective-C you need to manage memory yourself.
If you're coming from a C# background (or any modern language for that matter), moving to a language without automatic memory management will be really painful, as you will spend a lot of your coding time on properly managing memory (and debugging as well).
Here's a pretty good article comparing the two languages:
http://www.coderetard.com/2008/03/16/c-vs-objective-c/
Other than the paradigm difference between the 2 languages, there's not a lot of difference. As much as I hate to say it, you can do the same kind of things (probably not as easily) with .NET and C# as you can with Objective-C and Cocoa. As of Leopard, Objective-C 2.0 has garbage collection, so you don't have to manage memory yourself unless you want to (code compatibility with older Macs and iPhone apps are 2 reasons to want to).
As far as structured, readable code is concerned, much of the burden there lies with the programmer, as with any other language. However, I find that the message passing paradigm lends itself well to readable code provided you name your functions/methods appropriately (again, just like any other language).
I'll be the first to admit that I'm not very familiar with C# or .NET. But the reasons Quinn listed above are quite a few reasons that I don't care to become so.
The method calls used in obj-c make for easily read code, in my opinion much more elegant than c# and obj-c is built on top of c so all c code should work fine in obj-c. The big seller for me though is that obj-c is an open standard so you can find compilers for any system.

Do you have any good advice/links to a set of coding standards or best practices to follow?

For those of us that have programmed enough I’m sure we have come across many different flavours of coding standards that you can use when it comes to programming.
e.g. http://msdn.microsoft.com/en-us/library/ms229042.aspx
You might derive your coding standards for the current company you work for or from the original author of the code you’re working on. Coding styles are often used for specific program languages and some styles in one coding language might not be considered appropriate for others. Of course some coding standards can be applied across many different program languages.
Thank you for your time.
EDIT: As we know there are many related articles on this subject, but C# Coding standard / Best practices in SO has some very useful links in there which is worth a visit. (Check out the 2 links on .NET/C# guidelines by ESV - Accepted Answer)
Google has a posted style guide for C++ here which I consult sometimes. Just reading through the explanations and reasoning, despite whether you end up agreeing with some of the styles or not, may teach you some things you might not have thought about.
My best advice regarding coding standards: don't let them get in the way when trying to get work done.
A big bureaucracy might actually hinder progress in projects instead of helping to achieve better team work. When people complain about not following coding standards instead of the actual quality of the code, then it is too much regulation.
Other than that, pick one from the many suggestions and try to stick with it for as long as possible to build a code base following a single standard that you are used to.
Coding standards are good, but coding standards written from scratch in which the company reinvents the wheel, or coding standards imposed by a single "prophet", can be worse than having no coding standards at all.
This means:
Coding standards should be discussed and agreed upon.
The coding standards document should include the reasons behind each rule.
Coding standards should be at least partially based on reliable sources.
The sources I know of for the languages in your tags are:
For C++: The book C++ Coding Standards by Sutter/Alexandrescu.
For C#: 4 or 5 PDF's I found googling for C# Coding Standards :)
Adam Cogan has a great set of rules on his web site. There are coding guidelines, but there is much more there also.
Adam Cogan's Rules to Better...
Coding standards are great. We've been using Lance Hunt's C# Coding Standards for .NET almost without modifications
If you are maintaining code that continue to use the same standard as the original code was developed in (there is nothing worse then trying to debug a problem when the code looks all higgildy piggeldy)
Some comment to the post suggesting looking at the Google C++ guidelines. Detailed discussion about some aspects of these guidelines are posted at comp.lang.c++.moderated.
Some weird or controversial points include:
We don't believe that the available
alternatives to exceptions, such as
error codes and assertions, introduce
a significant burden.
As if assertions were a viable alternative... Assertions are usually for programming errors and situations that should never happen, while exceptions can happen (are somewhat anticipated) in the execution flow.
Reference Arguments: All parameters
passed by reference must be labeled
const. ... In fact it is a very strong
convention that input arguments are
values or const references while
output arguments are pointers.
No comment, about weasel phrase a very strong convention.
Doing Work in Constructors: Do only
trivial initialization in a
constructor. If at all possible, use
an Init() method for non-trivial
initialization.  ... If your object
requires non-trivial initialization,
consider having an explicit Init()
method and/or adding a member flag
that indicates whether the object was
successfully initialized.
Yes... 2-phase init to make things simpler... What if I have const fields? This rule is probably the effect of attitude towards exceptions.
Use streams only for logging
Which streams? IOStreams, standard C streams, other?
On one hand they advise to use macros only in exceptional situations, while they recommend using DISALLOW_COPY_AND_ASSIGN to prohibit copy/assign. They could have advised the approach with special class (like in Boost)
Do not overload operators except in rare, special circumstances.
What about assignment, or arithmetic operators for numeric calculations, etc?
Default parameters are more difficult to maintain because copy-and-
paste from previous code may not reveal all the parameters. Copy-and-
pasting of code segments can cause major problems when the default
arguments are not appropriate for the new code.
The what? Copy/paste from previous code?
Remember that reading any of the guidelines can introduce a bias to your way of thinking. And sometimes it won't be beneficial for you or your code. I agree with some other posts advising reading good books by good authors beforehand. When you have sufficient amount of knowledge, then you are able to look at the guidelines and find good and weak points easily, without creating a mess in your brain ;)
If you plan to introduce a code-formatting standard to an existing programming team, get input from each member of the team so they'll have "buy in" and be more likely to write code to that standard.
Programming styles are as difficult to change as habits, and you'll have to accept that some people won't make their code 100% compliant 100% of the time. It would be worth your time to find (or write your own) pretty-printer program and periodically run all your code through it to enforce consistency. (I always felt uneasy when manually checking in source code changes that only consisted of formatting corrections for other peoples' code; I worried that others would label me a nitpicker.)
Sun Java Code Conventions
Python Style Guide
Zend Coding Standard for PHP
Having asked this question. I found that the accepted answer proved to be sufficient for my needs.
However, I realise that this is not a 'one-size-fits-all' scenario, so there is a large quantity of information within the thread that you may find more or less useful. Weel worth a read!
For Java and other C-family languages I recommend Sofware Monkey's coding standards (of course, since they're mine).
In general, keep them simple, and provide examples and justification for every requirement.
What's in the standard doesn't really matter all that much. What matters is that you have one, and that your developers follow it.
It doesn't quite answer the question, but it's worth a mention...
I read Steve McConnell's Code Complete. Whilst it doesn't give you a pre-baked set of coding standards it does set out a lot of good arguments for the various approaches. It'll make you think about things you'd not thought of before.
It changed my little world for the better.
Coding standards themselves are great and all, but what I think is much, much, MUCH more important is keeping with the style of whatever code you're maintaining. I've seen people add a function to some class written one way and forcing their coding standard on just that function. It's inconsistent, it sticks out, and, in my opinion, it makes it harder to enjoy the class "as a whole".
Whenever you're maintaining code, look at the code around it. See what the style is. K&R braces? Capital Camel Case methods? Hungarian? Double-line comment blocks between every function? Whatever it is, you should do it too in that specific area.
Before I leave, one thing I'd like to note that's related - naming files. I'm mainly a C++ guy, so this may not apply to whatever else, but basically it goes _.h or .cpp. So, Foo::Bar would be in Foo_Bar.h. Common things (i.e. a precompiled header) for the Foo namespace would be in Foo_common.h (note the lowercase common). Of course, that's a taste thing, but everybody who has worked with this has come out in favor of this.
i think Code Craft - The Practice of Writing Excellent Code pretty much sums it all up
Very popular are Ellemtel rules for C++.
For C# I recommend Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition) (Microsoft .NET Development Series).
Mono Coding Guidelines
The answers here a pretty complete, thus I am not pointing to another coding standard document. However, once you decided to stick to one style you should use an automated coding style enforcer throughout your team.
For Java there is checkstyle and for .NET Microsoft Style Cop.
Here is a similar discussion on Stackoverflow: C# Coding standard / Best practices
Camel and pascal casing alone solves a lot of coding standard problems

Categories

Resources