Author Topic: RAWK Web Development Circle  (Read 118981 times)

Offline iSmiff

  • TECHNOBORE
  • RAWK Supporter
  • Legacy Fan
  • ******
  • Posts: 18,131
Re: RAWK Web Development Circle
« Reply #80 on: July 10, 2008, 11:34:31 am »
when he moves past the year 2000 we can continue the debate he started
STFU and agree with me.

Offline Deano06

  • Confirmed BOFH TECHNOBORE#1
  • Anny Roader
  • ****
  • Posts: 425
  • Smarter than you.
  • Super Title: Or is he?
Re: RAWK Web Development Circle
« Reply #81 on: July 10, 2008, 01:21:32 pm »
I haven't shown off or trolled. Except asking for iSmiff opinion because appearently he's a tech pro I thought? Or is he a consumer? I can't remember now..Of course I'm being incredulous...

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #82 on: July 10, 2008, 02:53:32 pm »
You can use Pyhon like language-like constructs (endifs  instead of closing curly brackets etc)
Python uses neither braces nor endifs. The end of blocks is determined by indentation, i.e.
Code: [Select]
def myCoolFunc(arg1, arg2):
    result = arg1 + arg2
    return result

arg1 = 1
arg2 = 2
result = myCoolFunc(arg1, arg2)
Funny ruby has such shit text encoding considering it's Japanese.
I said unicode, not text encoding. One is not the same as the other. Ruby uses multiple bytes to encode Japanese characters. It's text processing functions are byte-based, not character-based. There are external packages available and some regular expression support, but unicode on Ruby is currently a massive hack.

You really need to work on your manners, young man.

Slick_Beef: it doesn't really only support ASCII, but as it doesn't support unicode properly, you have to dick around with encodings a lot.

If you're using non-ASCII characters in source code, I think you have to set the $KCODE global to your encoding, but don't take my word for it.

I'd go with Python and Django instead. That's mostly down to the fact that I'm much more comfortable with Python than Ruby, but that in itself is a result of my fucking off Ruby a couple of years back because I work with a lot of non-ASCII text and Python has unicode built in.

Ruby's a lovely language, and very, very powerful, but no native unicode is a deal-breaker for me.

When I get a bit of time, I want to have a good look at MacRuby, though. It's fully-integrated with OS X Objective-C libraries, so it natively supports unicode, true threads and all other Objective-C classes. It also uses the Objective-C garbage collector, which is much, much faster.
Quidquid latine dictum sit, altum sonatur.

Offline MaschHead

  • Legacy Fan
  • ******
  • Posts: 1,953
Re: RAWK Web Development Circle
« Reply #83 on: July 10, 2008, 02:57:27 pm »
Just found this thread, I do web-development as a job  :butt

Working with asp.net (both vb.net & c#) and all the MS stuff that comes with it :P

Currently learning php/mysql as a hobby, much cheaper in hosting and stuff ;)

Offline iSmiff

  • TECHNOBORE
  • RAWK Supporter
  • Legacy Fan
  • ******
  • Posts: 18,131
Re: RAWK Web Development Circle
« Reply #84 on: July 10, 2008, 03:07:39 pm »
I haven't shown off or trolled. Except asking for iSmiff opinion because appearently he's a tech pro I thought? Or is he a consumer? I can't remember now..Of course I'm being incredulous...

When you're done correcting all the mistakes that wacko just showed you can  go and find where I claimed to be a tech pro.

I know what I know, no more no less and unlike yourself don't have a need to brag about it or show off, how's that latest bout of showing off working for you by the way ;D
STFU and agree with me.

Offline Mudface_

  • Boys Pen
  • *
  • Posts: 0
Re: RAWK Web Development Circle
« Reply #85 on: July 10, 2008, 03:07:46 pm »
Ruby's a lovely language, and very, very powerful, but no native unicode is a deal-breaker for me.

When I get a bit of time, I want to have a good look at MacRuby, though. It's fully-integrated with OS X Objective-C libraries, so it natively supports unicode, true threads and all other Objective-C classes. It also uses the Objective-C garbage collector, which is much, much faster.

I might take a look at IronRuby and IronPython if I get some spare time at work, although neither are complete as yet.

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #86 on: July 10, 2008, 04:55:01 pm »
I might take a look at IronRuby and IronPython if I get some spare time at work, although neither are complete as yet.
I'd definitely recommend it. Resolver One, a heavy-duty, programmable spreadsheet program is built on .NET using IronPython.

Ruby is conceptually, and practically, a very beautiful and powerful language. I must admit I'm not a fan of the implicit returns and some of the more cryptic, Perl-like syntax, though.

Know nowt about IronRuby, though.
Quidquid latine dictum sit, altum sonatur.

Offline Mudface_

  • Boys Pen
  • *
  • Posts: 0
Re: RAWK Web Development Circle
« Reply #87 on: July 10, 2008, 06:03:10 pm »
Ah, according to Wiki, Ironruby is still in Alpha and there's no Rails implementation as yet.

