Jump to content
The Dark Mod Forums

Learn to program


pakmannen

Recommended Posts

while you could have intepreted C if you really wanted to.

 

Not really IMO. After all, asm is a valid keyword in C to inject inline assmebling instructions, and you probably would have a hard time interpreting this as well. Theoretically you might be able to, but then you would have to write an emulator to interpret your C code. :P

As long as you only use "regular" C, then you are right though. :)

Gerhard

Link to comment
Share on other sites

  • Replies 63
  • Created
  • Last Reply

Top Posters In This Topic

"static" is certainly not associated to OO in any way. Your example is correct but doesn't go deep enough. static is also available in plain C where no OO existed and simply describes a variable that is immediately available like a globhal variable, only with a limited scope.

 

The example was in Java though, where static only has a single meaning.

Link to comment
Share on other sites

I just came across static today actually, while installing php5 on my computer (which has better OO support, I'm told)

 

I've played around a bit, and read some examples at php.net. Here's how I understand it: A function or a variable within a class can be static. This means you can use them without creating an object. In php it looks like this:

   class A
  {
   static function foo() { }
   function bar() { }
  }
  A::foo();
  $obj = new A;
  $obj->bar();

And yeah, that obviously means you can't use $this-> in a static function, since no object exists. Your post made more sense when I sat down and tried some code. In the real world, when do you want to use a static something? It's always easier to understand things if you get a concrete example of its usage. Something php.net always manages to avoid.. :P Why put a function inside a class if you want it static?

 

Oh, and what do you guys mean by "method"?

Link to comment
Share on other sites

Hey Pak - the way I think about "static" is;

 

You make lots of the same objects by making a class and then instantiating it however many objects you want. Each of those objects have their own variables.

 

But if you declare some variable as static, then it is a single variable that all of the instances will share. If one changes it, the others will see the change.

 

Same with functions - all functions in the class will be run "within" the object, as if each of them have their own copy. You would make a static function if you just want a function that can run on its own without being a part of an object.

 

An example is letting the objects know how many copies of themselves currently exist.

To be programming with proper standards, you'd create AddToTotal, SubtractFromTotal, and GetTotal static functions. Each time an object is created, they would call AddToTotal. Each time one is told to die, they would call SubtractFromTotal. And each time an object wanted to know how many copies are around it would call GetTotal. All these functions use the same static variable called total. Of course for something this simple you could be forgiven for breaking "proper practices" and just have the one static variable accessed directly rather than cluttering the code with 3 redundant functions.

 

Oh, and what do you guys mean by "method"?
A method is a name for a function in a class that is not static. It's just a way of saying that this function is meant to operate on the object, and not used on its own.
Link to comment
Share on other sites

Why put a function inside a class if you want it static?

In Java's case, because you can't have a function that's not inside a class. <_< Every class must have its own .java file, and each .java file must contain exactly one class, and nothing apart from that class is allowed in the file - except for comments and import statements and such. So if you want a global function, it has to be made static on a class somewhere.

 

There are uses for it which aren't dictated purely by somewhat-arbitrary fiats of the language, though. There are occasions when a method naturally belongs with a particular class, or it's nice to group it with a class for purposes of organisation, but there's no need to require that an object of the type is created. Or sometimes they're used in place of constructors, for various reasons (sometimes being able to give your constructors names is handy, for example). The Java API actually does this a lot; they're big fans of the "factory pattern".

 

You can also have static variables, which can be used as global variables or to pass information between objects of the same class.

My games | Public Service Announcement: TDM is not set in the Thief universe. The city in which it takes place is not the City from Thief. The player character is not called Garrett. Any person who contradicts these facts will be subjected to disapproving stares.
Link to comment
Share on other sites

Every class must have its own .java file, and each .java file must contain exactly one class, and nothing apart from that class is allowed in the file - except for comments and import statements and such.

Strictly speaking, this is not true. You can have nested classes, private classes, protected classes, local/member classes, anonymous classes, even interfaces all within the same .java file. You can only have one public class, however.

Link to comment
Share on other sites

Why put a function inside a class if you want it static?

 

This is sometimes usefull if you want to document the closeness to some object, or sometimes it's needed for technical reasons.

 

For example, you could write a calendar class. In this class you have several methods, that deal with all kind of things that are needed for a calendar class. Of course usually you will want to access the current data to process some function. For example, you write a function that determines the differences between two dates and return the number of days or number of seconds between them. Whatever.

 

class calendar
{
  public long Diff(calendar);
}

 

So this function returns the number X between the current date of the calss itself and the one passed in.

however, you might provide an additional function that also returns the difference, but between two arbitrary dates without an object. Since you already have the above function, such an additional function would come almost for free, as it is basically the same algorithm.

public long Diff(calendar, calendar);

 

In this case, the function doesn't really need the object because it already got both dates passed in. In this case you can write it as a firend function or a static function. The reason is, that it doesn't need an object and therefore the user shouldn't be needed to create an object just for the purpose of the calculation.

 

Maybe that's not a good example, but one where I would use static. Another example could be a singleton. Hery ou create the object only once, when it is created. So you can construct it somewhere unrelated, and provide a static function that returns the single object. This is a rather typical usage IMO.

 

Oh, and what do you guys mean by "method"?

 

In C++ this is just another name for function.

Gerhard

Link to comment
Share on other sites

Of course for something this simple you could be forgiven for breaking "proper practices" and just have the one static variable accessed directly rather than cluttering the code with 3 redundant functions.

 

IMO such functions are not redundant, because you certainly don't want to mess some other code with that value. So it makes sense to provide such functions. You can flag them as inline though, because then they will operate exactly as if they had direct access to the variable without the problem of unrelated code being able to change it.

Gerhard

Link to comment
Share on other sites

IMO such functions are not redundant, because you certainly don't want to mess some other code with that value. So it makes sense to provide such functions.
Yes you are right, that's what they're for.

 

But what I said was, for very simple circumstances, you can do without them (as you know). Even if only to make the code easier to read for a human. A real world example is the Vector3 class in pretty much any physics library or game engine. The .x, .y, and .z variables are public with no accessor or mutator functions, this simplifies the appearance of the code and lets you treat it as if it were a basic data type, yet the object is still more than a data structure, it comes with its own functions for performing Vector arithmetic.

 

In C++ this is just another name for function.

Well, a method is a function, but I wouldn't say it's "just another name" for one. I'd say a method is a type of function, though.

 

As I said, this term refers to a function used in a class to operate within the object, change the object's data, etc. you can't (and wouldn't want to) call this function unless it's via an instantiated object, where it's useful.

http://cplus.about.com/od/glossar1/g/methoddefn.htm

Probably a more common term is member functions (and member variables). Again, member just means these functions or variables belong to an object and don't operate on their own.

http://www.steveheller.com/glossm.htm

Link to comment
Share on other sites

Thanks for the replies and examples guys, I think I more or less understand what static does.

 

I've been learning about "accessor methods" or something like that today. Let's see if I got this straight. Objects should be self-contained and their variables preferably private or protected. This means that you have to write Get() and Set() functions/methods to retrieve and update variables from outside the class. In php this looks like:

class MyClass
{
public function __get($var)
{
	return $this->$var;
}

public function __set($var, $val)
{
	$this->$var = $val;
}	
}

I've tried it and it works and such, but again I'm wondering why.. Why should objects be self-contained? Why can't their variables be public? Is it about security? Or is it just confusing with a lot of variables everywhere? Does it affect performance?

 

(For the curious, the __ thing before the function name indicates that it's "magical". I think it's a php thing but I'm not sure. It means when you do $object->var=$val; it automatically runs the __set() function, if you've written one. You don't need to type $object->__set($var)=$val;)

Link to comment
Share on other sites

I've tried it and it works and such, but again I'm wondering why.. Why should objects be self-contained? Why can't their variables be public? Is it about security? Or is it just confusing with a lot of variables everywhere? Does it affect performance?

It's a design issue and it makes your life easier on the long run. The calling code doesn't want to or need to know how the "inner workings" of a class look like. Imagine a class car with a method, say changeOil(). The calling code doesn't want to know how exactly the oil is to be changed, it just needs to know how to call changeOil. This way you can easily swap your car class with a slightly different car class without a need to change the calling code, as long as the changeOil()interface stays the same. Hence it's a code compatibility issue.

 

It does affect performance, although only minimally. For the very rudimentary accessors you can inline your methods (at least in C++, I don't know a thing about Java).

 

I can give you another example from DarkRadiant (a little simplified): We have the class Entity, which has the method setKeyValue(string key, string value). How is the key/value pair actually stored? In fact, the client class doesn't care about that nor does it need to. That's implementation detail of the Entity class, and no one else's business. The Entity class might as well be rewritten and the storage variables might get changed, but the interface stays the same, and so does the calling code.

Link to comment
Share on other sites

I've tried it and it works and such, but again I'm wondering why.. Why should objects be self-contained? Why can't their variables be public? Is it about security? Or is it just confusing with a lot of variables everywhere? Does it affect performance?

 

To add to what Greebo said above about interface/implementation, often the variables in a class need to obey some kind of constaint. For instance, if you have a class Date with a method setMonth(), this method would obviously ensure that the month given was valid (1 - 12). If you left the variable exposed, some other code could just overwrite the month value with 99, violating the constraint of your class and possibly breaking lots of other code.

 

Another reason is that the getXXX() method might not actually refer to a variable at all, but might retrieve the value on demand (such as from a database). By designing the external interface around a get method you avoid imposing unnecessary constraints on how and where data should be stored.

 

For very simple classes, such as Vector3, get/set methods are probably not necessary. The working rule I use for DarkRadiant is that a simple data class that contains no methods can have public data, but if it has any methods other than constructors it should have private data and get/set methods.

 

(The worst example of this design idiom being violated I have seen to date concerns some code I am dealing with at work at the moment: it reimplements a hashtable (for no reason whatsoever) using two separate ordered lists of strings, corresponding to the keys and the values respectively; however, both of these lists are public so some other code could just replace them with lists of different sizes, types or even set them to null and the class would just carry on as if nothing had happened).

Link to comment
Share on other sites

Bascially, if you have simple variables, and you know they will never used in a more complex way, then you can just as well make them public. Get/Set methods, is exactly this. Making it public with a more complex interface. In some cases it might be usefull though. For example, if you want to allow to set the index into an array, you may not want the caller to be able to set the index higher then the lase element, so you would write a setter and getter method, and in the setter you validate the value and adjust it.

 

Usually it's also a good idea, to decleare simple setters and getters as inline.

Gerhard

Link to comment
Share on other sites

A method is just a function which is attached to an object (i.e. it is a member function of that class, which may or may not be static). In C++ the distinction is purely syntactical, whereby methods get compiled to a function which has an additional "this" parameter representing the object it is operating on, whereas in other languages there might be more of an implementational difference between them.

Link to comment
Share on other sites

So to sum up, using functions to change/retrive data gives 2 major benifits;

 

*The way that data is changed/retrived can be modified by a coder without affecting the rest of the program. (Eg. putting mail in the letterbox without caring when or how the mailman's routes have changed in your area)

 

*The way that data is changed/retrived is always controlled by that object and can't be inteferred with by external objects. (Eg. as opposed to walking into someone's house and borrowing their power screw driver without asking, and they come back and find they can't continue work on their house)

Link to comment
Share on other sites

I just saw this thread and in reply to a few posts about C#.. It's not that bad. I'm pretty much forced to use it, as it's what's used in all the classes I take.. But I find myself missing C++ while using it.

 

Plus, a friend who works for the Collective(Episode 3, Indiana Jones) has to use C# to work with the 360. Or is what he told me. A little bit of a factor there, I guess.

Link to comment
Share on other sites

Well, I've been fiddling with it for a few days now. Read a lot of articles about it. (This is a php implementation we're talking about, and I know it differs slightly from, say, Java) It really doesn't help that people can't agree on how it should function, and that there are countless variations and a whole lot of unfamiliar terminology. (The deeper you dig..)

 

I posted this rather long thread over at Sitepoint today. MVC Madness. Not sure if you guys would understand it without knowing php. I don't really know how similar it is to other languages.

 

Basically it's a lot of information to digest; some things make perfect sense while I struggle to understand other parts. I think I'm just going to take a long walk or something.. Before I go completely nuts.. :)

Link to comment
Share on other sites

Depends what you want to code. It's mostly database stuff. I haven't done any in a while but I have used php5 a little.

Well, take a look at the link I posted above, if you dare.. I'm trying to learn more about object oriented programming, and how you apply it to websites. The MVC pattern seems to be what most people advocates. Even if apparently no one agrees on what it really means.. <_< Just take a look at some of the replies I got.

Link to comment
Share on other sites

  • 2 weeks later...
In answer to your question - I don't know! I program to create sites and only take what I need. That stuff is beyond me tbh. I have some formal Javascript, Visual Basic (and thus ASP as they have very similar structures) and Relational Database design training (that I did for fun/CV) and as from my point of view as long as you create a robust database it won't matter about the UI at all - it's the underlying queries that supply the responses and it's up to the UI programmer to package them properly. The Sitepoint discussion goes into areas I have nooooo idea about.

Yeah, about that Sitepoint forum, it's a like a new world opening up I had no idea existed.. Basically, what happened was I'm part of quite a complex project, and maintainance was getting out of hands. Whenever you did something you'd break something else etc. Things were, to say the least, a mess. That's why I began looking at design patterns and frameworks which eventually led me to this whole MVC debacle. Suffice to say, it's rather complicated. :P Even if I think I'm slowly getting the hang of it. Actually, I've got the MVC part covered. Now I'm wrestling with how to structure Domain Logic. Working on an Active Record implementation which is trickier than I thought.

 

I can recommend Martin Fowler's Patterns of Enterprise Application Architecture if you want to get into this stuff.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recent Status Updates

    • Petike the Taffer

      I've finally managed to log in to The Dark Mod Wiki. I'm back in the saddle and before the holidays start in full, I'll be adding a few new FM articles and doing other updates. Written in Stone is already done.
      · 1 reply
    • nbohr1more

      TDM 15th Anniversary Contest is now active! Please declare your participation: https://forums.thedarkmod.com/index.php?/topic/22413-the-dark-mod-15th-anniversary-contest-entry-thread/
       
      · 0 replies
    • JackFarmer

      @TheUnbeholden
      You cannot receive PMs. Could you please be so kind and check your mailbox if it is full (or maybe you switched off the function)?
      · 1 reply
    • OrbWeaver

      I like the new frob highlight but it would nice if it was less "flickery" while moving over objects (especially barred metal doors).
      · 4 replies
    • nbohr1more

      Please vote in the 15th Anniversary Contest Theme Poll
       
      · 0 replies
×
×
  • Create New...