Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
chocojosh
Jun 9, 2007

D00D.
When I first started my current C# job I hadn't touched HTML for about two years besides one database university course. I had also never touched .NET.

I was first asked to convert a simple page from asp to ASP.NET. For some stupid reason I didn't realize that drop down lists had a text and a value property. I ended up creating a "DropDownInfo" class to map the texts displayed to the IDs via two hashtables, and you'd see code all over the place like:

code:
Page_Load() {
   Get drop down text and IDs from stored procedure
   Store the texts and IDs into an instance of the dropdowninfo class
   Databind the texts to the dropdown lists
}

Update_Button_Click_Handler() {
   Get the selected text from the drop down list.
   Get the matching ID from the drop down info.
   Pass the matching ID to the stored procedure to update.
}
Ugggh. The senior dev didn't have the heart to tell me to rewrite it as it was my first time and that page is very rarely updated.

Adbot
ADBOT LOVES YOU

chocojosh
Jun 9, 2007

D00D.

That Turkey Story posted:

A little side story -- I've seen someone do this before when he was first learning to program and when I told him that he didn't need the parenthesis because return is not a function, he said that he was using the parenthesis not because he thought it was a function but because he wasn't sure of the order of operations. For instance, he thought return 1 + 3; might return the value 1 and then the rest of the expression was evaluated "after the return" and therefore not affecting the return value (in other words he thought return 1 + 3 could potentially behave something like (return 1) + 3 where "return 1" returned the value 1 and had a value in the encapsulating expression of 1). I was kind of puzzled for a second, but I was actually sort of impressed when I heard his rationale since it showed both that he questioned the effect of a type of return statement he had never seen before, as up until then he probably had only seen 1 term return statements, and he also realized that by using parenthesis there he could more safely assume the result that he wanted. He is now actually a very good programmer!

Of course, that was someone who had only just started programming a week before, so he had an excuse to not know the behavior, and if I saw any experienced programmer doing it I'd definitely be a little bit more baffled (though honestly who really cares, some extra parenthesis never hurt anyone).

I sometimes put the return expression in parenthesis simply because I find it more readable. Is that really a coding horror? :)

chocojosh
Jun 9, 2007

D00D.

zootm posted:

Like (return 1 + 2); or return (1 + 2);? I think in C-like languages I'd regard the former as something of a coding horror simply because it's so unusual that I wouldn't even know if it worked. Really strange.

The latter. Note that I don't think I've ever done return (retVal); but I will do things like return (x + 10); or return (x > 0)

chocojosh
Jun 9, 2007

D00D.
Usercontrol DateLookupWindow. It contains a textbox with a hyperlink to a calendar window so that we can pick a date and have it auto populate the textbox with the date (the user can also manually type in a date into the textbox if they want).

DateLookupWindow has a property called Date, whose type is a string. WHY? Either call it Text (to indicate the text of the checkbox) or let it be a Date and in the getter/setter handle the appropriate behaviour.

chocojosh
Jun 9, 2007

D00D.
Wouldn't the correct solution be to use a bitmask? Define each enum value to 2^i (i = 0,1,2,...,n) and then just check if the relevant is set?

chocojosh
Jun 9, 2007

D00D.
In all seriousness then, how would you encode N different options that can be on simultaneously? I always assumed the bitmask would work (and I would go so far to say that it is a simple and clear solution that should be efficient enough for small cases, n <= 8 or n <= 32).

chocojosh
Jun 9, 2007

D00D.

Drx Capio posted:

std::vector<bool> AFAIK is almost always implemented as a bitfield that uses proxy objects to modify its 'bool references'. I doubt that the 31 bits you save per bool really add up to anything significant, but it's a simple solution at least.

Alright, so then you also second the bitmask suggestion (which means I'm not totally crazy).

In C++ you can use the bitset

chocojosh
Jun 9, 2007

D00D.

Drx Capio posted:

No, that's just a viable alternative if you're retarded and don't want to go with the prime factorization solution. Why would you use dynamic memory at runtime when you can quickly run through a sieve of eratosthenes and get some valid, unique flags?

For simplicity? Am I missing something here or does it just seem to be much easier to use a vector<bool> (or bitset) and just count the enumerated bits? I honestly don't see what advantage there is to factoring prime numbers.


Also, if you need 32 different options, then wouldn't you need to multiply the first 32 prime numbers together? That multiplication gives 31610054640417607788145206291543662493274686990 (47 digit number). I think that would require a significant amount of memory space..

I'm really lost as to who is joking right now :(

chocojosh
Jun 9, 2007

D00D.

king_kilr posted:

He's not looking for things that multiple together uniquely, it's addition.(I think)

How would you be able to factor primes by addition?

Let's pick the primes 2,3 and 5. If you use addition then 2 + 3 = 5. How would you distinguish 5 from representing 2 + 3 or from just representing 5.

However, using prime numbers you can find a number that is the product of those primes (as every number can be represented as a unique product of primes).


TSDK posted:

What if, now hear me out guys, what if we use this compression scheme where we represent each prime by a particular power of two. So the i-th prime is encoded as 2^i, and then add these together to represent which primes are factors of the number we're compressing.

Yeah, umm, that's called a bitmask :)

Alright, this thread has been good for some laughs.

chocojosh
Jun 9, 2007

D00D.

king_kilr posted:

What about 1, 4, 7 any addition of these numbers will be a unique sum(unless you need to add the same value multiple times, in which case primes are the only option).

A bitmask can do the exact same thing and will use less space ;)

