Coding: Fleeting Thoughts

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

Moderators: phlip, Moderators General, Prelates

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7368
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Sat Sep 06, 2014 7:47 pm UTC

You, sir, name? wrote:You could always have a parameter to the constructor that needs to be set to some specific token value that indicates you shouldn't be instantiating this class, like "NeverInstantiateOutsideOfClassFoobar". :P
Yeah, that's what I meant about using a keyword argument to do it -- but that's really inelegant. I was hoping there'd be some simple way to accomplish it, but it might just end up being a risk I'll take (or something I'll try and reconcile at the dispatcher level).

Nyktos
Posts: 138
Joined: Mon Mar 02, 2009 4:02 pm UTC

Re: Coding: Fleeting Thoughts

Postby Nyktos » Sat Sep 06, 2014 7:55 pm UTC

You may be able to use _getframe to achieve something like that, but please don't. Just give the class an underscored name.

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7368
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Sat Sep 06, 2014 8:13 pm UTC

...oh, actually -- I didn't think of that. Underscore name works really well as a solution. Thanks!

User avatar
Moo
Oh man! I'm going to be so rebellious! I'm gonna...
Posts: 6440
Joined: Thu Aug 16, 2007 3:15 pm UTC
Location: Beyond the goblin city
Contact:

Re: Coding: Fleeting Thoughts

Postby Moo » Sun Sep 07, 2014 7:42 am UTC

Huh. I think I was thinking of division by zero rather than general NaN cases.

This is why I just lurk here, I always assumed I'm secretly an idiot despite coding for years. Now I no longer need suspect :)
Proverbs 9:7-8 wrote:Anyone who rebukes a mocker will get an insult in return. Anyone who corrects the wicked will get hurt. So don't bother correcting mockers; they will only hate you.
Hawknc wrote:FFT: I didn't realise Proverbs 9:7-8 was the first recorded instance of "haters gonna hate"

User avatar
phlip
Restorer of Worlds
Posts: 7573
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: Coding: Fleeting Thoughts

Postby phlip » Sun Sep 07, 2014 9:27 am UTC

Nyktos wrote:Python, however, does raise an exception in this case.

Code: Select all

>>> 0.0 / 0.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero

You can still get infinities and NaNs in Python though, and they still behave the same... you just can't get them from division by zero.

Code: Select all

>>> 1e308 * 1e308
inf
>>> _ - _
nan
>>> _ >= _
False

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Sun Sep 07, 2014 10:36 am UTC

IIRC, using IEEE floating arithmetic, sqrt(x) for x<0 returns NaN, and usually you get a negative NaN to hint at the cause.

C is nice, because its operations either return values, NaN, infinity, or it brutally murders your application with a SIGFPE :-)
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
Diadem
Posts: 5654
Joined: Wed Jun 11, 2008 11:03 am UTC
Location: The Netherlands

Re: Coding: Fleeting Thoughts

Postby Diadem » Sun Sep 07, 2014 11:51 am UTC

Maybe you were sarcastic, but honestly I like it when my application gets brutally murdered. It's so much easier to debug applications that just explode horribly upon the first error, instead of continuing in a corrupted state and end up dying much later or spitting out wrong results.

Did I mention I hate exceptions. I believe I did. I honestly can not see their point. If the code throws an exception, there are three possibilities. First I can catch it right away, in which case I might as well check for errors there without using exceptions. Secondly I don't catch it, in which case my application dies and then what was the point of exceptions? Or worst of all, I can catch it somewhere else in the code, which seems the intended use of exceptions, but just means my code is now slower, filled with boilerplate, inevitably full of hidden bugs, much harder to debug, and I have no real idea anymore what is going on.

[edit]
Just to be clear. I'm not so arrogant that i think I know better than those very experienced programmers who design programming languages, who came up with the idea of exceptions. Logic dictates that if many people more skilled than me think exceptions are a good idea, then they probably are a good idea. I just don't see it. I can't imagine a situation where I'd prefer having exceptions over not having exceptions.
It's one of those irregular verbs, isn't it? I have an independent mind, you are an eccentric, he is round the twist
- Bernard Woolley in Yes, Prime Minister

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby korona » Sun Sep 07, 2014 12:35 pm UTC

In my experience there are two legitimate use cases for exceptions:
  • Signaling errors to the calling code, e.g. Java's IOException. This use case is more or less equivalent to returning error codes. Checked exceptions have the slight advantage that you are forced to handle the error, while you could forget to check the error code. They can also reduce code bloat when used correctly. IMHO only checked exceptions should be used for this case; in languages like C++ that don't have checked exceptions I prefer error codes because they are part of the function signature while unchecked exceptions are not.
  • Letting the program die in a controlled manner, e.g. assertions. Sometimes your program discovers that it is in an illegal state it cannot recover from. In that case you can throw an (unchecked) exception and catch it at the top-level in order to log it, display it to the user or let the user submit a bug report. This case is hard to replicate without exceptions. Sure, you can call abort() directly but then you have to move the logging code to the place where you test the assertion, which is ugly and less flexible. Calling abort() inside libraries is also questionable practice.

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7368
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Sun Sep 07, 2014 12:53 pm UTC

What about cases where you're building on top of someone else's code, but can't -- or don't want to -- modify their code?

Let's say my code throws an exception when you pass an integer to this function, because this function was not meant to receive integers and I cannot imagine any cases where you would want to pass integers to this function. Then you come along and realize, 'oh hey, actually, I can imagine of a couple of cases where that would work perfectly for what I'm doing'. So, you send an integer to my function, raise the exception -- then 'catch' it and tell the code to proceed anyway.

Exceptions seem like a cool way to say 'Circumstance X appears deranged and therefore should raise an error -- but on the off-chance you find an actual use for circumstance X, here's one way to let the code proceed'.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Sun Sep 07, 2014 1:02 pm UTC

I like liberal use of exceptions inside modules, and sparse use of them in public APIs. It's a bit language dependent though. I use them more conservatively in C++, as its exception handling is a bit awkward.

Most of my business logic top-level functions look something like this

Code: Select all

try {
  doStuff();
  doOtherStuff();
  doYetMoreStuff();
} catch (ModuleOperationFailed ex) { // module-local exception
   // will contain a string like "data consistency error in item foobar123",
   // "missing price for instrument greekgovernmentbonds001",
   // "could not translate Klingon to English: Expected apostrophe in \"Q'apla'\""
  return ex.makeResponse();
}
return makeOkResponse();


or

Code: Select all

Status = new Status();
for (Thing thing : allThings) {
  try {
    doStuff(thing);
    doOtherStuff(thing);
    doYetMoreStuff(thing);

    status.setStatusOkFor(thing)
  } catch (ModuleOperationFailed ex) { // module-local exception with Thing field
    status.failedFor(ex.thing, ex);
  }
}
return status;


Sometimes there are more than one exception, but they're all unchecked, and never leave the module. I've found this is a very convenient pattern of error propagation.

Error propagation through return values within a module generally speaking sucks. It isn't faster than exceptions, you're basically manually re-implementing them anyway, and it makes the code much harder to read, and you lose the possibility of returning values (unless you use return value arguments, which makes for nasty signatures), and you gain the dangerous ability to ignore "exceptions".
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

schapel
Posts: 244
Joined: Fri Jun 13, 2014 1:33 am UTC

Re: Coding: Fleeting Thoughts

Postby schapel » Sun Sep 07, 2014 2:54 pm UTC

Diadem wrote:Maybe you were sarcastic, but honestly I like it when my application gets brutally murdered. It's so much easier to debug applications that just explode horribly upon the first error, instead of continuing in a corrupted state and end up dying much later or spitting out wrong results.

Did I mention I hate exceptions. I believe I did. I honestly can not see their point. If the code throws an exception, there are three possibilities. First I can catch it right away, in which case I might as well check for errors there without using exceptions. Secondly I don't catch it, in which case my application dies and then what was the point of exceptions?

The point is... It's so much easier to debug applications that just explode horribly upon the first error, instead of continuing in a corrupted state and end up dying much later or spitting out wrong results.

Also, in a language like Java you can be warned if you do not properly catch exceptions, so you're reminded to write the error checking code instead of continuing in a corrupted state and end up dying much later or spitting out wrong results.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Sun Sep 07, 2014 3:17 pm UTC

Yes. Fail fast.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

Nyktos
Posts: 138
Joined: Mon Mar 02, 2009 4:02 pm UTC

Re: Coding: Fleeting Thoughts

Postby Nyktos » Sun Sep 07, 2014 4:45 pm UTC

Exceptions are effectively a compromise between error codes and explode-on-error. It eliminates the possibility of ignoring an error, while still allowing the possibility of reacting to one. They're the only error handling strategy I've seen that has both of those properties without requiring loads of boilerplate around every call.

For what it's worth, I am definitely a fan of programs exploding when they can't handle something, which is why I think checked exceptions are awful: there is no shame in not handling an exception.

schapel
Posts: 244
Joined: Fri Jun 13, 2014 1:33 am UTC

Re: Coding: Fleeting Thoughts

Postby schapel » Sun Sep 07, 2014 5:09 pm UTC

Nyktos wrote:For what it's worth, I am definitely a fan of programs exploding when they can't handle something, which is why I think checked exceptions are awful: there is no shame in not handling an exception.

If you want that behavior, you can catch the checked exception and throw an unchecked exception. That would cause the program to explode when it can't handle something, and also clearly mark the places in the program where that could happen!

You could even decide to have the program explode during development so you can quickly find the error, and have the code log an error and attempt to recover when it's deployed. I think this is suggested in The Pragmatic Programmer -- asserts should crash during development and log an error when the program is deployed. In effect, you're asserting that checked exceptions will not occur. You can also choose to recover from checked exceptions on a case-by-case basis rather than crash or log an error.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Sun Sep 07, 2014 5:30 pm UTC

In some instances, you want to catch the exception on the same line you throw it ;-)

Example:
Spoiler:

Code: Select all

void addItem(Item item) {

  if (item.type == null) {
    // FIXME <joe@business.inc> 2014-09-03: We need to figure out what is causing this, see ticket 1234
    Exception npe = new NullPointerException("Item with id " + item.id + " is missing type, please report stack trace if you see this, issue reference 1234");
    logExceptionWithFullStackTrace(npe);
  }
 
  // do stuff
}


For some types of code, this can be a pretty useful error investigation paradigm if you're unable to hook up a debugger to the code and for whatever reason failing hard isn't an option.
Last edited by You, sir, name? on Sun Sep 07, 2014 5:31 pm UTC, edited 1 time in total.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

Nyktos
Posts: 138
Joined: Mon Mar 02, 2009 4:02 pm UTC

Re: Coding: Fleeting Thoughts

Postby Nyktos » Sun Sep 07, 2014 5:30 pm UTC

schapel wrote:If you want that behavior, you can catch the checked exception and throw an unchecked exception. That would cause the program to explode when it can't handle something, and also clearly mark the places in the program where that could happen!
I want the behaviour that exceptions bubble up until they're caught, and if they aren't caught then the program explodes. I don't necessarily know at any particular level whether I expect the exception to be handled higher up or whether I expect explosion.

I mean I could stick "throws Exception" on everything in Java to get this behaviour, but I prefer the solution of not writing Java.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Sun Sep 07, 2014 5:34 pm UTC

Nyktos wrote:
schapel wrote:If you want that behavior, you can catch the checked exception and throw an unchecked exception. That would cause the program to explode when it can't handle something, and also clearly mark the places in the program where that could happen!
I want the behaviour that exceptions bubble up until they're caught, and if they aren't caught then the program explodes. I don't necessarily know at any particular level whether I expect the exception to be handled higher up or whether I expect explosion.

I mean I could stick "throws Exception" on everything in Java to get this behaviour, but I prefer the solution of not writing Java.


So why not stick to unchecked exceptions (i.e. use only RuntimeException-derived classes)? In sensible code, checked exceptions should be pretty rare.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

Nyktos
Posts: 138
Joined: Mon Mar 02, 2009 4:02 pm UTC

Re: Coding: Fleeting Thoughts

Postby Nyktos » Sun Sep 07, 2014 5:39 pm UTC

That works fine too. I probably haven't written enough Java to have a good sense of how common checked exceptions actually are.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Sun Sep 07, 2014 5:45 pm UTC

Nyktos wrote:That works fine too. I probably haven't written enough Java to have a good sense of how common checked exceptions actually are.