RoR does seem to have a fanatical userbase, but I've seen quite a number of articles doubting its practicality, in particular a massive rant from a former developer about the community and problems with the language which I'll have to trawl Slashdot for, it's well worth reading.

Offline Mudface_

  • Boys Pen
  • *
  • Posts: 0
Re: RAWK Web Development Circle
« Reply #88 on: July 10, 2008, 06:18:03 pm »
Here it is. Long but worth a read.

That spreadsheet looks very interesting. You can access the Excel/ Access/ Word object models from within Visual Studio, but there's no 'VBA.NET' unfortunately, so you can't use it directly within the Office programs, presumably because of the massive amount of legacy code that would get broken. Doing something like this would be very nice.

Offline Slick_Beef

  • RAWK's Master Baker
  • RAWK Supporter
  • Legacy Fan
  • ******
  • Posts: 9,087
Re: RAWK Web Development Circle
« Reply #89 on: July 10, 2008, 07:39:06 pm »
Well, having practiced with both RoR and ASP.net today I'd definetly say my preference is ASP.net... It seems powerful enough and well supported, and I was able to put things together much quicker than I was with RoR (although this is partly because I've used asp and VB6 a lot in the past so the transition was fairly straightforward..). That Visual Web Developer makes things so straightforward I almost feel like I'm cheating, but I'm willing to sacrifice some pride to make things more straightforward.

Anyway, still need to learn both. Got a call today for an interview on monday morning so I'm going to do some proper swotting up this weekend!

Offline Mudface_

  • Boys Pen
  • *
  • Posts: 0
Re: RAWK Web Development Circle
« Reply #90 on: July 10, 2008, 08:03:22 pm »
Slick- take a look at Scott Guthrie's data access tutorials, they give a nice way of implementing a simple n-tier type application. He uses datasets which I'm a bit ambivalent about- I prefer using domain objects as they're lighter and more flexible, but they involve writing a lot more code. This starter kit gives a very good example of using domain objects and many of the ASP.NET features, but to get the most out of it, you'll really need the accompanying book linked to there, and it's only in C#.

Offline Slick_Beef

  • RAWK's Master Baker
  • RAWK Supporter
  • Legacy Fan
  • ******
  • Posts: 9,087
Re: RAWK Web Development Circle
« Reply #91 on: July 10, 2008, 08:06:42 pm »
Nice one mate, I'll give those links a read over the weekend. In the middle of reading that RoR rant at the moment ;D An angry, angry man (some fair points mind you)

Offline Mudface_

  • Boys Pen
  • *
  • Posts: 0
Re: RAWK Web Development Circle
« Reply #92 on: July 10, 2008, 08:09:12 pm »
I loved it- a bit too Maddox-esque, but he obviously hates those people with a passion.

Offline Slick_Beef

  • RAWK's Master Baker
  • RAWK Supporter
  • Legacy Fan
  • ******
  • Posts: 9,087
Re: RAWK Web Development Circle
« Reply #93 on: July 10, 2008, 08:20:51 pm »
I loved it- a bit too Maddox-esque, but he obviously hates those people with a passion.

Hahaha, I was thinking the same...if he was using slightly larger font I would think it was maddox

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #94 on: July 10, 2008, 09:30:27 pm »
Here it is. Long but worth a read.

That spreadsheet looks very interesting. You can access the Excel/ Access/ Word object models from within Visual Studio, but there's no 'VBA.NET' unfortunately, so you can't use it directly within the Office programs, presumably because of the massive amount of legacy code that would get broken. Doing something like this would be very nice.
That rant is genius. They are a rabid lot, RoR devs. That's already the beginning of the end for them, if you ask me. Really bad case of not-invented-here syndrome.

I think Resolver One is intended more as a replacement for Excel than an add-on.

Can you do meta-programming like that in C# (i.e. automatically generate and execute C# code from a C# program)?
Quidquid latine dictum sit, altum sonatur.

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #95 on: July 10, 2008, 09:37:19 pm »
Going through that rant again, does anyone else here think perhaps Deano06 should be a Rails dev?
Quidquid latine dictum sit, altum sonatur.

Offline iSmiff

  • TECHNOBORE
  • RAWK Supporter
  • Legacy Fan
  • ******
  • Posts: 18,131
Re: RAWK Web Development Circle
« Reply #96 on: July 10, 2008, 10:03:48 pm »
He certainly ticks all the boxes.
STFU and agree with me.

Offline Mudface_

  • Boys Pen
  • *
  • Posts: 0
Re: RAWK Web Development Circle
« Reply #97 on: July 10, 2008, 10:24:49 pm »
I think Resolver One is intended more as a replacement for Excel than an add-on.

Yeah I got that, I was just saying it's a shame Excel itself doesn't support a "VBA.NET" language so you could import your own .NET functions.

Quote
Can you do meta-programming like that in C# (i.e. automatically generate and execute C# code from a C# program)?

Not so far as I know. I suppose the closest thing is reflection.

Offline iSmiff

  • TECHNOBORE
  • RAWK Supporter
  • Legacy Fan
  • ******
  • Posts: 18,131
Re: RAWK Web Development Circle
« Reply #98 on: July 10, 2008, 11:09:02 pm »
Don't listen to Mudface, he makes bleach for a living...
STFU and agree with me.

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #99 on: July 10, 2008, 11:36:21 pm »
Yeah I got that, I was just saying it's a shame Excel itself doesn't support a "VBA.NET" language so you could import your own .NET functions.
Got you. That is a bit dumb. Personally, I despise Excel (and other spreadsheets) on account of the spasticity they have for a 'language'.
Not so far as I know. I suppose the closest thing is reflection.
I'm no expert, but I think reflection and an eval function will get you most of the way there.
Quidquid latine dictum sit, altum sonatur.

Offline Bushy

  • Hrtfordshir
  • Legacy Fan
  • ******
  • Posts: 1,222
  • ANNUAL RANDOM RaWKITE 2006
Re: RAWK Web Development Circle
« Reply #100 on: July 10, 2008, 11:46:40 pm »
I've done a descent ish amount of html, looking into learning php I think as the way forward, have a website to join in the running of so can sort of learn by looking through and figure it out from there, also got a website to design for a DJ friend of mine soon so will need to get arse in gear soon! in any case, thought an answer in this thread will be handy for when I get stuck! ;D

Offline Deano06

  • Confirmed BOFH TECHNOBORE#1
  • Anny Roader
  • ****
  • Posts: 425
  • Smarter than you.
  • Super Title: Or is he?
Re: RAWK Web Development Circle
« Reply #101 on: July 11, 2008, 06:18:21 am »
Python uses neither braces nor endifs. The end of blocks is determined by indentation, i.e.
Code: [Select]
def myCoolFunc(arg1, arg2):
    result = arg1 + arg2
    return result

arg1 = 1
arg2 = 2
result = myCoolFunc(arg1, arg2)

First of all I was talking about PHP when i said isntead of curly brakets, PHP does definitely use curley brackets AND python DOES use endifs etc.

http://codesyntax.netfirms.com/lang-python.htm

Code: [Select]
# regular c style if statement
if (value is not None) and (value == 1):        # is tests for same object
  print "value equals 1",
  print " more can come in this block"

# if-else block
if (job == "millionaire") or (state != "dead"): # !=,== can be used for strings
  print "a suitable husband found"              # <> for lexographical compare
else:
  print "not suitable"

list1 = (1,2,3,9)
list2 = (1,2,7)
# comparing lists / tuples compares var by var until one is different
if (list1 <= list2) and (not age < 80):
  print "1 = 1, 2 = 2, but 3 <= 7 so its True"

# short form with no blocks is also ok
if ok: print "ok"

# since there is no switch statement, this is the shortest way to reproduce
if (i == 1): do_something1()
elif (i == 2): do_something2()
elif (i == 3): do_something3()
else: do_something4()





So clearly youve never used python at all or just not very much :S.
« Last Edit: July 11, 2008, 06:21:34 am by Deano06 »

Offline Deano06

  • Confirmed BOFH TECHNOBORE#1
  • Anny Roader
  • ****
  • Posts: 425
  • Smarter than you.
  • Super Title: Or is he?
Re: RAWK Web Development Circle
« Reply #102 on: July 11, 2008, 06:24:44 am »
I said unicode, not text encoding

ummmmmmmmmmmmmmmmmm yeah and Unicode is a character encoding....which Ruby DOESN'T support.

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #103 on: July 11, 2008, 08:40:21 am »
First of all I was talking about PHP when i said isntead of curly brakets, PHP does definitely use curley brackets AND python DOES use endifs etc.

http://codesyntax.netfirms.com/lang-python.htm

Code: [Select]
# regular c style if statement
if (value is not None) and (value == 1):        # is tests for same object
  print "value equals 1",
  print " more can come in this block"

# if-else block
if (job == "millionaire") or (state != "dead"): # !=,== can be used for strings
  print "a suitable husband found"              # <> for lexographical compare
else:
  print "not suitable"

list1 = (1,2,3,9)
list2 = (1,2,7)
# comparing lists / tuples compares var by var until one is different
if (list1 <= list2) and (not age < 80):
  print "1 = 1, 2 = 2, but 3 <= 7 so its True"

# short form with no blocks is also ok
if ok: print "ok"

# since there is no switch statement, this is the shortest way to reproduce
if (i == 1): do_something1()
elif (i == 2): do_something2()
elif (i == 3): do_something3()
else: do_something4()





So clearly youve never used python at all or just not very much :S.
Please point out one endif in the above code you just quoted.

Brackets are only necessary in if statements to set precedence.
if i == 1 or i == 2:
is perfectly valid.
if i == 1 or (i == 2 or i == 5):
is where you might need brackets.

In the second example, the definition of tuples (not lists, as you say, which are defined with []--there's a big and very important difference in Python), the brackets are also entirely unnecessary. You can remove every bracket in the code you quoted above except after the functions calls (do_something1() etc.) and it will run exactly the same.

Now, what you actually said was:
Quote
You can use Pyhon like language-like constructs (endifs  instead of closing curly brackets etc)
Apart from the nonsensical grammar of the sentence, it's also utterly false (i.e. no endifs as I said above).
ummmmmmmmmmmmmmmmmm yeah and Unicode is a character encoding....which Ruby DOESN'T support.
Unicode is indeed a character encoding, however it's also a multi-byte one. As I explained before, Ruby's text processing functions treat strings as a series of bytes, not characters, so you can't slice strings reliably or get their length, for example, without using external modules. Python, in contrast, has a native unicode string type which works perfectly well with string functions, string slicing etc. As long as you're careful to take care of encoding at IO barriers, you're golden.

That's the last reasonable answer you're going to get out of me if you continue to spout arrogant, ignorant shite and insults.

Great idea for a thread, and you've done a superlative job dragging it down into the gutter.  :wanker
« Last Edit: July 11, 2008, 08:44:08 am by wacko »
Quidquid latine dictum sit, altum sonatur.

Offline Deano06

  • Confirmed BOFH TECHNOBORE#1
  • Anny Roader
  • ****
  • Posts: 425
  • Smarter than you.
  • Super Title: Or is he?
Re: RAWK Web Development Circle
« Reply #104 on: July 11, 2008, 08:52:34 am »
Wacko I never insulted you or anyone and in fact I tend to agree with you as you're one of the only intelligent/informed people on this board, but my personal opinion is that Ruby isn't very good as a deployed language that's the bottom-line. Syntactically it's sound. But I think in terms of deployablility and flexibility for web-scripting PHP beats any language hands down at the moment.

If you read my original post in this board RE: Ruby you can see I was mainly agreeing with you but you got defensive.

Offline Deano06

  • Confirmed BOFH TECHNOBORE#1
  • Anny Roader
  • ****
  • Posts: 425
  • Smarter than you.
  • Super Title: Or is he?
Re: RAWK Web Development Circle
« Reply #105 on: July 11, 2008, 08:54:06 am »
on that note:

Javascript frameworks. I've never used any in production but Prototype/Scriptaculous. Played with JQuery in the early days.

Anyone got any thoughts. Anything better than Prototype out there for Ajax.

Offline Deano06

  • Confirmed BOFH TECHNOBORE#1
  • Anny Roader
  • ****
  • Posts: 425
  • Smarter than you.
  • Super Title: Or is he?
Re: RAWK Web Development Circle
« Reply #106 on: July 11, 2008, 08:57:15 am »
Ah, according to Wiki, Ironruby is still in Alpha and there's no Rails implementation as yet.

RoR does seem to have a fanatical userbase, but I've seen quite a number of articles doubting its practicality, in particular a massive rant from a former developer about the community and problems with the language which I'll have to trawl Slashdot for, it's well worth reading.

Is that the Rails Is A Ghetto by Zed Shaw? FUCKING HILARIOUS I've never laughed so much at a tech related blog before. Google Rails Is A Ghetto.

Rails is good for smaller applications, I know there are some big ones out there but its a very heavy framework. Alot of overhead for small actions.

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #107 on: July 11, 2008, 09:22:36 am »
my personal opinion is that Ruby isn't very good as a deployed language that's the bottom-line. Syntactically it's sound.
I agree. It's too slow.
But I think in terms of deployablility and flexibility for web-scripting PHP beats any language hands down at the moment.
PHP is great for little things (and its universal deployability), but I think it's a very badly-designed language. That's because I prefer OO, I guess.

So clearly youve never used python at all or just not very much :S.
This is insulting, particularly as it's very obvious I have much, much more experience of Python than you.
ummmmmmmmmmmmmmmmmm yeah and Unicode is a character encoding....which Ruby DOESN'T support.
This is also rude.

Tone it down.
Quidquid latine dictum sit, altum sonatur.

Offline Deano06

  • Confirmed BOFH TECHNOBORE#1
  • Anny Roader
  • ****
  • Posts: 425
  • Smarter than you.
  • Super Title: Or is he?
Re: RAWK Web Development Circle
« Reply #108 on: July 11, 2008, 09:59:03 am »
PHP isn't perfect. But love isn't about loving something that's perfect. It's about learning to love something that isn't perfect ;).

The OO of PHP is actually quite good, especially the overloading features. Generally though not having datatypes is shit. And not being able to use strings and numbers as objects is shit too. I think in PHP7. They need to really start thinking about implementing these types of things or someone should fork php and make a far cleaner, better designed version of the language.

PHP is flexible and doesn't enforce a coding style which I do like but means so many retards write terrible, terrible unreadable code.

Offline Mudface_

  • Boys Pen
  • *
  • Posts: 0
Re: RAWK Web Development Circle
« Reply #109 on: July 11, 2008, 10:04:25 am »
I'm no expert, but I think reflection and an eval function will get you most of the way there.

I'm far from an expert myself. I use attributes quite liberally to decorate my code, both custom and built-in, but the only time I've really used reflection has been to set the provider type for a website, e.g. the SQL Server provider in this case-

Code: [Select]
    public class EmployeeDetailsElement : ConfigurationElement
    {
 // other methods here

        [ConfigurationProperty("providerType", DefaultValue = "ChangeControl.DAL.SQLClient.SQLEmployeesProvider")]
        public string ProviderType
        {
            get { return (string)base["providerType"]; }
            set { base["providerType"] = value; }
        }
    }

 public abstract class EmployeesProvider : DataAccess
    {
        // Other methods
       

        // Static singleton instance

        static private EmployeesProvider _instance = null;
        static public EmployeesProvider Instance
        {
            get
            {
                if (_instance == null)
                    _instance = (EmployeesProvider)Activator.CreateInstance(Type.GetType(Globals.Settings.Employees.ProviderType));
                return _instance;
            }
        }
    }
}

I'd be interested in seeing an example of meta-programming in Python as nothing really seems to fit in C#. There's generics, delegates, reflection as above and meta-data in the form of attribute decoration as for the ProviderType property, but nothing that really does what I think you're suggesting.

Offline Mudface_

  • Boys Pen
  • *
  • Posts: 0
Re: RAWK Web Development Circle
« Reply #110 on: July 11, 2008, 10:30:11 am »
Don't listen to Mudface, he makes bleach for a living...

I've been exaggerating- I only test it. On fluffy creatures.

Offline iSmiff

  • TECHNOBORE
  • RAWK Supporter
  • Legacy Fan
  • ******
  • Posts: 18,131
Re: RAWK Web Development Circle
« Reply #111 on: July 11, 2008, 06:06:15 pm »
On their eyes hopefully.
STFU and agree with me.

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #112 on: July 11, 2008, 10:56:10 pm »
I'd be interested in seeing an example of meta-programming in Python as nothing really seems to fit in C#. There's generics, delegates, reflection as above and meta-data in the form of attribute decoration as for the ProviderType property, but nothing that really does what I think you're suggesting.
I must say, I barely understood that code at all. If you've got the time, do you think you could explain what's going on there? (I don't know the language at all, and that abstract class business confuses me.)

I wasn't suggesting anything in particular by metaprogramming: it seems to cover a huge range of things. I generally understand it as referring to programs altering themselves or writing other programs.

Something I do often in Python is to cache the results of long-running functions:
Code: [Select]
from urllib import quote_plus, urlopen

class memoize(object):

    def __init__(self, func):
        self.func = func
        self._cache = {}
   
    def __call__(self, *args):
        if not self._cache.has_key(args):
            self._cache[args] = self.func(*args)
        return self._cache[args]

@memoize
def google(query):
    url = "http://www.google.com/search?q=%s" % quote_plus(query)
    return urlopen(url).read()
   

if __name__ == "__main__":
    import time
    for x in range(10):
        start = time.time()
        google('some search')
        print "%d: %04f secs" % (x + 1, time.time() - start)


Output:
Code: [Select]
1: 1.399915 secs
2: 0.000024 secs
3: 0.000006 secs
4: 0.000006 secs
5: 0.000006 secs
6: 0.000006 secs
7: 0.000006 secs
8: 0.000005 secs
9: 0.000005 secs
10: 0.000006 secs

@memoize is a Python decorator that wraps the following function. So, whenever google() is called, in fact memoize(google).__call__() is called. If it hasn't seen the exact arguments already, it calls google() with the args and caches the result before returning it, otherwise it simply returns the cached result.

It's a contrived example, but nevertheless, the first call of google('some search') takes about 1.7 seconds on my machine and subsequent calls of the same take 0.000006 seconds or less.

I don't consider that particularly 'meta' as it's not really dynamic, just a time-saver. The most complex stuff I like to touch would be something like this:
Code: [Select]
import new

class Data:
   
    def __init__(self):
        self.attr1 = "foo"
        self.attr2 = "bar"

def dumpxml(self):
    s = "<item>\n"
    for k, v in self.__dict__.items():
        if k == 'dumps': continue
        s += "\t<attribute name='%s' value='%s' />\n" % (k, v)
    s += "</item>"
    return s

def dumpjson(self):
    d = self.__dict__.copy()
    del(d['dumps'])
    return repr(d)
   
class CockstashException(Exception):
    pass

class DataProvider(object):
   
    def __init__(self, format="xml"):
        self.format = format
   
    def get(self):
        d = Data()
        if self.format == 'xml':
            func = new.instancemethod(dumpxml, d, d.__class__)
            d.dumps = func
        elif self.format == 'json':
            func = new.instancemethod(dumpjson, d, d.__class__)
            d.dumps = func
        else:
            raise CockstashException('Invalid format, cockstash.')
        return d


if __name__ == '__main__':
    xmlprovider = DataProvider('xml')
    jsonprovider = DataProvider('json')
    bollixprovider = DataProvider('MS Word')
    xml = xmlprovider.get()
    print xml.dumps()
    json = jsonprovider.get()
    print json.dumps()
    bollix = bollixprovider.get() # throws an exception


Output:
Code: [Select]
<item>
        <attribute name='attr2' value='bar' />
        <attribute name='attr1' value='foo' />
</item>
{'attr2': 'bar', 'attr1': 'foo'}
Traceback (most recent call last):
  File "meta.py", line 51, in <module>
    bollix = bollixprovider.get() # throws an exception
  File "meta.py", line 39, in get
    raise CockstashException('Invalid format, cockstash.')
__main__.CockstashException: Invalid format, cockstash.

This code adds the instance method dumps to dump the object's attributes to a format specified at runtime. As far as I know, that would be nigh-on impossible in a statically-compiled language as self in the dumpxml and dumpjson functions-cum-methods is not bound until runtime. (I may be completely wrong here.)

Before anyone jumps down my throat, I know it's hackish, and I know that repr() doesn't return valid JSON data, but rather Python source code for the object (at least in the case of Python primitives), however, in the context of this example, it's also valid JSON data.

I try to avoid anything more complex than that, as it invariably confuses the fuck out of me the next time I read my own code.

BTW: You can run either of the examples by copying the code to a text file and running it with Python.
« Last Edit: July 11, 2008, 10:59:32 pm by wacko »
Quidquid latine dictum sit, altum sonatur.

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #113 on: July 11, 2008, 11:03:21 pm »
PHP isn't perfect. But love isn't about loving something that's perfect. It's about learning to love something that isn't perfect ;).

The OO of PHP is actually quite good, especially the overloading features. Generally though not having datatypes is shit. And not being able to use strings and numbers as objects is shit too.
That's what really bugs me about it. I find PHP's OO useful only for organising code. It doesn't do any of the clever stuff that duck-typed languages with OO primitives can do, like, say, passing custom objects with a read method to functions expecting a file handle.
Quidquid latine dictum sit, altum sonatur.

Offline Deano06

  • Confirmed BOFH TECHNOBORE#1
  • Anny Roader
  • ****
  • Posts: 425
  • Smarter than you.
  • Super Title: Or is he?
Re: RAWK Web Development Circle
« Reply #114 on: July 12, 2008, 09:59:23 am »
Only for what organising code? I don't think that's right at all.

What about making on the fly activerecord instances using __autoload()? for example.

And you can pass objects into classes and type-hint them, if you type hint a base class with an inherited standard method that you want to invoke, you cant type cast their results but you should know what they're going to be anyway. I've never actually needed duck-typing it's just for code security really. Making sure people don't pass irrelevant objects into methods. Also duck typing doesn't account for methods having the same name but producing different results.

Duck typing is a feature not a necessity at all. It won't make your job more difficult in any way. C++, PHP, Java (to and extent) all don't support true duck typing and they're all big languages and I wouldnt put any of them down for not supporting it. Nearly every Program you use was written without duck typing.

PHP's OO feature set is  strong and probably one of the best implementations around it's just the legacy side of PHP that's shit.

edit: sorry if that sounds like I'm being a dick I just don't think it's important.
« Last Edit: July 12, 2008, 10:01:34 am by Deano06 »

Offline Andy @ Allerton!

  • Missing an asterisk - no, wait sorry, that's his rusty starfish..... RAWK Apple fanboy. Hedley Lamarr's bestest mate. Has done nothing incredible ever.
  • RAWK Supporter
  • Legacy Fan
  • ******
  • Posts: 73,206
  • Asterisks baby!
Re: RAWK Web Development Circle
« Reply #115 on: July 12, 2008, 10:02:54 am »
I get what you mean, but if you just tag something properly and comment where you should you could get the same effect surely?

And if you need a human-readable way to exchange data then why not make a front end then the not so advanced users won't be overwhelmed by code.

It seemed a bit outdated to me when I learnt it.  But then again my teacher wasn't great and we never really got to see any examples of why it was practically a good thing, or why it was better than other technologies.


XML is great - wish we'd had it when we were developing mainframe systems 25 years ago.

You can send complex data structures and amend and change them easily and quickly - because as it is all tagged data - it's easy to construct and deconstruct.

Genius idea - so flexible, reliable and secure.
I love you all. Even Mancs x

Offline Mudface_

  • Boys Pen
  • *
  • Posts: 0
Re: RAWK Web Development Circle
« Reply #116 on: July 12, 2008, 07:49:14 pm »
I must say, I barely understood that code at all. If you've got the time, do you think you could explain what's going on there? (I don't know the language at all, and that abstract class business confuses me.)

Sorry about that, it is rather cryptic now I look at it again.

An abstract class is a base/ parent class which can't be instantiated, only inherited. All child classes inheriting from it must implement any abstract methods which it defines- it only defines the signature of these, without any other detail. It's similar to an interface, but can also contain overridable (virtual in C#) concrete methods which the child class can use. I had a very quick look to see what the equivalent would be in Python, and found this. In VB.NET, an abstract class is termed MustInherit and its abstract properties and procedures MustOverride, which seems to describe it better.

In the case above, an abstract provider class is defined containing all the CRUD methods required for each particular aspect of the database (employees, projects etc etc). I can then define a class which inherits from it which has concrete implementations of its methods and is targeted towards a particular data store. We use SQL Server at the moment, so the inherited class would have specific methods for SQL Server. If the data store were to change, for example to Oracle, which we use for SAP, then I could just rewrite the inherited class to specifically target Oracle, drop it in in place of the SQL Server provider and I wouldn't have to touch any of my other code layers.

All this rather tortuous piece of code does, is generate an instance of the inherited class based on what provider has been specified in my configuration module- i.e. ChangeControl.DAL.SQLClient.SQLEmployeesProvider. If I was using Oracle, then I'd change the DefaultValue of the ConfigurationProperty to ChangeControl.DAL.OracleClient.OracleEmployeesProvider (or whatever namespace and class combination I'd used) and it would activate that instead.

Code: [Select]
public class EmployeeDetailsElement : ConfigurationElement
    {
 // other methods here

        [ConfigurationProperty("providerType", DefaultValue = "ChangeControl.DAL.SQLClient.SQLEmployeesProvider")]
        public string ProviderType
        {
            get { return (string)base["providerType"]; }
            set { base["providerType"] = value; }
        }
    }

 public abstract class EmployeesProvider : DataAccess
    {
        // Other methods
       

        // Static singleton instance

        static private EmployeesProvider _instance = null;
        static public EmployeesProvider Instance
        {
            get
            {
                if (_instance == null)
                    _instance = (EmployeesProvider)Activator.CreateInstance(Type.GetType(Globals.Settings.Employees.ProviderType));
                return _instance;
            }
        }
    }
}

I find a problem with OOP is that you do need the full picture for even moderately complex projects, so I can post up a fuller code listing if you like when I get back to work. I took the overall idea for this from Marco Bellisano's book and starter kit website, which I linked to above in a reply to Slick_Beef, and I've found it works extremely well. You do have to write a fair amount of code, but I enjoy doing that anyway.

Thanks for the meta-programming examples you posted- that's pretty neat. The first one looks sort of similar to a delegate function, and I've used a vaguely similar method to the second one before to get description attributes from an enumeration. I wanted to use values from the enumeration in a dropdown list, but obviously you can only have the one word as the enumeration's value. By decorating it with a description attribute, then picking that up you can have a proper description in the list, rather than having entries like SAPChangeRequested and PDGAssessmentRequired  displayed-

Code: [Select]
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Reflection;
using System.Text;

/// <summary>
/// Various static Helper methods
/// </summary>

namespace ChangeControl
{
    [DataObject(true)]
    public static class Helpers
    {
        public enum ProjectStatus
        {
            [Description("Cancelled")]
            Cancelled = 0,
            [Description("Initiated")]
            Initiated = 1,
            [Description("SAP Change Requested")]
            SAPChangeRequested = 5,
            [Description("SAP Change Completed")]
            SAPChangeCompleted = 10,
            [Description("PDG Assessment Required")]
            PDGAssessmentRequired = 20,
            [Description("Approved")]
            Approved = 30,
            [Description("Requires Approval From SHEQA Manager")]
            F4Required = 35,
            [Description("Requires Approval From SHEQA Manager")]
            F5Required = 40,
            [Description("Ready For Close-Out")]
            ReadyForCloseOut = 45,
            [Description("Closed Out")]
            ClosedOut = 50,
            [Description("Abandoned Pre-Approval")]
            Abandoned = 66
        }
     
        private static string GetDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }

        public static string GetProjectStatusDescription(ProjectStatus value)
        {
            return GetDescription(value);
        }

        public static string GetProjectStatusDescription(int value)
        {
            return GetDescription((ProjectStatus)value);
        }

        [DataObjectMethod(DataObjectMethodType.Select)]
        public static SortedList GetProjectStatusesForDropdown()
        {
            SortedList projectStatuses = new SortedList();
            projectStatuses.Add(-1, "(Select)");
            foreach (ProjectStatus status in Enum.GetValues(typeof(ProjectStatus)))
            {
                projectStatuses.Add((int)status, GetProjectStatusDescription(status));
            }
            return projectStatuses;
        }
    }
}

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #117 on: July 13, 2008, 09:19:35 am »
Only for what organising code? I don't think that's right at all.

What about making on the fly activerecord instances using __autoload()? for example.
It's not all it's good for, it's just all I ever really used it for. I haven't even looked at PHP5, though, so my comments aren't relevant to the latest and greatest. I might have a look when my webhost installs v.5, but until then, it's irrelevant to me.

That __autoload() business was in v.4, too, wasn't it? I recall having done something similar many years ago, but the details are long gone from memory.
And you can pass objects into classes and type-hint them, if you type hint a base class with an inherited standard method that you want to invoke, you cant type cast their results but you should know what they're going to be anyway. I've never actually needed duck-typing it's just for code security really. Making sure people don't pass irrelevant objects into methods.
If anything, duck typing is a security risk. I think you meant the opposite. If people want to pass the wrong objects into methods, that's their problem: they should read the docs better. If you're passing other people's objects into your code without validating them anyway, you're asking for trouble.

It's trivially easy to ensure that an object is of a specific type if you need to:
Code: [Select]
assert isinstance(myObject, DesiredClass)
which is much shorter than the hoops C++ or Java make you jump through.

There are still plenty of other ways to shoot yourself in the foot.
Also duck typing doesn't account for methods having the same name but producing different results.
What does that mean? Are you talking about method overloading or methods in different classes?
Duck typing is a feature not a necessity at all. It won't make your job more difficult in any way. C++, PHP, Java (to and extent) all don't support true duck typing and they're all big languages and I wouldnt put any of them down for not supporting it. Nearly every Program you use was written without duck typing.

PHP's OO feature set is  strong and probably one of the best implementations around it's just the legacy side of PHP that's shit.

edit: sorry if that sounds like I'm being a dick I just don't think it's important.
Of course duck-typing isn't essential--a huge number of very experienced devs think it's the devil's own work--but it is a huge productivity boon (if a drag on performance). Python and Ruby programs are typically about 10% the size of Java, C or C++ programs. A lot of that is down to duck typing.

C++ and Java don't support duck typing, as far as I know. You can get around it with inheritance and interfaces, but that means more work. You have to be more aware of the code you're working with with duck typing, sure, but that's a price I'm willing to pay to save myself writing 10x the code, much of it mindless boilerplate.

In fact, the majority of the programs I use were written with duck typing, because I use a Mac and most of the programs are written in Objective-C.
Quidquid latine dictum sit, altum sonatur.

Offline wacko

  • Keepsh a shecret gottle of Shcotch in hish top drawer. Cunning linguist and ical genius
  • Legacy Fan
  • ******
  • Posts: 5,205
Re: RAWK Web Development Circle
« Reply #118 on: July 13, 2008, 09:23:48 am »
Sorry about that, it is rather cryptic now I look at it again.

An abstract class is a base/ parent class which can't be instantiated, only inherited. All child classes inheriting from it must implement any abstract methods which it defines- it only defines the signature of these, without any other detail. It's similar to an interface, but can also contain overridable (virtual in C#) concrete methods which the child class can use. I had a very quick look to see what the equivalent would be in Python, and found this. In VB.NET, an abstract class is termed MustInherit and its abstract properties and procedures MustOverride, which seems to describe it better.

In the case above, an abstract provider class is defined containing all the CRUD methods required for each particular aspect of the database (employees, projects etc etc). I can then define a class which inherits from it which has concrete implementations of its methods and is targeted towards a particular data store. We use SQL Server at the moment, so the inherited class would have specific methods for SQL Server. If the data store were to change, for example to Oracle, which we use for SAP, then I could just rewrite the inherited class to specifically target Oracle, drop it in in place of the SQL Server provider and I wouldn't have to touch any of my other code layers.

All this rather tortuous piece of code does, is generate an instance of the inherited class based on what provider has been specified in my configuration module- i.e. ChangeControl.DAL.SQLClient.SQLEmployeesProvider. If I was using Oracle, then I'd change the DefaultValue of the ConfigurationProperty to ChangeControl.DAL.OracleClient.OracleEmployeesProvider (or whatever namespace and class combination I'd used) and it would activate that instead.
Thanks, Mudface. Now I get it. Do you need the abstract class/interface like in Objective-C? What purpose does it serve? Is that where you implement methods common to all subclasses? Or is it just a way of guaranteeing you don't forget to implement a method in subclasses?
Quidquid latine dictum sit, altum sonatur.

Offline Deano06

  • Confirmed BOFH TECHNOBORE#1
  • Anny Roader
  • ****
  • Posts: 425
  • Smarter than you.
  • Super Title: Or is he?
Re: RAWK Web Development Circle
« Reply #119 on: July 13, 2008, 10:03:54 am »

In fact, the majority of the programs I use were written with duck typing, because I use a Mac and most of the programs are written in Objective-C.

Touché!

I definitely think you should try PHP5 out. It's a revelation. I'll send you my activerecord class i've written at some point if you're interested.