1 2 4 (Decimal)
001 010 100 (Binary)

1 + 2 + 4 = 7
1 + 4 + 7 = 12


Also, king_kilr, what set of numbers would you use if you have 5 numbers that will always be a unique sum.. or 10 numbers.. or 100 numbers...

chocojosh
Jun 9, 2007

D00D.

JoeNotCharles posted:

Jesus, what is it with you and your fetish for bitmaps?

I simply want somebody to show me how they can implement something using prime factorization or whatever in a way that is better than bitmaps. Nobody has been able to so far, or I am not understand them if there is a better way.

I still feel that I'm new to programming and second-guess myself a lot. I know that a lot of people on these forums know more than I do, but I simply don't see why you would use anything except for a bitset. I'm thinking that most of the people are deliberately posting outrageous solutions as a joke, but I'm not sure if maybe they are being just a bit serious at the same time.

chocojosh fucked around with this message at 20:10 on Apr 25, 2008

chocojosh
Jun 9, 2007

D00D.
Some awesome code I saw today:

code:
dataRow[columnName]=  IIF(osui.GetString(optionSystemName)==null,"(N/A)",osui.GetString(optionSystemName));


protected string IIF(bool expression,string returnValue1,string returnValue2)
		{
			if (expression==true)
			{
				return returnValue1;
			}
			else
			{
				return returnValue2;
			}						 
		}

We couldn't have just used the ? operator?

chocojosh
Jun 9, 2007

D00D.

Mr.Radar posted:

The person who wrote that probably cut their teeth with VB6 and wasn't aware of the ?: operator. VB6 didn't have a dedicated short-circuiting inline conditional operator, but it included a (non-short-circuiting IIRC) IIF function that worked like the one you posted.

Thanks :) The person who wrote the function also wrote a lot of our old ASP/VB6 SQL 2000 code. That would explain it.

chocojosh
Jun 9, 2007

D00D.

stack posted:

This makes me cry
code:
@empty($someVar)

@isset($someVar)
What error are you trying to suppress? If the value doesn't exist they'll return false. isset() for the love of pete exists to check if a value 'is set'.

Also this hurts me
code:
if(!isset($bravo)) $blah = here($something);
elseif(isset($charlie)) $blah = here($charlie);
else $blah = nothere();
Whitespace is free goddamnit. A couple pairs of braces couldn't hurt either.

New code is committed daily that is littered with examples and uses of the above.

Stack: I tend to code regularly like this:

code:
if(!isset($bravo))
   $blah = here($something)
elseif(isset($charlie)) 
   $blah = here($charlie)
else
   $blah = nothere();
My logic is I hate wasting an entire line just to show a brace. Also, I think that python has a specific syntax for an if statement in the form of
if <condition>: <statement>

chocojosh
Jun 9, 2007

D00D.

Jethro posted:

Unless you're using an 80 line monitor for some terminal from the '80s, there is no such thing as "wasting a line."

To me, the line is wasted because it's more that I have to process. If I need to read 20 lines to understand a function instead of 15, then it is more difficult for me to process because it takes up more space, even if part of the space is only closing braces.

I also prefer clear code instead of very terse code. I basically like to make code "easy to read" because as Spolsky (lol) said, code is read much more often than it is written.

chocojosh
Jun 9, 2007

D00D.

JoeNotCharles posted:

What's wrong with this? The only weird thing I can see is that db.Open is called after creating the transaction, but that doesn't have anything to do with your comment so I assume that's just the way the API works.

I imagine the catch all Exception instead of an SqlException?

To be honest though I use catch-all exceptions due to lazyness. I don't really care *why* I can't delete from the DB.. just that it failed.

chocojosh
Jun 9, 2007

D00D.

Vanadium posted:

As posted in ##c++ on freenode:
code:
iteration_begin:
std::vector<CGameEvent*>::iterator lIterator = mEvents.begin();
for(lIterator; lIterator != mEvents.end(); lIterator++)
{
	if((*lIterator)->Dirty())
	{
		DestroyEvent(*lIterator);
		//Yes this is a shame, but once we remove an element the iterator is invalidated
		// there is for sure a better way to handle this, we do not want to only break
		// as this would keep the remaining event from being iterated
		goto iteration_begin;
	}
	(*lIterator)->OnIterate(inDeltaT);
}