I'd call them rare. There are some in the older parts of the Java API, but then that is infamous for its dubious design decisions. Like good old Boolean.getBoolean(). Reflect over the fact that Java has a class that wraps primitive booleans, parses strings into booleans, translates and booleans into strings, behaves like a boolean, and reads system properties. What. the. actual. fuck.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

schapel
Posts: 244
Joined: Fri Jun 13, 2014 1:33 am UTC

Re: Coding: Fleeting Thoughts

Postby schapel » Sun Sep 07, 2014 8:35 pm UTC

Nyktos wrote:
schapel wrote:If you want that behavior, you can catch the checked exception and throw an unchecked exception. That would cause the program to explode when it can't handle something, and also clearly mark the places in the program where that could happen!
I want the behaviour that exceptions bubble up until they're caught, and if they aren't caught then the program explodes. I don't necessarily know at any particular level whether I expect the exception to be handled higher up or whether I expect explosion.

I mean I could stick "throws Exception" on everything in Java to get this behaviour, but I prefer the solution of not writing Java.

Or you could do as I already suggested... catch the checked exception and throw an unchecked exception.

User avatar
Thesh
Made to Fuck Dinosaurs
Posts: 6598
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Sun Sep 07, 2014 8:47 pm UTC

I hate dealing with user input... So tedious, so not-rewarding.

I can't wait for the future when everything is automated and we can replace the users.
Summum ius, summa iniuria.

Nyktos
Posts: 138
Joined: Mon Mar 02, 2009 4:02 pm UTC

Re: Coding: Fleeting Thoughts

Postby Nyktos » Sun Sep 07, 2014 11:58 pm UTC

schapel wrote:Or you could do as I already suggested... catch the checked exception and throw an unchecked exception.
That works if I want to say "this definitely explodes", but what I actually want to say is "this explodes unless something higher up the call stack can handle it". Unless you're suggesting that anything higher up catches the unchecked exception; that's fine, but it's again the moral equivalent of not using checked exceptions at all.

User avatar
PM 2Ring
Posts: 3715
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Sydney, Australia

Re: Coding: Fleeting Thoughts

Postby PM 2Ring » Mon Sep 08, 2014 5:55 am UTC

All this talk of exceptions reminds me of Steinbach's Rule, which I think predates the invention of exceptions:
"Never test for an error condition you don't know how to handle".

:)

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby korona » Mon Sep 08, 2014 10:10 am UTC

Nyktos wrote:
schapel wrote:Or you could do as I already suggested... catch the checked exception and throw an unchecked exception.
That works if I want to say "this definitely explodes", but what I actually want to say is "this explodes unless something higher up the call stack can handle it". Unless you're suggesting that anything higher up catches the unchecked exception; that's fine, but it's again the moral equivalent of not using checked exceptions at all.

I think using checked exceptions for semi-exceptional code flow in Java is fine. Throwing a (checked) IOException when a read from a damaged hard disk fails is a perfectly fine design decision. It is equally hard to handle as an error code and has the additional benefit that you are forced to handle it. Letting the program explode in this situation is not an option in most cases (e.g. for database, web or other servers or even end-user GUI applications). If it is acceptable for your program just rethrow an unchecked exception like suggested above.

IMHO it is much better to have each read() method throw a checked IOException that can either propagate to the calling code or can be handled in-place than have each read() method return an error code that always must be handled in-place by some ugly if or select construct. Both solutions achieve the same thing while the second one introduces more bloat and does not actually force the user to check the error code.

As I already wrote in my previous post: Use checked exceptions as a checked alternative to error codes and use unchecked exceptions to abort the whole program. Of course you shouldn't throw checked exceptions for errors the user cannot (or usually does not want to) recover from like invalid state, invalid arguments, out-of-memory or failed assertions and preconditions but luckily the Java API (mostly) does not do that.

In the C world checked exceptions are roughly equivalent to checking errno or the return value while unchecked exceptions are roughly equivalent to calling abort() or raising a signal.

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Mon Sep 08, 2014 2:10 pm UTC

I'm not sure why, but using a text field to display a date value makes me irrationally angry at the person responsible, whomever they are.

Also, it's their fault I have to fix this other bug with that field that necessitates it not being text.

If only I too had low standards and was willing to just use DateTime.Parse...

User avatar
Thesh
Made to Fuck Dinosaurs
Posts: 6598
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Tue Sep 09, 2014 1:50 am UTC

With about 50 blocks like this:

Code: Select all

for (BaseType x in y.Stuff)
{
    if (x is DerivedType1)
    {
         ((DerivedType1)x).foo();
    }
    else if (x is DerivedType2)
    {
         ((DerivedType2)x).bar();
    }

//A bunch more

    else if (x is DerivedType10)
    {
         ((DerivedType10)x).baz();
    }
}


I really wish I could just do something like this:

Code: Select all

if (x is DerivedType)
{
    x@DerivedType.baz();
}
Summum ius, summa iniuria.

User avatar
Diadem
Posts: 5654
Joined: Wed Jun 11, 2008 11:03 am UTC
Location: The Netherlands

Re: Coding: Fleeting Thoughts

Postby Diadem » Tue Sep 09, 2014 8:20 am UTC

Me: "This variable is not initialized in the constructor, but if it is NaN our code blows up".
Senior Colleague: "No. This variable is either set there, or multiplied by zero, so everything is fine".

*sigh*
It's one of those irregular verbs, isn't it? I have an independent mind, you are an eccentric, he is round the twist
- Bernard Woolley in Yes, Prime Minister

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby korona » Tue Sep 09, 2014 9:17 am UTC

Thesh wrote:With about 50 blocks like this:

Code: Select all

for (BaseType x in y.Stuff)
{
    if (x is DerivedType1)
    {
         ((DerivedType1)x).foo();
    }
    else if (x is DerivedType2)
    {
         ((DerivedType2)x).bar();
    }

//A bunch more

    else if (x is DerivedType10)
    {
         ((DerivedType10)x).baz();
    }
}


I really wish I could just do something like this:

Code: Select all

if (x is DerivedType)
{
    x@DerivedType.baz();
}

What about a visitor pattern or virtual method?

User avatar
Thesh
Made to Fuck Dinosaurs
Posts: 6598
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Tue Sep 09, 2014 1:45 pm UTC

All of the types come from a third party library, so there is no modifying them.
Summum ius, summa iniuria.

User avatar
Yakk
Poster with most posts but no title.
Posts: 11129
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Tue Sep 09, 2014 2:27 pm UTC

Is your problem the fact that the method name changes?

Don't you have the equivalent of a traits template that lets you map a type to a method pointer/name in your language?

Or is it something else.
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
Thesh
Made to Fuck Dinosaurs
Posts: 6598
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Tue Sep 09, 2014 3:02 pm UTC

Yakk wrote:Is your problem the fact that the method name changes?

Don't you have the equivalent of a traits template that lets you map a type to a method pointer/name in your language?

Or is it something else.


Well, depending on the type of object there is different logic I have to run. Some objects I ignore completely, some objects have children I have to recursively loop through, for some I look at a single properties, for others I look at multiple properties. It's not really problematic, it's just annoying to have to wrap the whole thing in parenthesis to do the type cast.
Summum ius, summa iniuria.

User avatar
Yakk
Poster with most posts but no title.
Posts: 11129
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Tue Sep 09, 2014 3:13 pm UTC

So in C++, if I was really bothered by that, I'd write a dynamic cast switch (taking a list of types) that invoked a function (or function object) with a pre-casted argument. Then let overload resolution kick in.

This would move the dynamic cast and type checking away from the task code, and allow the task code to be moved nearer to the types in question (and distributed). Adding a new type would involve adding it to the type list, and making sure there was a valid overload (including ADL).

Of course, in C++ I would be less likely to be passing around a pointer to an object of a type distributed over multiple 3rd party libraries. I'd rather type erase the property I want to use later at the point where we had the full type information, which would move the invocation from being a chained set of dynamic casts to a simple dispatch. If this was a persistent/repeated problem, I might look into boost type erasure, or roll my own type erasure assistant.

I suppose we could be in a situation where we never have the full type information at compile time: the object is handed to me a as a root in a hierarchy, yet I'm still expected to violate the substitution principle and behave differently based on the dynamic type of the object. Meh, that would suck. More than one dynamic 'switch' run on the same code? Is it common? If so, we could reconstitute the static type information at the point where we get it from the library and store the type erased information there? Or maybe kick the library into orbit and see where it lands?
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
Thesh
Made to Fuck Dinosaurs
Posts: 6598
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Tue Sep 09, 2014 3:23 pm UTC

If I was redoing the whole thing, I would probably just serialize it as XML. Honestly, that would still work for my purposes and it would be a lot easier to work with had this hadn't already been mostly completed by the time I realized that.
Summum ius, summa iniuria.

User avatar
Sizik
Posts: 1260
Joined: Wed Aug 27, 2008 3:48 am UTC

Re: Coding: Fleeting Thoughts

Postby Sizik » Tue Sep 09, 2014 4:27 pm UTC

Thesh wrote:
Yakk wrote:Is your problem the fact that the method name changes?

Don't you have the equivalent of a traits template that lets you map a type to a method pointer/name in your language?

Or is it something else.


Well, depending on the type of object there is different logic I have to run. Some objects I ignore completely, some objects have children I have to recursively loop through, for some I look at a single properties, for others I look at multiple properties. It's not really problematic, it's just annoying to have to wrap the whole thing in parenthesis to do the type cast.


Do the casting separately from the method/property calls?

Code: Select all

    if (x is DerivedType1)
    {
        DerivedType1 x1 = (DerivedType1) x;
        x1.foo();
    }
she/they
gmalivuk wrote:
King Author wrote:If space (rather, distance) is an illusion, it'd be possible for one meta-me to experience both body's sensory inputs.
Yes. And if wishes were horses, wishing wells would fill up very quickly with drowned horses.

User avatar
Thesh
Made to Fuck Dinosaurs
Posts: 6598
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Tue Sep 09, 2014 4:46 pm UTC

If I have to access multiple properties, I do that. Still, creating a new variable just for accessing one property seems excessive.
Summum ius, summa iniuria.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Tue Sep 09, 2014 4:51 pm UTC

Not much to do at work, so I spent the day refactoring code.

I've noticed excessively long functions often seem to be long because their length makes it hard for developers modifying them to detect repetitive or unnecessary code.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

schapel
Posts: 244
Joined: Fri Jun 13, 2014 1:33 am UTC

Re: Coding: Fleeting Thoughts

Postby schapel » Tue Sep 09, 2014 5:17 pm UTC

Diadem wrote:Me: "This variable is not initialized in the constructor, but if it is NaN our code blows up".
Senior Colleague: "No. This variable is either set there, or multiplied by zero, so everything is fine".

Heh. I suppose I should share my NaN story. I was working on a program that computed the objective value for different models and then sorted the models by increasing objective value. The sort was performed by the C function qsort, which takes a function that compares two values. Since we were using floating point values, it made sense to use <, =, and > to compare them. The problem was that sometimes there was a problem computing the objective value, in which case the value would be NaN. Where do the NaNs end up in the sorted list? I suppose anywhere they want to!

I resolved the problem by considering NaN to be greater than +Infinity. That way, objective values that could not be computed were considered the worst, as lower objective value meant that the model was better.

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Wed Sep 10, 2014 2:23 pm UTC

Thesh wrote:

Code: Select all

if (x is DerivedType)
{
    x@DerivedType.baz();
}
Well, in C# 6.0 you can do

Code: Select all

(x as DerivedType)?.baz();

So... marginally less code anyway.

User avatar
Yakk
Poster with most posts but no title.
Posts: 11129
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Wed Sep 10, 2014 2:29 pm UTC

Code: Select all

    template<class T, class U, class F>
    if_is( U* u, F&& f ) {
      if (T* t = dynamic_cast<T*>(u))
        std::forward<F>(f)(t);
    }

    if_is<DerivedType>( foo, [&](auto* foo){
      foo->bar(); // foo here is a DerivedType*
    });

can something like that be done in C#?
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
Robert'); DROP TABLE *;
Posts: 730
Joined: Mon Sep 08, 2008 6:46 pm UTC
Location: in ur fieldz

Re: Coding: Fleeting Thoughts

Postby Robert'); DROP TABLE *; » Wed Sep 10, 2014 3:13 pm UTC

Code: Select all

void forward<T, U>(U u, Action<T> f) where T : class
{
   if (u is T)
   {
      var t = u as T;
      f(t);
   }
}
forward<DerivedType,Base>(foo, foo => foo.baz());
...And that is how we know the Earth to be banana-shaped.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 7 guests