Coding: Fleeting Thoughts

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Prelates, Moderators General

Re: Coding: Fleeting Thoughts

Postby b.i.o » Sun Feb 19, 2012 2:03 pm UTC

Steax wrote:Whoever invented exceptions is now thrashing uncontrollably in his/her grave.

Honestly I have no real problems with code like this when the 'exceptional' case isn't actually somewhere where you want an exception that's going to propagate up the call stack. While rather strange for PHP, it looks pretty similar to an option type like you'd find in Haskell or OCaml:

Code: Select all
type 'a option = Some of 'a | None


You don't get most of the benefits in PHP, but you *do* get one: it's much harder to forget to write code that correctly works in the 'bad' case when you're writing code that works in the 'good' case, because even for the 'good' case you're getting back some unexpected data structure you need to handle specially.

Of course, my argument is somewhat nullified by the fact that your coworker apparently did not write anything to deal with the case of not finding an email. And I'd bet your coworkers had none of the above in mind when writing that code. But still! I kind of like it. :)
User avatar
b.i.o
Green is the loneliest number
 
Posts: 2520
Joined: Fri Jul 27, 2007 4:38 pm UTC
Location: Hong Kong

Re: Coding: Fleeting Thoughts

Postby Steax » Sun Feb 19, 2012 3:11 pm UTC

But you could also just do...

Code: Select all
function get_user_email($id){
    
$q query("SELECT `email` from `users` where `id`='".mysql_real_escape_string($id)."'");
    if(
mysql_num_rows($q) == 0){
        throw new 
EmptyResultException();
    }else{
        return 
mysql_result($q0'email');
    }
}

function 
display_user_email($id){
    try {
        
$email get_user_email($id);
        echo 
"<div>" $email "</div>"
    
}catch(EmptyResultException $e){}
}
 


Which would do the same thing, while allowing for greater flexibility. The issue I have with these 'response codes' is it becoming ridiculously annoying to compensate for a growing list of codes, and in the long run it tends to turn into... basically a pseudo-exception system. Argh.

In other news... Bootstrap's latest version is kickass. Makes prototyping stuff really quickly, too.

And unlike everything I hate about most of these frameworks, they don't force you to use their model!

Spoiler:
Image
In Minecraft, I use the username Rirez.
User avatar
Steax
SecondTalon's Goon Squad
 
Posts: 3037
Joined: Sat Jan 12, 2008 12:18 pm UTC

Re: Coding: Fleeting Thoughts

Postby elminster » Sun Feb 19, 2012 9:02 pm UTC

When you've worked on a project for two years and the code is still shit overall... you realise how important making code maintainable is.
Adding another floor on a tower built with cardboard foundations requires going through every level strengthening things just to support a tiny amount more.
Image
elminster
 
Posts: 1506
Joined: Mon Feb 26, 2007 1:56 pm UTC
Location: London, UK, Dimensions 1 to 42.

Re: Coding: Fleeting Thoughts

Postby Webzter » Mon Feb 20, 2012 12:23 am UTC

Steax wrote:The issue I have with these 'response codes' is it becoming ridiculously annoying to compensate for a growing list of codes, and in the long run it tends to turn into... basically a pseudo-exception system.


There are other alternatives. One could return a simple true/false. Or, return a sensible default (perhaps a null or empty string). It really depends on how exceptional the lack of data is and what the expected path should be. I agree wholeheartedly with your hatred of return codes though.
Webzter
 
Posts: 179
Joined: Tue Dec 04, 2007 4:16 pm UTC
Location: Michigan, USA

Re: Coding: Fleeting Thoughts

Postby jareds » Mon Feb 20, 2012 1:09 am UTC

EvanED wrote:Oh, EDG already being able to somewhat emulate MSVC didn't occur to me. Do you know how close it gets? E.g. does it at least mostly get their template lookup right? Or is it just some stuff more on the parser side?

Their MS and GNU modes definitely fall into the "crazy good" (but not perfect) category.1 The docs have an enormous list of deviations, many of which would affect name resolution in one way or another. As for lookup in template instantiation specifically, they definitely allow non-dependent names to be resolved at the point of instantiation. Actually, the non-standard instantiation lookup is separately controllable from MS compatibility, so if you want you can try it on Comeau's thing by passing --no_dep_name. (However, note that Comeau's thing apparently was not built to allow the MS compatibility options I mentioned.) Unfortunately, they have nothing like your "assist" mode--I know Clang is pretty good in that way.

1The craziest thing with the compatibility options at first glance, although it is ultimately just thoroughness rather than conceptual difficulty, is numeric --gnu_version and --microsoft_version options. We (my employer will remain nameless) don't even expose the numeric options to our own customers because testing them fully wouldn't be worth it (and we don't expose things we don't test ourselves).
jareds
 
Posts: 407
Joined: Wed Jan 03, 2007 3:56 pm UTC

Re: Coding: Fleeting Thoughts

Postby b.i.o » Mon Feb 20, 2012 1:27 am UTC

Steax wrote:But you could also just do...
[...]
Which would do the same thing, while allowing for greater flexibility.

No, it wouldn't. My point is that having some wrapper returned is an indication that there's an exceptional value and that you need to deal with it, because you can't deal with the returned value unless you deal with there being a possible exceptional value. You can completely ignore the existence of an exception if you don't know it's there.

I'm not saying the overall implementation is actually a good idea in your case, especially if there are lots of different possible result codes (which seems wrong to me), just that the implementation has bits and pieces of an actually good idea, even if that's by accident.
User avatar
b.i.o
Green is the loneliest number
 
Posts: 2520
Joined: Fri Jul 27, 2007 4:38 pm UTC
Location: Hong Kong

Re: Coding: Fleeting Thoughts

Postby Steax » Mon Feb 20, 2012 3:00 am UTC

Webzter wrote:There are other alternatives. One could return a simple true/false. Or, return a sensible default (perhaps a null or empty string). It really depends on how exceptional the lack of data is and what the expected path should be. I agree wholeheartedly with your hatred of return codes though.


They used true/falses before, but then their minds exploded when they had functions that could fail in more ways than one.

b.i.o wrote:No, it wouldn't. My point is that having some wrapper returned is an indication that there's an exceptional value and that you need to deal with it, because you can't deal with the returned value unless you deal with there being a possible exceptional value. You can completely ignore the existence of an exception if you don't know it's there.

I'm not saying the overall implementation is actually a good idea in your case, especially if there are lots of different possible result codes (which seems wrong to me), just that the implementation has bits and pieces of an actually good idea, even if that's by accident.


Oh, that makes sense. But yeah, it's quite common for there to be many result codes, especially in complex things like submitting data.
In Minecraft, I use the username Rirez.
User avatar
Steax
SecondTalon's Goon Squad
 
Posts: 3037
Joined: Sat Jan 12, 2008 12:18 pm UTC

Re: Coding: Fleeting Thoughts

Postby TheChewanater » Mon Feb 20, 2012 3:09 am UTC

Steax wrote:
Webzter wrote:There are other alternatives. One could return a simple true/false. Or, return a sensible default (perhaps a null or empty string). It really depends on how exceptional the lack of data is and what the expected path should be. I agree wholeheartedly with your hatred of return codes though.


They used true/falses before, but then their minds exploded when they had functions that could fail in more ways than one.

It's preferable to OpenGL style, where you can get the general type of error, but you have absolutely no idea what generated the error.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.
User avatar
TheChewanater
 
Posts: 1286
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Fleeting Thoughts

Postby Webzter » Mon Feb 20, 2012 3:23 am UTC

Steax wrote:They used true/falses before, but then their minds exploded when they had functions that could fail in more ways than one.


Nice :)

This has me thinking though....

If the function is in direct response to user input, then I like to use something like (C# code):
Spoiler:
Code: Select all
    public class PasswordValidationResult
    {
        private IList<string> _reasonsInvalid = new List<string>();

        public bool IsValid
        {
            get { return _reasonsInvalid.Count == 0; }
        }

        public IEnumerable<string> ReasonsInvalid
        {
            get { return _reasonsInvalid; }
        }
    }

    public class PasswordValidator : IPasswordValidator
    {
        public PasswordValidationResult ValidatePassword(User user, string newPassword)        { .. }
    }


However, if it's in data processing somewhere in the backend, then I prefer to return a sensible default (perhaps an empty string in the case of getting someone's email address in order to send them, say, an order confirmation) and then act accordingly based on the data. I tend to save exception throwing for exceptional cases... say a user with a missing email address if my users are always supposed to have addresses. So, more or less in cases where there was a breakdown in the business or technical processes that result in an invalid state... which would be highly dependent on one's domain.

(sorry to waste so much e-space on a fleeting thought, just it really got me thinking)

My favorite method to kill of all time was, in a C# system where everything ran local to each other, was something along the lines of:
Spoiler:
Code: Select all
 public void SetObject(string valueName, object objectValue)
 {
   switch (valueName)
   {
     case "FNAME":
     case "FIRSTNAME":
     _firstName=objectValue;
  ........ repeat the above for 100 values
   }
 }

Along with some other wonderful tricks... they made any sensible attempt at refactoring in a strongly typed language like C# all but impossible because you could never follow the call chain. The original author was proud of having used every pattern from the Gang of Four. Killing off his work is still my proudest accomplishment... took a 100k line pile with no tests and turned it into 17k lines which included a robust set of automated unit tests. And it ended up saving us an incredible amount of time every month in both QA and development time.
Webzter
 
Posts: 179
Joined: Tue Dec 04, 2007 4:16 pm UTC
Location: Michigan, USA

Re: Coding: Fleeting Thoughts

Postby Yakk » Tue Feb 21, 2012 3:55 pm UTC

Steax wrote:Which would do the same thing, while allowing for greater flexibility. The issue I have with these 'response codes' is it becoming ridiculously annoying to compensate for a growing list of codes, and in the long run it tends to turn into... basically a pseudo-exception system. Argh.

So, it depends. Do you want an error you didn't handle to result in your entire program going away as the exception propagates up the stack?

That is what exceptions require that you do -- every exception, unless you "catch all", threatens to be a nearly arbitrary distance "goto". Which means that you either push for a coding standard that doesn't let you throw exceptions willy-nilly, or you have to do a "catch all" whenever you call any code that you didn't personally write then physically prevent anyone else from every modifying if you want to avoid those nearly arbitrary distance "gotos".

Flow control is far too important a task to be left to chance. So even if you end up reimplementing an exception system, at least the flow control won't be as brain-dead broken as exception based flow control is, because you almost certainly don't have access to that level of brain-dead power (short of building a setjmp/longjmp based pseudo-exception system) within your language outside of exceptions.

The ideal situation I'd want is a compile-time enforced "you must handle the set of answers that this function can return". But that is rare outside of some relatively esoteric languages (like Haskell). I could hack something like it together in C++, but it would be a hack (the return type is a functor that takes multiple functors to handle the possible return types, each of which must be implemented, and type-safely takes as input the possible type. They'd all have to have a common return type (enforced via a template mechanism) which the functor would then return.

But, as noted, that is a hack.

( Ignoring letting the end-user make their own return type:
Code: Select all
struct not_found {};
struct other_error {};

function< void( function< void(int) >, function< void(not_found) >, function< void(other_error)> ) > doWork();

// use:
doWork()(
  [&]( int result )->void
  {
    printf("result is: %d\n", result);
  },
  [&]( not_found& )->void
  {
    printf("not found!\n");
  },
  [&]( other_error& )->void
  {
    printf("Some other error!\n");
  }
);
// Note: failure to handle each return case results in the code not compiling.

// Error codes themselves could be bundled similarly, so you have one error case that takes as an argument the error-handling functor, which you then call if you want to figure out what error it was... allowing you to pass the error up the stack to handle somewhere else.

As mentioned, this is pretty hacky. But it does ensure that if you get any result from a function, you also handle any error cases (or explicitly do not handle them). And it keeps flow control under control.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
Poster with most posts but no title.
 
Posts: 10399
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby korona » Wed Feb 22, 2012 1:32 am UTC

Yakk wrote:The ideal situation I'd want is a compile-time enforced "you must handle the set of answers that this function can return". But that is rare outside of some relatively esoteric languages (like Haskell).

I guess that is the idea behind Java's checked exceptions and I don't think that this design decision was that great.
What is so bad about C++ exceptions (when used properly)? Of course you cannot solve every problem with them and there are some gotchas but in many situations they are a good choice for handling unexpected errors (e.g. out of memory, ...). Of course there are better ways to handle multiple return values.
korona
 
Posts: 338
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby EvanED » Wed Feb 22, 2012 5:58 pm UTC

On Linux, my <assert.h> has the following:

Code: Select all
/* The following is not at all used here but needed for standard
   compliance.  */
extern void __assert (const char *__assertion, const char *__file, int __line)
     __THROW __attribute__ ((__noreturn__));


Anyone know what it's talking about? I can't find __assert in either C99 or POSIX.
EvanED
 
Posts: 4130
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI

Re: Coding: Fleeting Thoughts

Postby cemper93 » Wed Feb 22, 2012 7:19 pm UTC

So, in school, we're learning this Java thing.

Our homework is to write a program to solve the eight queens puzzle. Now me, a fan of over-engineering with OO, want to write my program modular enough that it could solve any other eight * puzzle (knight, rook, whatever) without having to modify it heavily. The classes I have right now are Chessboard (a wrapper around Vector, it's sole purpose being to check whether a specific token can be captured by iterating over all the others and calling their canCapture-methods), Token (abstract class, wants method canCapture(pos) implemented), and Queen (implements Token). Of course, what is still missing is the EightSomethingSolver class. Since the various types of Tokens that may be implemented only vary by the fields they can capture, it doesn't seem to make any sense to rewrite EightSomethingSolver for every type of token. In fact, I'd strongly prefer it to have no knowledge of the Tokens it is dealing with at all; it just has to instantiate them to place them on the field, then call their canCapture-methods to check whether they endanger each other or not.

So, my question is: How can I achieve this in Java? I don't seem to be able to treat classes like objects and just pass them around, so there has to be a different way. I thought about using generics, like this (heavily stripped):
Code: Select all
ifNotSolvedYet(board) {
    board.addToken(new TokenType(pos));
}

but apparently, Java is evil and doesn't allow me to instantiate TokenType (which makes enough sense to me: Java does of course have no way of knowing that I will use only Token-subtypes as parameters to my generic class.

So, my question and tl;dr: How can I write a class that is able to create instances of another class without having it know the other class is?

EDIT: I just didn't create a new thread because my question feels utterly noobish. I wish to apologize for any inconvenience this may cause.
Hello good friend.<br>Thank you for the kind insight. To gain free XBOX, please click this link <a href="http://forums.xkcd.com/viewtopic.php?f=53&t=37971">for m&ouml;re information visit our website.</a><br>Also more can be found.<br>Best regard
User avatar
cemper93
 
Posts: 183
Joined: Sun Feb 20, 2011 2:35 pm UTC
Location: `pwd`

Re: Coding: Fleeting Thoughts

Postby Yakk » Wed Feb 22, 2012 7:30 pm UTC

korona wrote:
Yakk wrote:The ideal situation I'd want is a compile-time enforced "you must handle the set of answers that this function can return". But that is rare outside of some relatively esoteric languages (like Haskell).
I guess that is the idea behind Java's checked exceptions and I don't think that this design decision was that great.
How so?
What is so bad about C++ exceptions (when used properly)?

Because on any reasonably large code base, I can't think of a way they can be used properly, barring a really really huge amount of code discipline and static checking utilities aimed at making sure things aren't going wrong.

As written in C++, each throw() is an arbitrary depth goto into your calling stack. Each call to a function without a catch(...) is also an arbitrary depth goto into your own stack. There is no way you can locally determine the flow of execution without wrapping each external bit of code in a try{}catch(){} block.

You can fix this by rigid code standards that basically come down to "do not use exceptions", or "only use exceptions in functions that are not exported outside of your translation unit, and decorate the name of such exception throwing functions, only throwing one kind of exception", etc.
Of course you cannot solve every problem with them and there are some gotchas but in many situations they are a good choice for handling unexpected errors (e.g. out of memory, ...).
Out of memory is an interesting problem.

Most C++ code bases of any reasonable size do not deal with running out of memory well. Regardless of the exception being thrown or not. The best they can usually do is go into emergency shutdown mode, often.

Some small code bases can isolate their memory allocation to a handful of areas. And handle running out of memory in those areas. Note, however, that a nullptr return from a new call would be about as useful.
Of course there are better ways to handle multiple return values.

I'm talking both about multiple return values and multiple return paths. Exceptions produce both, but there is a serious lack of the ability to in-language describe the return paths that a given function can generate.

Being able to understand what code does by reading it is an important feature of a language, and exceptions mean that there are code execution paths that are not at all clear when reading things locally. You could take it as a given that every function call will throw an exception, and do unit testing based on this assumption, and see if things work...

But I've yet to see a large C++ code base that does that.

To be clear, I'm not all that keen with the verbosity of Java exceptions. I'd want meta-decoration coding in which the "brutal exceptions" are implicitly added to a function by the "standard" function decoration modifier.

Ie, suppose that you "by default" decorated every function with the modifier "function". That modifier implies that you can throw division by zero, memory shortage, segmentation fault, and a myriad of other critical exceptions. The programmer could write their own standard modifier that presumes a different set of possible exceptions.

Even better, when calling an incompatible function, your modifier might describe what happens. Maybe you have an unhandled exception exception and your decorator says that you implicitly wrap all calls to more broadly throwing functions in a try-catch block that rewraps their exception into an unhandled exception, then rethrows the unhandled exception. Such decoration could be on the level of a function, or on a block, which lets you write code that doesn't care about exceptions, or more careful code that does.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
Poster with most posts but no title.
 
Posts: 10399
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Pepve » Wed Feb 22, 2012 8:21 pm UTC

Yakk wrote:
korona wrote:
Yakk wrote:The ideal situation I'd want is a compile-time enforced "you must handle the set of answers that this function can return". But that is rare outside of some relatively esoteric languages (like Haskell).
I guess that is the idea behind Java's checked exceptions and I don't think that this design decision was that great.
How so?
What is so bad about C++ exceptions (when used properly)?

Because on any reasonably large code base, I can't think of a way they can be used properly, barring a really really huge amount of code discipline and static checking utilities aimed at making sure things aren't going wrong.

As written in C++, each throw() is an arbitrary depth goto into your calling stack. Each call to a function without a catch(...) is also an arbitrary depth goto into your own stack. There is no way you can locally determine the flow of execution without wrapping each external bit of code in a try{}catch(){} block.

You can fix this by rigid code standards that basically come down to "do not use exceptions", or "only use exceptions in functions that are not exported outside of your translation unit, and decorate the name of such exception throwing functions, only throwing one kind of exception", etc.
Of course you cannot solve every problem with them and there are some gotchas but in many situations they are a good choice for handling unexpected errors (e.g. out of memory, ...).
Out of memory is an interesting problem.

Most C++ code bases of any reasonable size do not deal with running out of memory well. Regardless of the exception being thrown or not. The best they can usually do is go into emergency shutdown mode, often.

Some small code bases can isolate their memory allocation to a handful of areas. And handle running out of memory in those areas. Note, however, that a nullptr return from a new call would be about as useful.
Of course there are better ways to handle multiple return values.

I'm talking both about multiple return values and multiple return paths. Exceptions produce both, but there is a serious lack of the ability to in-language describe the return paths that a given function can generate.

Being able to understand what code does by reading it is an important feature of a language, and exceptions mean that there are code execution paths that are not at all clear when reading things locally. You could take it as a given that every function call will throw an exception, and do unit testing based on this assumption, and see if things work...

But I've yet to see a large C++ code base that does that.

To be clear, I'm not all that keen with the verbosity of Java exceptions. I'd want meta-decoration coding in which the "brutal exceptions" are implicitly added to a function by the "standard" function decoration modifier.

Ie, suppose that you "by default" decorated every function with the modifier "function". That modifier implies that you can throw division by zero, memory shortage, segmentation fault, and a myriad of other critical exceptions. The programmer could write their own standard modifier that presumes a different set of possible exceptions.

Even better, when calling an incompatible function, your modifier might describe what happens. Maybe you have an unhandled exception exception and your decorator says that you implicitly wrap all calls to more broadly throwing functions in a try-catch block that rewraps their exception into an unhandled exception, then rethrows the unhandled exception. Such decoration could be on the level of a function, or on a block, which lets you write code that doesn't care about exceptions, or more careful code that does.

Are you on crack?
Pepve
 
Posts: 57
Joined: Wed Jul 28, 2010 9:47 am UTC

Re: Coding: Fleeting Thoughts

Postby Xeio » Wed Feb 22, 2012 8:35 pm UTC

cemper93 wrote:So, my question and tl;dr: How can I write a class that is able to create instances of another class without having it know the other class is?
Short answer: You can't, you'll have to create a case for every possibility.

Long answer: You shouldn't, because it would be using something like reflection and there's no way you should be doing something like that.
User avatar
Xeio
Friends, Faidites, Countrymen
 
Posts: 4769
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\

Re: Coding: Fleeting Thoughts

Postby cemper93 » Wed Feb 22, 2012 8:53 pm UTC

Thanks.

In other news, I just started to hate Java.
Hello good friend.<br>Thank you for the kind insight. To gain free XBOX, please click this link <a href="http://forums.xkcd.com/viewtopic.php?f=53&t=37971">for m&ouml;re information visit our website.</a><br>Also more can be found.<br>Best regard
User avatar
cemper93
 
Posts: 183
Joined: Sun Feb 20, 2011 2:35 pm UTC
Location: `pwd`

Re: Coding: Fleeting Thoughts

Postby Xeio » Wed Feb 22, 2012 9:18 pm UTC

I'm pretty sure that problem wouldn't be specific to java. Generics can be very helpful but one thing they don't do is knowledge of all derived types.
User avatar
Xeio
Friends, Faidites, Countrymen
 
Posts: 4769
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\

Re: Coding: Fleeting Thoughts

Postby TNorthover » Wed Feb 22, 2012 9:20 pm UTC

cemper93 wrote:So, my question is: How can I achieve this in Java? I don't seem to be able to treat classes like objects and just pass them around, so there has to be a different way.

To me, the obvious solution is to pass around an instance of TokenType instead.

If you haven't discovered reflection yet, then at the point you decide which TokenType to use you must be capable of creating an instance anyway. The more bizarre solutions would only really be beneficial if you wanted the user to be able to supply a completely unknown .class file and do something sane with it (say in some application's plugin system).
User avatar
TNorthover
 
Posts: 191
Joined: Wed May 06, 2009 7:11 am UTC
Location: Cambridge, UK

Re: Coding: Fleeting Thoughts

Postby jaap » Wed Feb 22, 2012 9:21 pm UTC

cemper93 wrote:Thanks.

In other news, I just started to hate Java.

It just shows you that your design is wrong. Why should the EightSomethingSolver have "to instantiate them to place them on the field"? It need not be the responsibility of the EightSomethingSolver to create and destroy them - it only has to move them about. Therefore you could as an alternative just give EightSomethingSolver eight instances of the Token that it can then manipulate.
Come to think of it, why do you need eight Tokens anyway? You can give the EightSomethingSolver an instance of a class that represents the rule by which the pieces work. All it needs to do is provide a function that takes as input one board location and return a list of those locations that a piece at that location would cover (or a function that given two locations returns true if a piece on the first location would cover the square at the second location).
User avatar
jaap
 
Posts: 1815
Joined: Fri Jul 06, 2007 7:06 am UTC

Re: Coding: Fleeting Thoughts

Postby Yakk » Wed Feb 22, 2012 9:41 pm UTC

cemper93 wrote:So, my question and tl;dr: How can I write a class that is able to create instances of another class without having it know the other class is?

Easy. Create a TokenFactory interface that returns a reference to a (root, abstract/interface) class of the Tokens. Each TokenFactory actually creates one of the subtypes of Token.

As noted above, this isn't the only way to solve the problem. But you don't want to pass around a class, you want to pass around a factory for instances of a class, and that is far easier to do.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
Poster with most posts but no title.
 
Posts: 10399
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby cemper93 » Wed Feb 22, 2012 11:11 pm UTC

Yakk wrote:Easy. Create a TokenFactory interface that returns a reference to a (root, abstract/interface) class of the Tokens. Each TokenFactory actually creates one of the subtypes of Token.

As noted above, this isn't the only way to solve the problem. But you don't want to pass around a class, you want to pass around a factory for instances of a class, and that is far easier to do.

This solution is so obvious that my head hit my table when reading it. Thank you! Plus, the factory pattern means my solution is even more over-OOifed than before. I love Java :mrgreen:

jaap wrote:It need not be the responsibility of the EightSomethingSolver to create and destroy them - it only has to move them about.

I think the responsibility of a Solver class should be to turn an empty board into a solved one, so it should have the ability to create the Tokens. But yes, I admit I could have gone for a simpler solution by giving that responsibility to the caller.
Hello good friend.<br>Thank you for the kind insight. To gain free XBOX, please click this link <a href="http://forums.xkcd.com/viewtopic.php?f=53&t=37971">for m&ouml;re information visit our website.</a><br>Also more can be found.<br>Best regard
User avatar
cemper93
 
Posts: 183
Joined: Sun Feb 20, 2011 2:35 pm UTC
Location: `pwd`

Re: Coding: Fleeting Thoughts

Postby chridd » Wed Feb 22, 2012 11:53 pm UTC

cemper93 wrote:
jaap wrote:It need not be the responsibility of the EightSomethingSolver to create and destroy them - it only has to move them about.

I think the responsibility of a Solver class should be to turn an empty board into a solved one, so it should have the ability to create the Tokens. But yes, I admit I could have gone for a simpler solution by giving that responsibility to the caller.
But then what if one wanted to solve the problem for, say, four rooks and four bishops (or some other combination of pieces of different types)? Having the caller create the tokens would allow that, making it even more more-general-than-it-needs-to-be.
(unless you wanted it to find what the maximum number of pieces of a particular type that can fit on a board is, thus generalizing in a different direction)
~ chri d. d.
mittfh wrote:I wish this post was very quotable...
User avatar
chridd
 
Posts: 477
Joined: Tue Aug 19, 2008 10:07 am UTC
Location: ...Earth, I guess?

Re: Coding: Fleeting Thoughts

Postby cemper93 » Thu Feb 23, 2012 1:14 am UTC

chridd wrote:But then what if one wanted to solve the problem for, say, four rooks and four bishops (or some other combination of pieces of different types)? Having the caller create the tokens would allow that, making it even more more-general-than-it-needs-to-be.
(unless you wanted it to find what the maximum number of pieces of a particular type that can fit on a board is, thus generalizing in a different direction)

I guess I'll go for the "maximum number of pieces"-idea, because in class my teacher made a remark about the problem not having solutions for certain field sizes. On the other hand, four rooks and four bishops sounds pretty cool. But come to think about it, all I would need to implement both of these ideas would be a TokenFactoryFactory1 to be passed to the solver class, which can then use the different TokenFactories it gets to alternate between the types of pieces in an attempt to maximize the number of placed pieces. Awesome.

1: Actually, this would be more like a TokenFactoryList. But that doesn't sound as nice.
Hello good friend.<br>Thank you for the kind insight. To gain free XBOX, please click this link <a href="http://forums.xkcd.com/viewtopic.php?f=53&t=37971">for m&ouml;re information visit our website.</a><br>Also more can be found.<br>Best regard
User avatar
cemper93
 
Posts: 183
Joined: Sun Feb 20, 2011 2:35 pm UTC
Location: `pwd`

Re: Coding: Fleeting Thoughts

Postby Yakk » Thu Feb 23, 2012 2:24 am UTC

Token generator instead of factory factory. Like python generators. Or foreach adapter that is called once per element.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
Poster with most posts but no title.
 
Posts: 10399
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Sean Quixote » Thu Feb 23, 2012 3:30 am UTC

Anyone know any good tutorials to show me how to get started learning how to write Android apps? I also know it's written in Java - how much about Java does one need to really understand in order to make simple programs for your smartphone? Do I need to actually have a nice hang of all the OO madness or could I possibly get by using standard library stuff (and if so a point in the right direction would also be well appreciated)?
User avatar
Sean Quixote
 
Posts: 220
Joined: Tue Sep 14, 2010 1:20 am UTC
Location: Ubeki-beki-beki-beki-stan-stan

Re: Coding: Fleeting Thoughts

Postby TheChewanater » Sat Feb 25, 2012 12:28 am UTC

FT: Does anyone else sometimes get the feeling that 99.99% of your comments are completely useless?
Last edited by TheChewanater on Sat Feb 25, 2012 12:45 am UTC, edited 2 times in total.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.
User avatar
TheChewanater
 
Posts: 1286
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Fleeting Thoughts

Postby ahammel » Sat Feb 25, 2012 12:32 am UTC

TheChewanater wrote:FT: Does anyone else sometimes get the feeling that 99.99% of your comments are completely useless?


The best one I've seen is:

Code: Select all
int x; //x is an int

But to answer your question: yes.
I also answer to 'Alex'

YES, IT'S SPACEY-WACEY!
User avatar
ahammel
My Little Cabbage
 
Posts: 1475
Joined: Mon Jan 30, 2012 12:46 am UTC
Location: Vancouver BC

Re: Coding: Fleeting Thoughts

Postby cemper93 » Sat Feb 25, 2012 11:43 am UTC

Sean Quixote wrote:Anyone know any good tutorials to show me how to get started learning how to write Android apps? I also know it's written in Java - how much about Java does one need to really understand in order to make simple programs for your smartphone? Do I need to actually have a nice hang of all the OO madness or could I possibly get by using standard library stuff (and if so a point in the right direction would also be well appreciated)?

I found the official Android documentation very helpful.

The Android API is quote OO-heavy, but I guess if you're not totally new to programming you can pick it up as you go.
Hello good friend.<br>Thank you for the kind insight. To gain free XBOX, please click this link <a href="http://forums.xkcd.com/viewtopic.php?f=53&t=37971">for m&ouml;re information visit our website.</a><br>Also more can be found.<br>Best regard
User avatar
cemper93
 
Posts: 183
Joined: Sun Feb 20, 2011 2:35 pm UTC
Location: `pwd`

Re: Coding: Fleeting Thoughts

Postby gametaku » Sat Feb 25, 2012 7:18 pm UTC

cemper93 wrote:
Sean Quixote wrote:Anyone know any good tutorials to show me how to get started learning how to write Android apps? I also know it's written in Java - how much about Java does one need to really understand in order to make simple programs for your smartphone? Do I need to actually have a nice hang of all the OO madness or could I possibly get by using standard library stuff (and if so a point in the right direction would also be well appreciated)?

I found the official Android documentation very helpful.

The Android API is quote OO-heavy, but I guess if you're not totally new to programming you can pick it up as you go.


The hardest part, as long as you have some understanding of OO programming and java, is managing the lifecycles of different components such as activities and services.
gametaku
 
Posts: 149
Joined: Tue Dec 30, 2008 2:21 am UTC

Re: Coding: Fleeting Thoughts

Postby EvanED » Tue Feb 28, 2012 1:58 am UTC

In the span of about a week, I have independently found bugs in old versions (since fixed) of: the C++ standard, GNU libstdc++, and GCC.

I'm not sure if I'm doing something very wrong or very right...

(The bugs are: in C++98/03, the inability to compare a reverse_iterator to a const_reverse_iterator, defect report #280; in libstdc++, probably whatever the heck this is, though evidenced in a different form; and in GCC, some random internal compiler error that went away in later versions and so I spent exactly zero time looking into.)
EvanED
 
Posts: 4130
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI

Re: Coding: Fleeting Thoughts

Postby Thesh » Wed Feb 29, 2012 4:49 am UTC

So at my work, there is a job that connects with an external company to download the information, it was written by a guy who left long before I got there. Our job is written in VB.Net, the external company uses an ASP.net webservice. Now, he could have added a web reference and let .NET do all the grunt work, meaning his code would be 20 lines. Of course, that would have been the sane thing to do, and he didn't want to do sane. Instead, he wrote a hacky integration from the ground up in several hundred lines of code, half of it building XML strings.
Big are getting bigger and hearts are getting harder, an imaginary game
eating at every living thing, a voice dripping with sarcasm like a bloody fat slash
grinning over bleached white-fang teeth that glow like green warning signs of sickness.
User avatar
Thesh
Has the Brain Worms, In Case You Forgot.
 
Posts: 3623
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: California, Southern USA

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Wed Feb 29, 2012 8:01 pm UTC

The other day I jokingly suggested to my coworkers there should be a google translate for computer code.

Then the discussion got semi-serious. This would actually kinda work. You can compile the code into an intermediate byte code, and then decompile it back into the new language. If you create the intermediate language in such a way that it's layered in terms of abstraction, you can retain much of the code appearance when translating between closely related languages, and go into something close to machine code when translating between disparate languages (resulting in working, but incomprehensible code).
I now occasionally update my rarely-updated blog.

I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.
User avatar
You, sir, name?
 
Posts: 6524
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City

Re: Coding: Fleeting Thoughts

Postby Yakk » Wed Feb 29, 2012 8:11 pm UTC

A problem is that many languages have serious corner cases. Detecting if your code is "using" a corner case is tricky. If you don't do that, then you have to build your translator to duplicate all corner cases.

And when you duplicate all corner cases, you are quickly reduced to building a simulation of the language in your intermediate form. Detecting these simulations and remapping them back to what you have (corner cases and all) becomes tricky, even if you are going back to the exact same language you started with!

As an example, suppose your language provides some kind of object based hash map. If your language has a default interface for objects, you'll need to take your hash map and implement all of the default object junk that you probably don't use (or really care about) in your code. Detecting that nobody ever treats it "like an object" gets tricky the moment you toss it into a reference type structure -- or worse, suppose there is a garbage collector in your language, that keeps an object-typed reference to the object around!

To bypass this problem, you have to move from local syntactic translation to full-on semantic translation -- garbage collection goes from being how it is implemented, to what it means to be garbage collected (and woe betide you if there are quirks in how you can get a given object be collected!). And you can see how well computers do with semantic translation with google translate...
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
Poster with most posts but no title.
 
Posts: 10399
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby jaap » Wed Feb 29, 2012 8:12 pm UTC

You, sir, name? wrote:The other day I jokingly suggested to my coworkers there should be a google translate for computer code.

Then the discussion got semi-serious. This would actually kinda work. You can compile the code into an intermediate byte code, and then decompile it back into the new language. If you create the intermediate language in such a way that it's layered in terms of abstraction, you can retain much of the code appearance when translating between closely related languages, and go into something close to machine code when translating between disparate languages (resulting in working, but incomprehensible code).

For certain pairs of languages, converters have existed for years. Fortran to C (f2c) comes to mind.
User avatar
jaap
 
Posts: 1815
Joined: Fri Jul 06, 2007 7:06 am UTC

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Wed Feb 29, 2012 11:24 pm UTC

jaap wrote:
You, sir, name? wrote:The other day I jokingly suggested to my coworkers there should be a google translate for computer code.

Then the discussion got semi-serious. This would actually kinda work. You can compile the code into an intermediate byte code, and then decompile it back into the new language. If you create the intermediate language in such a way that it's layered in terms of abstraction, you can retain much of the code appearance when translating between closely related languages, and go into something close to machine code when translating between disparate languages (resulting in working, but incomprehensible code).

For certain pairs of languages, converters have existed for years. Fortran to C (f2c) comes to mind.


Well, Fortran is just a limited version of C with a different syntax, so that's not surprising.
I now occasionally update my rarely-updated blog.

I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.
User avatar
You, sir, name?
 
Posts: 6524
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City

Re: Coding: Fleeting Thoughts

Postby Jplus » Thu Mar 01, 2012 3:05 pm UTC

You, sir, name? wrote:Fortran is just a limited version of C with a different syntax

Really? I think C is already quite Spartanic.
Feel free to call me Julian. J+ is just an abbreviation.
Image coding and xkcd combined
User avatar
Jplus
 
Posts: 1554
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: classified

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Thu Mar 01, 2012 5:43 pm UTC

The set of things possible in C is larger than almost any other non-esoteric language (other than assembly), even if the set of things easy to do is smaller than almost any non-esoteric language (other than assembly).

When you include things that aren't per se defined but still is de facto possible in specific implementations, things get really silly.
I now occasionally update my rarely-updated blog.

I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.
User avatar
You, sir, name?
 
Posts: 6524
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City

Re: Coding: Fleeting Thoughts

Postby Dason » Fri Mar 02, 2012 4:35 am UTC

Just discovered this site: http://ideone.com/

From their site:
What is ideone?
Ideone is something more than a pastebin; it's an online compiler and debugging tool which allows
to compile and run code online in more than 40 programming languages.

It's an interesting idea and I found it while searching for an online R server. I've always wanted to mess around with Prolog...
double epsilon = -.0000001;
User avatar
Dason
 
Posts: 1293
Joined: Wed Dec 02, 2009 7:06 am UTC
Location: ~/

Re: Coding: Fleeting Thoughts

Postby Yakk » Fri Mar 02, 2012 7:08 pm UTC

Code: Select all
std::map< foo*, whatever, decltype( []( foo const* lhs, foo const* rhs) { return (!lhs||!rhs)?lhs<rhs:*lhs<*rhs; } ) > ohMyGodWhatDidIJustDo;

That is all.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
Poster with most posts but no title.
 
Posts: 10399
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

PreviousNext

Return to Coding

Who is online

Users browsing this forum: No registered users and 8 guests