Would it have been so hard to keep a second vector of invalid nodes and then invalidate those after the for loop?

chocojosh
Jun 9, 2007

D00D.
Sorry, I wasn't clear, I meant:

code:
std::vector<CGameEvent*>::iterator lIterator = mEvents.begin(); 
std::vector<CGameEvent*> invalidEvents;

for(lIterator; lIterator != mEvents.end(); lIterator++) { 
    if((*lIterator)->Dirty()) { 
        invalidEvents.push_back(*lIterator);
    } 
    (*lIterator)->OnIterate(inDeltaT); 
}

//Starting at last node in case vector size changes
for(int i = invalidEvents.size(); i >= 0; i--) {
    DestroyEvent(invalidEvents[i]);
}
I haven't touched the STL in over two years though -- your code makes much more sense.

chocojosh
Jun 9, 2007

D00D.

deimos posted:

Calling Nebby here to ILLUSTRATE TO YOUR PLEBE BRAIN how SUPERIOR HUNGARIAN NOTATION is.

Obviously we just don't see the light here. HUNGARIAN WILL SAVE YOU FROM THE DEVIL.

chocojosh
Jun 9, 2007

D00D.
And why are all variable names only three letters long?

fle? file!
lin? line!

chocojosh
Jun 9, 2007

D00D.

Ryouga Inverse posted:

Okay, look, there's a difference between there possibly being edge cases in which it can be used and...
code:
        private void ReadIniFile()
        ....
I mean, I feel like I'm reading Ruby or something, except ugly.

What exactly is wrong with that code? He has an INI file with three lines in the form of X=Y and he's taking the second field of the first three lines and using them to populate values. How is it ugly?

chocojosh
Jun 9, 2007

D00D.

Ryouga Inverse posted:

:words:

Thanks, because of the comment you made about the goto I read it four times wondering where the goto was.

Outlaw: When I wrote a small desktop app for my company last summer, I just followed the "standard convention" at our office and used app.config. I believe ConfigurationManager.AppSettings was what I used.

I hope it didn't take him 60 hours to just come up with a 20 line function! If so.. are you looking to replace him?

chocojosh
Jun 9, 2007

D00D.

Zakalwe posted:

That's not a horror, that's a savage optimisation for an operation done a lot in many renderers. Low accuracy bitwise hack combined with one Newton-Raphson iteration.

Fixed the quote. I do wish the code had some more spaces in it though :(

chocojosh
Jun 9, 2007

D00D.

wrok posted:

code:
    foreach (string item in _ptAttributeDic.Keys)
    {
        string val = _ptAttributeDic[item];
        switch (item.ToLower())
        {
            case "mail":
                if (string.IsNullOrEmpty(base._email))
                    base._email = val;
                break;
            
            case "facsimiletelephonenumber":
                base._faxNum = val;
                break;
            
            case "telephonenumber":
                base._phoneNumber = val;
                break;
        }
    }

So this is such a bad varation of the for-switch that once it matches either "mail", "facsimiletelephonenumber", or "telephonenumber" it's going to exit the loop.

Unless the author meant to only initialize one of them, but then it would just be much easier to use

if(_ptAttributeDic.Contains("X"))
base._X = _ptAttributeDic["X"];
...

chocojosh
Jun 9, 2007

D00D.

Scaevolus posted:

Serious question, have you ever used C, C++, C#, or Java?

I'm a .NET developer working on WPF, WCF, and Windows Mobile.

I had a brain fart about how break works. Other stuff was on my mind.

chocojosh
Jun 9, 2007

D00D.

king_kilr posted:

Guys you should be using ruby so you can just monkeypatch a to_radians and to_degrees functions onto int.

C# has extension methods that can do that.

chocojosh
Jun 9, 2007

D00D.

Captain Capacitor posted:

I'm guilty of nondescript variables in two ways: Loop variables and isolated variables in methods/procedures under 5 lines or so (for example, getters/setters).

What's the general opinion on short variable names that are explained/in limited context?

code:
def averageLoginCount():
  q = query = User.objects.all()
  q = q.filter(firstname__contains='y')
  q = q.aggregate(Avg('login_count'))
  return q

I'm wondering why you do q = query = ... Is it to set the value to both q (local var) and query (object var)?

For local variables, I fairly often create objects from the initials of the class name, such as:
FlipTransition ft = new FlipTransition();
MemoryStream ms = new MemoryStream();

Some people have gone "uggggh I don't like it", but my coworkers do similar things and for local variables in short functions it tends to not be a problem.

Adbot
ADBOT LOVES YOU

chocojosh
Jun 9, 2007

D00D.
Dear former intern: Just because .NET allows you to pass any object in the sender field of the event, does not mean you should use it to pass any arbitrary data. The first google result of "C# Custom Event" shows you exactly how to pass in custom event args.

Also, if your dialog only contains an ok and cancel button, you don't need to fire an event on when ok is pressed. Use the Dialog Result instead.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply