Our new Indie Games subforum is now open for business in G&T. Go and check it out, you might land a code for a free game. If you're developing an indie game and want to post about it, follow these directions. If you don't, he'll break your legs! Hahaha! Seriously though.
Our rules have been updated and given their own forum. Go and look at them! They are nice, and there may be new ones that you didn't know about! Hooray for rules! Hooray for The System! Hooray for Conforming!

Giant Programming Clusterfuck++

NightslyrNightslyr Registered User regular
Shamelessly stolen from Janin's awesome OPs (all examples below written in Python):

Turning progamers into programmers hell yeah

I wrote up this wall of text while playing EVE. I hope that this thread will become a place where people new to programming can learn what languages are available, how to operate basic parts of programming, get help deciphering inscrutable homework assignments, etc. It might also serve as a useful repository for commonly-asked questions like "what is a pointer", "how do I write a function", etc.

Basic overview

In the code samples here, lines starting with the "#" character are comments. This means that they are not part of the program itself, but are instructions or notes to the reader.

Stuff that doesn't go anywhere specific

Always turn on compiler or interpreter warnings, and set them to maximum. If possible, make them errors rather than warnings. Compiler writers are very smart, and probably know more than you do. Read the documentation to your compiler or interpreter to determine how to set warning and error levels.

Variables

Variables are a way to "label" a certain value. They can be used to reduce code duplication. If you wanted to change the base value in the old code, you would have to update it in three places. In the new code, it only has to be updated in one.
# Old code
value1 = (5 * 10) + 5
value2 = (5 * 10) + 6
value3 = (5 * 10) + 7

# New code
base = 5 * 10
value1 = base + 5
value1 = base + 6
value1 = base + 7

To document code behavior. In the old code, the numbers "5", "10", and "100" are "magic numbers". Their purpose is unknown - may be it's how many cars have been sold, how many employees took the day off sick, or how many dollars were spent on candy bars. May be there's a comment hidden somewhere about its purpose, or may be not. In the new code, their purposes are inherently documented everywhere the variables are used.
# Old code
var = 100
income_today = var * 10 * 0.3

# New code
cent_multiplier = 100
net_dollar_income = 10
tax_rate = 0.3
income_today = net_dollar_income * cent_multiplier * tax_rate

In most modern languages, variables have "types". A type determines what values a variable can hold and what operations you can perform on it. For example, you can add two numbers, but cannot add a number and a string.

Common types of variables:
Boolean - May be either True or False, nothing else. In some primitive languages, such as C, the integers 0 and 1 are used instead of true and false.
Integer - A number with no fractional part.
Floating Point - A number that may contain fractional parts. Because computers only operate on Base 2 numbers, floating point math in most languages can give very "weird" values. For an example, enter "javascript:alert (0.1 + 0.2)" into your browser's URL bar.
String - An ordered list of characters. These might be letters like A, digits like 2, punctuation like !, or "unprintable" control characters such as a "new line" marker.
List - An ordered list of variables. These are usually accessed by a "0-based" index. For example, position 0 of the list (5 10 15 20) is 5, and position 3 is 20.

Conditionals

Conditionals are what separate a programming language from a mere list of equations. A conditional always has an if-block, and sometimes an else-block. In some languages, the two can be combined to save space. One thing to note here is the use of "==" to check for equality. Because "=" is used to assign to a variable, "==" checks if two values are equal.

An example of an if statement:
name = "Alice"
if name == "Alice":
        print "Hello Alice!"
else:
        if name == "Bob":
                print "Guten Tag Bob!"
        else:
                print "I don't know who you are."

# The same as above, with a combined 'elif' statement
name = "Alice"
if name == "Alice":
        print "Hello Alice!"
elif name == "Bob":
        print "Guten Tag Bob!"
else:
        print "I don't know who you are."

Loops

Loops are used to help reduce code duplication. If you have to do something many times, it's easier to put into a loop than try to write out every step. And if you want to change how many times something happens, it'll have to be in a loop.

The most basic form of the loop is the while loop. This loop will simply run over and over until some condition is met. If you make a mistake in the body, the loop might run forever and freeze your program.
x = 10
while x < 500:
        x = x * 10
print x

The other popular form of the loop is the for loop. A for loop is used for doing something once for every item in a group.
numbers = [5, 10, 15, 20, 25, 30]
# The number is: 5
# The number is: 10
# etc
for number in numbers:
        print "The number is: ", number


# The name is: Alice
# The name is: Bob
# etc
for name in ["Alice", "Bob", "Charlie", "David", "Eve"]:
        print "The name is: ", name

Nightslyr on
My PA, PSN, XBL, Origin, and Steam names are the same. 3DS Friend Code: 1607-1682-2948
steam_sig-400.png
Stack Exchange | http://www.mpdevblog.blogspot.com
«13456763

Posts

  • EtheaEthea Registered User regular
    edited January 2009


    The other form of loop is a relative newcomer, only seen in newer languages and addon libraries for older OO languages like C++. It's called a foreach loop, and is used to run a function across all elements of a collection (like an array).

    Could also explain it uses an iterator, and what that is.

  • AngelHedgieAngelHedgie Registered User regular
    edited January 2009
    Ethea wrote: »


    The other form of loop is a relative newcomer, only seen in newer languages and addon libraries for older OO languages like C++. It's called a foreach loop, and is used to run a function across all elements of a collection (like an array).

    Could also explain it uses an iterator, and what that is.

    Actually, foreach doesn't use an iterator.

    XBL: Nox Aeternum / PSN: NoxAeternum / NN:NoxAeternum
    Spoiler:
  • BlueSquareBlueSquare Registered User
    edited January 2009
    Ethea wrote: »


    The other form of loop is a relative newcomer, only seen in newer languages and addon libraries for older OO languages like C++. It's called a foreach loop, and is used to run a function across all elements of a collection (like an array).

    Could also explain it uses an iterator, and what that is.

    Actually, foreach doesn't use an iterator.


    Actually, it does in the CLR languages (really enumerator here). It only unrolls to a 'for loop' on intrinsic types.

  • NightslyrNightslyr Registered User regular
    edited January 2009
    Ack, so many replies/revisions! I'll get to work on all those tomorrow. Thanks for all of the input so far, everyone.

    My PA, PSN, XBL, Origin, and Steam names are the same. 3DS Friend Code: 1607-1682-2948
    steam_sig-400.png
    Stack Exchange | http://www.mpdevblog.blogspot.com
  • AngelHedgieAngelHedgie Registered User regular
    edited January 2009
    Iteration Vs. Recursion

    There are actually two ways to repeat code - iteration, where we loop over and over through a piece of code; and recursion, where we call a function inside of itself. Let's take a look at Nightslyr's Fibonacci function:
    int fib(int n)
    {
       if (n == 0)
          return 0;
       if (n == 1)
          return 1;
       return fib (n - 1) + fib (n - 2);
    }
    

    This is an example of a recursive function. If you look at the bottom, you can see that to get any value past the first 2, we call the function inside of itself. That said, we could write the same function iteratively:
    int fib2(int n)
    {
       if (n == 0)
          return 0
       if (n == 1)
          return 1 
       else
       {
          int v1 = 1;
          int v2 = 1;
          int temp = 0;
          n = n-2
          for (int i = 0; i < n; i++)
          {
             temp = v1 + v2;
             v1 = v2;
             v2 = temp;
          }
          return v1 + v2;
       }
    }
    

    That will do the exact same thing as the recursive example. However, it is a bit more complicated.


    Now, here's the kicker - which one would you use to calculate, say...the 5th Fibonacci number? How about the 25th? I would use the recursive function to get the first, but the iterative one to get the 25th. The reason is simple - while the iterative function is more complex, it always remains at the same level of complexity. In comparison, watch what happens when we start looking at the mechanism of the recursive function:

    fib(2) = fib(1) + fib(0) = 1 + 1 = 2
    fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + fib(0) = (1 + 1) + 1 = 3
    fib(4) = fib(3) + fib(2) = (fib(2) + fib(1)) + (fib(1) + fib(0)) = ((fib(1) + fib(0)) + fib(1)) + (fib(1) + fib(0)) = ((1 + 1) + 1) + (1 + 1) = 5

    And so on. As you can see, the recursive function increases in complexity in a geometric fashion, whereas the iterative version increases arithmetically.

    XBL: Nox Aeternum / PSN: NoxAeternum / NN:NoxAeternum
    Spoiler:
  • PantsBPantsB Registered User regular
    edited January 2009
    (I'll essentially be using psuedo code below. I think AH is using C# and I'm trying to remain consistent but its been 2 years since I used it)

    Polymorphism is probably the central concept behind OOP, and one of the more difficult to fully grasp. Its also one of the few areas where different languages require fundamentally different designs depending on their implementation of inheritance.

    Abstract Classes
    Consider: What if you were using the above Mammal system. No animal is simply a "Mammal" and there is no "Mammal" noise to make when it speaks. The system should thus be prohibited from creating an instance of "Mammal" as this does not reflect reality.

    While this may appear harmless in other examples it could lead to instability and security holes.

    This is achievable through an "abstract class."
    abstract private class Mammal
    {
      public virtual string Speak();
    
    }
    
    Not there is no Constructor, nor is there any code behind Speak(). The lack of code behind Speak is optional, but by using the virtual keyword, any non-abstract subclass must implement Speak.

    Time is running short (I want to bang out a few more things before 530 when I'm out of here), so forgive the pseudo-code here on out.

    Multiple inheritance:
    In some languages (C++, LISP, Python), a class can inherit from more than one class. Other languages (Java, C#, PHP) you can inherit obligations through more than one class if you use a specific type of abstract class called an "interface." The former is increasingly deprecated because (in part) of the diamond problem.

    The above example could have "Mammal" as an interface if we removed the name attribute (or made it some combination of final, constant and/or static depending on the language).
    Interface Vendor
    {
    public bool takeMoney();
    protected bool evaluateChoice();
    public bool receiveChoice();
    protected bool dispenseToy(Object x);
    }
    

    Any vendor - a coke machine, a candy machine, a cigarette machine, or a robot bartender would have to implement those features.
    Class RobotBarKeep extends Robot implements Vendor
    {
    /*etc*/
    }
    


    There's more if anyone wants to tackle Final classes and probably more important the static concept, fire away.

    Oh and Linked Lists. That should probably be covered in combination with recursion, right before Tower of Hanoi

    11793-1.png
    Spoiler:
  • ObsObs __BANNED USERS regular
    edited January 2009
    Intro to Cocoa Programming (Mac OS X)


    What you will need: a Mac and Xcode Developer Tools. You can buy a Mac from your local Apple store and Xcode should be available online as well, some say it also comes on the installation DVD with most Macs.

    Prerequisites: You should be familiar with object oriented concepts and programming in general, as these are universal things that may not be specific to Cocoa. If you already know C and at least one object oriented language such as C++ or Java, you will do well and learn fast as fuck.

    I'll update this section here regularly with new stuff over time, so check back every once and a while because I can tell already I'm probably not going to write all this stuff in one sitting. If you have any questions PM me or ask in the thread (but I don't really keep up with every page of this thread).

    So let's begin.



    Part 1: Objective C 2.0

    This language is what you will use to do your Cocoa programming. If I had to describe Objective-C, I would basically tell you it's C with powerful object oriented shit added to it. C is a complete subset of Objective-C, which means any Objective-C compiler will also compile pure C code; you can freely mix C, C++ and Objective-C code together in the same application without problems. This gives you a powerful advantage, because you have the ease of high level coding like with Java and C#, but you are not restricted to it all the time (so you could do some custom optimization).

    Because of this, a good Objective-C programmer should also be a good C programmer.

    In Objective-C there exist things called objects. Objects are basically structures that carry two things, variables and methods. An object is defined by a class. The class describes the format of the object, meaning it tells you what variables the object has and their types, and what methods the objects run and what they return. In Objective-C, a class is also used to allocate an object.

    When you want an object to run a certain method, you send it a message. There is a certain format to sending a message to an object, it looks like this:
    [objectRecievingMessage messageBeingSent];
    


    Notice this is dramatically different from some languages where you may write something like:

    object.Function();


    Well, it gets wierder. If you are sending messages with parameters, they start to look like this
    [objectRecievingMessage messageBeingSentWithParameterOne: 55.0  ParameterTwo: 958.0 ParameterThree: 46.0];
    

    It looks bizarre at first, the function being peppered with parameters all up inside it like that, but the end result is some very readable code. The format for the messages is defined of course when you write the classes.

    In Objective-C there is also a variable of type id. An id variable stands for object identifier. You can think of an id as a pointer to any type of object. So if you see a method that returns a type "id", it means it returns a pointer to an object. Because an id can be any object type, you don't really know shit about it other than the fact that it IS an object.



    A class is defined by two files: a header file (.h) and an implementation file (.m). Xcode generally creates both these files when you go to define a new class.

    Here is an example of a class definition, in it's own file called noobert.h
    #import <Foundation/Foundation.h> [I] ////This line adds all the necessary header files for Cocoa.
    [/I]
    
    @interface noobert : NSObject {[I] ////This line means you are defining an interface for a class named noobert, which inherits the instance and method variables of the class [b]NSObject[/b].[/I]
         
         int one; [I]///standard int[/I]
         float two; [I] ///standard float[/I]
    }
    
    -(float)multiplyNumbers; [I] //this defines a method that returns a float[/I]
    -(void)printGarbage;      [I]//this defines a method that returns nothing[/I]
    -(void)newNumbersForFirst:(int)num1 Second:(float)num2;[I]              //And this method returns nothing and takes two parameters, num1 and num2, of type int and float respectively.[/I]
    
    @end    [I]//and here we know that the class definition has come to an end. [/I]
    
    Spoiler:

    And here is the implementation of that class, in a separate file called noobert.m
    #import <Foundation/Foundation.h>
    #import "noobert.h"     [I]////Notice we have to import the .h file for the class to this .m file so it can know what the hell is going on. We use quotes because it's a file we created here in the project.[/I]
    
    @implementation noobert     [I] ////Now this line lets us know we are implementing methods for the noobert class.[/I]
    
    
    -(float)multiplyNumbers {
    
         return (one * two); [I]//returns the result of multiplying these two numbers, which will be a float. [/I]
    }
    
    
    -(void)printGarbage {
    
          printf("\n get the fuck outta here"); [I]//prints a line to the console, wherever that is. [/I]
    }    
    
    -(void)newNumbersForFirst:(int)num1 Second:(float)num2 {
    
          one = num1;
          two = num2;
    } 
    
    @end         [I]// implementation is over at this point[/I]
    
    Spoiler:



    So now suppose we have this class called noobert, and we wish to create an object of type noobert.

    We will need to create a variable, allocate memory for the noobert object, and then initialize it. It works like this (assuming all this code is a part of something larger):
    noobert *variableName;      [I]//The * means this is a pointer to an object of type noobert. We do not create statically defined objects. If you try you will get an error. [/I]
    
    variableName = [[noobert alloc] init];   
    
    [I]///In the line above you are telling the class to allocate memory for a new object of it's type. The alloc function returns an object of type "noobert". Then, for that object, you call it's init function which prepares the new object instance for use. If you think it's weird that something abstract like a class could receive a message like that in Objective-C, don't worry about it. I think every class in Objective-C actually creates it's own instance at the start of a program that serves a single purpose of creating new objects of it's own type, but I could be horribly wrong. Either way, doesn't really matter. [/I]
    
    
    //and now the new object can be used for stuff. 
    
    int small;
    [variableName printGarbage];
    float value = [variableName multiplyNumbers];
    small = (value * 2);
    [variableName newNumbersForFirst:small Second:[variableName multiplyNumbers]];
    
    //etc...
    
    






    Ok well I've talked about Objective-C this whole time and I actually haven't said anything about Cocoa yet so I'll have to continue later because I'm going to sleep.

    I don't really know how much more I'll write about Objective-C, I mean I could basically go on forever, and I've only scratched the syntactic surface here. It's a simple language to learn though if you have the right background, so next update I'll show you how to start building applications right away, complete with full UI and stuff, no command line BS. Peace.




    Part 2: Building a Cocoa Application

    coming soon

    update: in case anyone cares, I'll get to this eventually, sorry I'm just pretty loaded with work right now

    spacer.png
    spacer.png
    Obs.gif
  • noobertnoobert Registered User
    edited January 2009
    Obs wrote: »
    Intro to Cocoa Programming (Mac OS X)


    Reserved.

    waitin' on 'dis.

  • BlueSquareBlueSquare Registered User
    edited January 2009
    As relating to .NET languages, (syntax is C#):

    An abstract class can not be marked private. That would defeat the purpose of being inherited. It can be marked public or internal.

    If a method must be implemented by sub classes (edit: i had weird wording here), it is marked abstract, such as your Speak() method. It is not a virtual method.

    Abstract classes can certainly have a constructor and any other implementation that is seen in non-abstract classes.

    An Interface is not an abstract class at all. It is a special type that defines a contract that the object that implements the interface is bound to uphold. There is not much else to it than that. Interfaces also can not define the accessor on it's members. IOW, you can not tell the implementer that they must set function Foo to private.

    One important concept I have not yet seen discussed is the concept of immutability.

  • ASimPersonASimPerson And protect them from the evils of the world like trigonometry and prime numbers.Registered User regular
    edited January 2009
    As the user with the 11th-most posts in the old thread, let me state here:

    Ask some freakin' C questions :)

    redoctober2.png
    SE++ Forum Battle Archive | PST = Pacific Standard Time | DRUNKSTUCK: A Homestuck recap
  • ecco the dolphinecco the dolphin Registered User regular
    edited January 2009
    ASimPerson wrote: »
    As the user with the 11th-most posts in the old thread, let me state here:

    Ask some freakin' C questions :)

    I second this sentiment.

    Although I get the feeling we're getting a bit long in the tooth, old friend. Back in my days, I remember having to write assembly bitblt instructions by hand to work with SVGA graphics (640 x 480 x 16-bit colour!? WOW!!! I think my S3 video card had enough video memory to do 800 x 600 x 16-bit colour as well!). See, it was real mode on the x86 back then - I hadn't quite mastered protected mode, so I could only access 64k of video RAM at any time. Ahh, bank switching.

    Remember EMS and XMS? You wanted more than 640k but didn't want to go into protected mode? EMS and XMS were the only real ways (well, there was that fake real mode with 32-bit flat memory addresses that you could get into, but that required you to remove memory managers like himem.sys and emm386, so it didn't feel that good).

    Learning how to use DMA to pipe sound out to sound-blaster compatible cards.

    Man, those were the days.

    Now, you get callbacks and HALs and whatever else to do everything for you.

    Times have changed, I say. Perhaps for the better, but I still remember the shock I had when I finally played a wav file through my speakers (okay, I had calculated the sample rate wrong, so it played about 4 times as fast or something - but still!).

    Penny Arcade Developers at PADev.net.
  • ASimPersonASimPerson And protect them from the evils of the world like trigonometry and prime numbers.Registered User regular
    edited January 2009
    ASimPerson wrote: »
    As the user with the 11th-most posts in the old thread, let me state here:

    Ask some freakin' C questions :)

    I second this sentiment.

    Although I get the feeling we're getting a bit long in the tooth, old friend. Back in my days, I remember having to write assembly bitblt instructions by hand to work with SVGA graphics (640 x 480 x 16-bit colour!? WOW!!! I think my S3 video card had enough video memory to do 800 x 600 x 16-bit colour as well!). See, it was real mode on the x86 back then - I hadn't quite mastered protected mode, so I could only access 64k of video RAM at any time. Ahh, bank switching.

    Remember EMS and XMS? You wanted more than 640k but didn't want to go into protected mode? EMS and XMS were the only real ways (well, there was that fake real mode with 32-bit flat memory addresses that you could get into, but that required you to remove memory managers like himem.sys and emm386, so it didn't feel that good).

    Learning how to use DMA to pipe sound out to sound-blaster compatible cards.

    Man, those were the days.

    Now, you get callbacks and HALs and whatever else to do everything for you.

    Times have changed, I say. Perhaps for the better, but I still remember the shock I had when I finally played a wav file through my speakers (okay, I had calculated the sample rate wrong, so it played about 4 times as fast or something - but still!).

    Um, I kind of hate to say this, but while I do know everything you're talking about, I never had to deal with it.
    Spoiler:
    That said, I do program C every day and it's just my preferred language. While I'm sure OS and other system level code can be written in other languages, it's still mostly good ole C.

    redoctober2.png
    SE++ Forum Battle Archive | PST = Pacific Standard Time | DRUNKSTUCK: A Homestuck recap
  • Smug DucklingSmug Duckling Registered User regular
    edited January 2009

    ...

    And so on. As you can see, the recursive function increases in complexity in a geometric fashion, whereas the iterative version increases arithmetically.

    It doesn't have to. Recursion can do Fibonacci just fine. Just have to go about it slightly differently:
    int fib(int n) {
      return fib_helper(0, 1, n);
    }
    
    int fib_helper(int prev, int cur, int rem) {
      if(rem == 0) {
        return prev;
      } else {
        return fib_helper(cur, prev + cur, rem - 1);
      }
    }
    

    Runs in nice linear time. :)

    As an interesting exercise for anyone who's curious, try executing both my method and the previous recursive method of finding Fibonacci numbers. You will quickly see the difference in speed as you increase n.

    smugduckling,pc,days.png
  • Smug DucklingSmug Duckling Registered User regular
    edited January 2009
    Another, iterative, way to do it is called Dynamic Programming, which sounds more complex than it really is. At its core, it is about filling in a table of already calculated results so that you never need to calculate the same thing twice. A neat side-effect is that by the end of the calculation, you can have a table of results so that in the future you can recalculate the same problem by simply looking at the table.

    In the Fibonacci example, you might do it like this:
    int fib(int n) {
      int[] fibs = new int[n+1];
      fibs[0] = 0;
      fibs[1] = 1;
      for(int i = 2; i <= n; i++) {
        fibs[i] = fibs[i-1] + fibs[i-2];
      }
      return fibs[n];
      // If you wish you could return the whole array here for easy use later.
    }
    

    The iterative solution that was proposed earlier is kind of an optimization of this, designed to save memory. Since only the last two entries of the array of used, only those are kept in variables.

    smugduckling,pc,days.png
  • AiranAiran Registered User regular
    edited January 2009
    java.lang.NoClassDefFoundError

    I'm working in Eclipse. I've transferred my project files from my Vista laptop to my XP desktop. I fixed the reference file locations, etc etc.
    When I try to start main(), My laptop runs the program fine, my desktop does not. Does anyone have any ideas because this is seriously pissing me off. Google hasn't been much help, apart from telling me that main.class is missing, and to set the classpath to fix it. I'm not sure if I'm setting it correctly (Configure Build Path > Classpath tab > Advanced > Enter Classpath Variable > Configure > New).

    Seriously guys this is doing my head in :x

    [edit]NEVER MIND, I don't know what the hell happened, but the error fixed itself and after correcting a typo it found the prerequisite DLLs and shit, now it's working all fine and dandy, yay.

    paDudSig.jpg
  • PantsBPantsB Registered User regular
    edited January 2009
    BlueSquare wrote: »
    As relating to .NET languages, (syntax is C#):

    An abstract class can not be marked private. That would defeat the purpose of being inherited. It can be marked public or internal.

    If a method must be implemented by sub classes (edit: i had weird wording here), it is marked abstract, such as your Speak() method. It is not a virtual method.

    Abstract classes can certainly have a constructor and any other implementation that is seen in non-abstract classes.

    An Interface is not an abstract class at all. It is a special type that defines a contract that the object that implements the interface is bound to uphold. There is not much else to it than that. Interfaces also can not define the accessor on it's members. IOW, you can not tell the implementer that they must set function Foo to private.

    One important concept I have not yet seen discussed is the concept of immutability.
    I was trying to be more general conceptually then speaking directly to C# but a few points:

    1 - An abstract class can be private, both conceptually and in C#. I didn't intend to leave a private keyword on Mammal but that was incorrect for reasons other than inheritance.
    2 - Just screwed up on virtual keyword, rusty as a I said.
    3 - Abstract classes can have constructors, you're correct. Those constructors should not be directly accessible, however.
    4 - Interfaces are absolutely abstract classes. Abstract classes are by definition those classes that can not be directly created, only classes that inherit from them. Interfaces are a subset of abstract classes conceptually and only really exist to deal with multiple inheritance.

    11793-1.png
    Spoiler:
  • PantsBPantsB Registered User regular
    edited January 2009
    Airan wrote: »
    java.lang.NoClassDefFoundError

    I'm working in Eclipse. I've transferred my project files from my Vista laptop to my XP desktop. I fixed the reference file locations, etc etc.
    When I try to start main(), My laptop runs the program fine, my desktop does not. Does anyone have any ideas because this is seriously pissing me off. Google hasn't been much help, apart from telling me that main.class is missing, and to set the classpath to fix it. I'm not sure if I'm setting it correctly (Configure Build Path > Classpath tab > Advanced > Enter Classpath Variable > Configure > New).

    Seriously guys this is doing my head in :x

    Java classpath isn't set correctly. Always took me 20 minutes to figure out whenever I went back to Java at the start of a new semester

    11793-1.png
    Spoiler:
  • BlueSquareBlueSquare Registered User
    edited January 2009
    PantsB wrote: »
    BlueSquare wrote: »
    As relating to .NET languages, (syntax is C#):

    An abstract class can not be marked private. That would defeat the purpose of being inherited. It can be marked public or internal.

    If a method must be implemented by sub classes (edit: i had weird wording here), it is marked abstract, such as your Speak() method. It is not a virtual method.

    Abstract classes can certainly have a constructor and any other implementation that is seen in non-abstract classes.

    An Interface is not an abstract class at all. It is a special type that defines a contract that the object that implements the interface is bound to uphold. There is not much else to it than that. Interfaces also can not define the accessor on it's members. IOW, you can not tell the implementer that they must set function Foo to private.

    One important concept I have not yet seen discussed is the concept of immutability.
    I was trying to be more general conceptually then speaking directly to C# but a few points:

    1 - An abstract class can be private, both conceptually and in C#. I didn't intend to leave a private keyword on Mammal but that was incorrect for reasons other than inheritance.
    2 - Just screwed up on virtual keyword, rusty as a I said.
    3 - Abstract classes can have constructors, you're correct. Those constructors should not be directly accessible, however.
    4 - Interfaces are absolutely abstract classes. Abstract classes are by definition those classes that can not be directly created, only classes that inherit from them. Interfaces are a subset of abstract classes conceptually and only really exist to deal with multiple inheritance.

    1. It can be, only internal to another class. True. We should probably find a better example than the link you provided, which is almost a proof of concept (bad design) example of it. I can only think of a single design reason for using an abstract class in this manner.
    Either way, it *is* incorrect for inheritance because no types would have scope to it in that context. My point, although being wrong, was for you to correct your mistake so that others didn't repeat it.

    3. It needs to be decided if we're going to discuss what *can* be done and what *should* be done. Public constructors are fine on abstract classes. They aren't the best as far as design goes, but they are correct. It wouldn't make much sense for a language to support abstract classes yet allow them to be instantiated just because you made the constructor accessible.

    4. I completely disagree. Saying they are the same and then saying one is a subset of the other makes no sense to me. They function differently and provide different, yet closely related, purposes. Thinking they are the same is exactly why most people fail interview questions about the two.

  • AiranAiran Registered User regular
    edited January 2009
    PantsB wrote: »
    Airan wrote: »
    java.lang.NoClassDefFoundError

    I'm working in Eclipse. I've transferred my project files from my Vista laptop to my XP desktop. I fixed the reference file locations, etc etc.
    When I try to start main(), My laptop runs the program fine, my desktop does not. Does anyone have any ideas because this is seriously pissing me off. Google hasn't been much help, apart from telling me that main.class is missing, and to set the classpath to fix it. I'm not sure if I'm setting it correctly (Configure Build Path > Classpath tab > Advanced > Enter Classpath Variable > Configure > New).

    Seriously guys this is doing my head in :x

    Java classpath isn't set correctly. Always took me 20 minutes to figure out whenever I went back to Java at the start of a new semester

    Yeah see, I tried entering the 'jdk folder/lib' location into the Windows env variable section, I don't think Eclipse cares though. Spent an hour looking through Eclipse settings and saw nothing obvious. Somehow a reboot fixed the problem. It was a goddamn headache anyway.

    paDudSig.jpg
  • KrisKris Registered User regular
    edited January 2009
    BlueSquare wrote: »
    PantsB wrote: »
    BlueSquare wrote: »
    As relating to .NET languages, (syntax is C#):

    An abstract class can not be marked private. That would defeat the purpose of being inherited. It can be marked public or internal.

    If a method must be implemented by sub classes (edit: i had weird wording here), it is marked abstract, such as your Speak() method. It is not a virtual method.

    Abstract classes can certainly have a constructor and any other implementation that is seen in non-abstract classes.

    An Interface is not an abstract class at all. It is a special type that defines a contract that the object that implements the interface is bound to uphold. There is not much else to it than that. Interfaces also can not define the accessor on it's members. IOW, you can not tell the implementer that they must set function Foo to private.

    One important concept I have not yet seen discussed is the concept of immutability.
    I was trying to be more general conceptually then speaking directly to C# but a few points:

    1 - An abstract class can be private, both conceptually and in C#. I didn't intend to leave a private keyword on Mammal but that was incorrect for reasons other than inheritance.
    2 - Just screwed up on virtual keyword, rusty as a I said.
    3 - Abstract classes can have constructors, you're correct. Those constructors should not be directly accessible, however.
    4 - Interfaces are absolutely abstract classes. Abstract classes are by definition those classes that can not be directly created, only classes that inherit from them. Interfaces are a subset of abstract classes conceptually and only really exist to deal with multiple inheritance.

    1. It can be, only internal to another class. True. We should probably find a better example than the link you provided, which is almost a proof of concept (bad design) example of it. I can only think of a single design reason for using an abstract class in this manner.
    Either way, it *is* incorrect for inheritance because no types would have scope to it in that context. My point, although being wrong, was for you to correct your mistake so that others didn't repeat it.

    3. It needs to be decided if we're going to discuss what *can* be done and what *should* be done. Public constructors are fine on abstract classes. They aren't the best as far as design goes, but they are correct. It wouldn't make much sense for a language to support abstract classes yet allow them to be instantiated just because you made the constructor accessible.

    4. I completely disagree. Saying they are the same and then saying one is a subset of the other makes no sense to me. They function differently and provide different, yet closely related, purposes. Thinking they are the same is exactly why most people fail interview questions about the two.

    Can someone give a clear explanation of the difference between abstract classes and interfaces, and perhaps an example of when you would want to use one and not the other? I'm still shaky on this topic, even after my C# course last semester.

    Steam: Zephyrall || XBL: Zephyrall || PS3: Zephyrall_KN || Battle.Net: Zephyrall#398
  • PantsBPantsB Registered User regular
    edited January 2009
    BlueSquare wrote: »
    4. I completely disagree. Saying they are the same and then saying one is a subset of the other makes no sense to me. They function differently and provide different, yet closely related, purposes. Thinking they are the same is exactly why most people fail interview questions about the two.

    The definition of an abstract class is one that can not be instantiated.

    "Interfaces" only exist in languages that prohibit multiple inheritance. They exist explicitly because of the diamond problem. Intro courses don't teach it in these terms usually but the only reason they exist is to get some of the benefits of multiple inheritance while limiting the problems inherent by gimping some of the flexibility in the class (usually all virtual methods & only immutable/static attributes).

    If you can come up with an interface example that could not be conceptually replaced by an abstract class in a system with multiple inheritance fire away. In the same way that an abstract class is a subset with restrictions of classes in general, interfaces are a subset of abstract classes.

    11793-1.png
    Spoiler:
  • BlueSquareBlueSquare Registered User
    edited January 2009
    PantsB wrote: »
    BlueSquare wrote: »
    4. I completely disagree. Saying they are the same and then saying one is a subset of the other makes no sense to me. They function differently and provide different, yet closely related, purposes. Thinking they are the same is exactly why most people fail interview questions about the two.

    The definition of an abstract class is one that can not be instantiated.

    "Interfaces" only exist in languages that prohibit multiple inheritance. They exist explicitly because of the diamond problem. Intro courses don't teach it in these terms usually but the only reason they exist is to get some of the benefits of multiple inheritance while limiting the problems inherent by gimping some of the flexibility in the class (usually all virtual methods & only immutable/static attributes).

    If you can come up with an interface example that could not be conceptually replaced by an abstract class in a system with multiple inheritance fire away. In the same way that an abstract class is a subset with restrictions of classes in general, interfaces are a subset of abstract classes.


    Oh good lord, you win. I don't even care if someone believes your garbage anymore. Yes, there are many many debates about abstract classes versus interfaces even though they are the same thing. You are correct. I was wrong.

    I'll go back to my SAMS: Lurn OOP in 24 Ours book and my JCL programming classes.

  • AngelHedgieAngelHedgie Registered User regular
    edited January 2009
    Kris wrote: »
    Can someone give a clear explanation of the difference between abstract classes and interfaces, and perhaps an example of when you would want to use one and not the other? I'm still shaky on this topic, even after my C# course last semester.

    An abstract class is one where an object of said class cannot be created. Going back to the Mammal concept, we can define the characteristics of a Mammal (vertebrate, warm-blooded, gives birth to live young, etc.), but there's no such thing as a pure "Mammal". Instead, there are various kinds of Mammals, like Dogs and Cats and Humans and such.

    An interface is a subset of abstract classes that consist only of a list of virtual functions. When a class implements an interface, it guarantees that the functions listed in the interface definition will be implemented. For example, in order to call a foreach loop on an object in C#, the object must implement the IEnumerable interface, which details the specific commands needed for an enumerator.

    XBL: Nox Aeternum / PSN: NoxAeternum / NN:NoxAeternum
    Spoiler:
  • iTunesIsEviliTunesIsEvil Registered User regular
    edited January 2009
    Properties too AH. Methods and properties (dunno if you include properties when you say "functions").

    I dont have VS sitting in front of me: when inheriting from an abstract class (.NET), are you required to provide override implementations of all methods and properties of the abstract class?

  • His CorkinessHis Corkiness Registered User
    edited January 2009
    BlueSquare wrote: »
    PantsB wrote: »
    BlueSquare wrote: »
    4. I completely disagree. Saying they are the same and then saying one is a subset of the other makes no sense to me. They function differently and provide different, yet closely related, purposes. Thinking they are the same is exactly why most people fail interview questions about the two.

    The definition of an abstract class is one that can not be instantiated.

    "Interfaces" only exist in languages that prohibit multiple inheritance. They exist explicitly because of the diamond problem. Intro courses don't teach it in these terms usually but the only reason they exist is to get some of the benefits of multiple inheritance while limiting the problems inherent by gimping some of the flexibility in the class (usually all virtual methods & only immutable/static attributes).

    If you can come up with an interface example that could not be conceptually replaced by an abstract class in a system with multiple inheritance fire away. In the same way that an abstract class is a subset with restrictions of classes in general, interfaces are a subset of abstract classes.


    Oh good lord, you win. I don't even care if someone believes your garbage anymore. Yes, there are many many debates about abstract classes versus interfaces even though they are the same thing. You are correct. I was wrong.

    I'll go back to my SAMS: Lurn OOP in 24 Ours book and my JCL programming classes.

    "Is a subset of" != "Is exactly the same". Someone competent in OOP should recognise this.

  • urahonkyurahonky Registered User regular
    edited January 2009
    Hey guys. I really, REALLY didn't want to post here because I wanted to figure out this project myself, but I'm a retard and can't figure anything out in programming apparently (tell me why I am going for this degree if I'm not even good at it?)

    Anyway. I'm working with double linked lists. (working on an insert function, to put the number in a sorted list) but I can't seem to figure out why I am getting an error when I type the following:
    template <class Elem>
    bool LinkedSortedList<Elem>::insert(const Elem &newvalue) 
    {
    	Lnode<Elem>* node = head;
    	Lnode<Elem>* newnode = new Lnode<Elem>(newvalue);
    	if(node == NULL)
    	{
    		node = newnode;
    	}
    	return true;
    }
    

    This right here runs perfectly, except that node is never actually saved. I did an insert call in my main program, and it completes fine, but when I try to output the node it says the head node is null. But if (right after the if statement) I type: cout<<node->value; It outputs the correct number.

    So I try: node->value = newvalue and I get:
    Unhandled exception at 0x0041184a in Lab0.exe: 0xC0000005: Access violation writing location 0x00000000.
    

    So I have no idea what to do. I don't think I'm cut out for this stuff like you guys are.

    Games completed recently: Dragon's Crown, Knights of Pen and Paper, Castlevania: Symphony of the Night (20th time), Defender's Quest, The Witcher
  • ecco the dolphinecco the dolphin Registered User regular
    edited January 2009
    urahonky wrote: »
    This right here runs perfectly, except that node is never actually saved. I did an insert call in my main program, and it completes fine, but when I try to output the node it says the head node is null.

    You're actually very close to it. You've identified what the problem is - i.e. that "head" never changes.

    Now look at the insert function. Ask yourself, where does it change the value of "head"?

    Then ask yourself, where should it change the value of "head"?

    Penny Arcade Developers at PADev.net.
  • urahonkyurahonky Registered User regular
    edited January 2009
    urahonky wrote: »
    This right here runs perfectly, except that node is never actually saved. I did an insert call in my main program, and it completes fine, but when I try to output the node it says the head node is null.

    You're actually very close to it. You've identified what the problem is - i.e. that "head" never changes.

    Now look at the insert function. Ask yourself, where does it change the value of "head"?

    Then ask yourself, where should it change the value of "head"?

    head is a private variable though, so I can't change it right? So shouldn't setting it equal to another node be the same thing as placing a new value in it?

    I feel like smacking my head in the desk :(

    Games completed recently: Dragon's Crown, Knights of Pen and Paper, Castlevania: Symphony of the Night (20th time), Defender's Quest, The Witcher
  • urahonkyurahonky Registered User regular
    edited January 2009
    Oh mother of Christ. I'm such an idiot... I completely forgot that I am still in the .cpp file that is attached to the .h file, so I can modify head. Ugh. I'm sorry for wasting your time eeccccoo :(

    Games completed recently: Dragon's Crown, Knights of Pen and Paper, Castlevania: Symphony of the Night (20th time), Defender's Quest, The Witcher
  • ecco the dolphinecco the dolphin Registered User regular
    edited January 2009
    urahonky wrote: »
    head is a private variable though, so I can't change it right?

    I feel like smacking my head in the desk :(

    Not quite. If head is a private variable, then it means that it can only be changed by member functions, not by everyone. You can change it, but only inside the member functions (like your insert function).
    urahonky wrote: »
    So shouldn't setting it equal to another node be the same thing as placing a new value in it?

    It would be, but what you've done is the opposite. Instead of setting head equal to another node, you've set another node equal to the value of head. i.e. you've copied the value of head into the "node" variable, but "head" itself remains unchanged.
    urahonky wrote: »
    I feel like smacking my head in the desk :(

    Been there, done that. =/

    Edit:
    urahonky wrote: »
    Oh mother of Christ. I'm such an idiot... I completely forgot that I am still in the .cpp file that is attached to the .h file, so I can modify head. Ugh. I'm sorry for wasting your time eeccccoo :(

    Also, been there, done that.

    Penny Arcade Developers at PADev.net.
  • LoneIgadzraLoneIgadzra Registered User regular
    edited January 2009
    Since we're sort of OP mode here, let me add my two cents: If you're at all serious about programming, buy some books.

    If nothing else, I am of the opinion that every programmer should own a copy of "Code Complete" by Steve McConnell. This is the kind of book where there are a lot of sections that will be immediately relevant to a novice such as the sections on code formatting and variable use, and sections that you will grow into as you get better (there is oodles of material on being part of and managing real world projects). If you've ever asked yourself questions like, "Should I throw an exception here?" this fucker has the answer.

    For the prospective Cocoa programmer, I really recommend "Cocoa Programming For Mac OS X" by Aaron Hillegass. It'll make your life a lot easier and just walk you through all important concepts of building Cocoa apps like a breeze. You can get this information from online tutorials and reading Apple documentation, but this way is so much less painful and quicker - and, dare I say, fun. The book is laid out like one long tutorial and chalk full of screenshots and excellent diagrams and explanations that cover the most important points concisely and in an easy-going comprehensible manner.

    Will mention more as I get cash.

    I am also taking recommendations on a C++ book for a more experienced programmer. I figure I really ought to get good at this thing, but my comp sci intro class textbook is this super thick piece of crap that's all hung up on explaining the glory of Abstract Data Types to peasants who, presumably, have never known anything other than C and Assembly.
    urahonky wrote: »
    Hey guys. I really, REALLY didn't want to post here because I wanted to figure out this project myself, but I'm a retard and can't figure anything out in programming apparently (tell me why I am going for this degree if I'm not even good at it?)

    Your first mistake is you're trying to do it in C++, the language where you can have absolutely nothing wrong with your understanding of the algorithm but still screw up some little bit of syntax and get an incomprehensible error message. :?

    Edit: I have a question of my own. I don't yet own the book, and I'm trying to figure something out in my C# / Windows Forms application: Do I need to implement "Dispose()", and, if so, how should I do it? Should I call it on my own objects that are no longer needed? MSDN is, as ever, pretty helpful, but it lacks the ultimatum of "should" or "shouldn't" that I'm looking for. I am currently giving myself a headache trying to figure out if I need to be sure to null member objects that have already been disposed and prevent calling dispose on them again in the containing class' dispose method and really I should probably just sleep on it.

  • AngelHedgieAngelHedgie Registered User regular
    edited January 2009
    Properties too AH. Methods and properties (dunno if you include properties when you say "functions").

    I dont have VS sitting in front of me: when inheriting from an abstract class (.NET), are you required to provide override implementations of all methods and properties of the abstract class?

    Properties, no (there's no such thing as a "virtual property"), but yes, classes have to implement the methods in an interface.

    XBL: Nox Aeternum / PSN: NoxAeternum / NN:NoxAeternum
    Spoiler:
  • His CorkinessHis Corkiness Registered User
    edited January 2009
    Edit: I have a question of my own. I don't yet own the book, and I'm trying to figure something out in my C# / Windows Forms application: Do I need to implement "Dispose()", and, if so, how should I do it? Should I call it on my own objects that are no longer needed? MSDN is, as ever, pretty helpful, but it lacks the ultimatum of "should" or "shouldn't" that I'm looking for. I am currently giving myself a headache trying to figure out if I need to be sure to null member objects that have already been disposed and prevent calling dispose on them again in the containing class' dispose method and really I should probably just sleep on it.

    Your first mistake is that you're doing it in C#, the language with a hackish RAII idiom. :P

  • His CorkinessHis Corkiness Registered User
    edited January 2009
    Properties too AH. Methods and properties (dunno if you include properties when you say "functions").

    I dont have VS sitting in front of me: when inheriting from an abstract class (.NET), are you required to provide override implementations of all methods and properties of the abstract class?

    Properties, no (there's no such thing as a "virtual property"), but yes, classes have to implement the methods in an interface.
    public interface IFoo
    {
        string Name { get; }
    }
    
    public class Bar : IFoo
    {
        string Name
        {
            get
            {
                return "Tom";
            }
        }
    }
    

  • LoneIgadzraLoneIgadzra Registered User regular
    edited January 2009
    Edit: I have a question of my own. I don't yet own the book, and I'm trying to figure something out in my C# / Windows Forms application: Do I need to implement "Dispose()", and, if so, how should I do it? Should I call it on my own objects that are no longer needed? MSDN is, as ever, pretty helpful, but it lacks the ultimatum of "should" or "shouldn't" that I'm looking for. I am currently giving myself a headache trying to figure out if I need to be sure to null member objects that have already been disposed and prevent calling dispose on them again in the containing class' dispose method and really I should probably just sleep on it.

    Your first mistake is that you're doing it in C#, the language with a hackish RAII idiom. :P

    No shit, it's pissing me off. I like my languages elegant and with one right answer. Edit: Not seeing the RAII thing though. Seems like any other garbage collected language, where every now and then any objects that no variables are pointing to get reclaimed. (Whereas C++ objects are destructed the instant they go out of scope.) Except with the addition that you can dispose of them explicitly, too.

    No choice though. Gotta be a Windows database-driven app and fuck if I'm using MFC and C++ or some shit. I'd probably still be trying to get the DataGridView to work if I hadn't done it hack and slash in C#.

    Incidentally, the reason I'm asking such a question is I'm currently embroiled in a major re-factoring of the app. What I did first was just get the damn thing working by writing a bunch of code to manage a DataGridView and a MySQL connection for the main window. Then I added some other windows to display other tables in the database and just copied and pasted and modified the code slightly.

    Obviously that's a shitty state of affairs, so now I'm writing a "DataGridViewManager" class to encapsulate all the interactions between the DataGridView and the Database so that all windows are using the same code. I figure since these will last the entire life time of the program I don't need to worry about anything besides making sure the MySQL connection gets closed, but I still want to get it right.

  • His CorkinessHis Corkiness Registered User
    edited January 2009
    I've never used the language, but I hear that D combines the best of both worlds. The Garbage Collector is able to free memory whenever the hell it feels like it, but objects still have destructors which are called deterministically as soon as an object is no longer referenced.

    The more I use C# the more I prefer it over C++, but I do love C++'s RAII. And templates, though they're not perfect by any means.

  • LoneIgadzraLoneIgadzra Registered User regular
    edited January 2009
    Can't say as I've had any positive experiences with C++ RAII to date. It relies an incredible amount on implicit behavior of the language such that you have to read docs upon docs to fully understand, and even then what I often really need is just some decent reference counting on a shared object, which can get syntactically nightmarish even if you let Boost do it for you.

    Still taking book recommendations. C++ FAQ Lite sucks.

  • NightslyrNightslyr Registered User regular
    edited January 2009
    Still taking book recommendations. C++ FAQ Lite sucks.

    I've found that the two Thinking in C++ books are pretty good. They assume that the reader has basic knowledge of C (or, really, any other similar language...hell, I had no problem following along with most of it, and my 'best' language is PHP), and, from what I can tell, they cover most of Standard C++.

    My PA, PSN, XBL, Origin, and Steam names are the same. 3DS Friend Code: 1607-1682-2948
    steam_sig-400.png
    Stack Exchange | http://www.mpdevblog.blogspot.com
  • PantsBPantsB Registered User regular
    edited January 2009
    Books:
    PERL :
    Camel Book
    Llama Book
    PERL in a Nutshell

    C:
    K&R aka the Bible - might not be great for starting out though.

    11793-1.png
    Spoiler:
  • elkataselkatas Registered User regular
    edited January 2009
    Since we're sort of OP mode here, let me add my two cents: If you're at all serious about programming, buy some books.

    I dunno about that. I do programming for my living, but I have never founds them that useful, because typical programming books tend to be so goddamn thick that they can't be browsed quickly. Furthermore, you can't cut-copy-n'-paste stuff from them. But then again, I'm usually working with VB.net and C#, and developer centers for those are very good.

    Hypnotically inclined.
«13456763
This discussion has been closed.