• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

hateradio

The Most Dangerous Yes Man
You don't have to quote everything! :p

Agreed. Though in Swift specifically, I don't particularly like the notation for explicit typing.
You mean colon followed by type? I actually really like that because you're declaring the variable/constant as immutable or not and then its type. It also sidesteps the need to use a word like final in Java.

Immutability is an important aspect of functional programming, and is a great proponent to concurrent processing because you don't have to worry about side effects.
 

iapetus

Scary Euro Man
You don't have to quote everything! :p

I don't - just the parts I'm responding to directly. :p

You mean colon followed by type? I actually really like that because you're declaring the variable/constant as immutable or not and then its type. It also sidesteps the need to use a word like final in Java.

I could probably get used to it; as it is, I like the white space between type and name from a clarity perspective.
 

Two Words

Member
I rely on your imagination to provide a more concrete example. If all your methods specify the type in the method name, then I'm thinking you need better naming conventions. :p



Enough with the '3 extra keypresses' bullshit.

Ba<autocomplete> badger = no<autocomplete>.<autocomplete> with explicit typing.

a<autocomplete> badger = no<autocomplete>.getB<autocomplete> without.

I make that 18 keypresses with explicit typing, 21 without, because explicit typing allows the IDE to know which method or methods you're going to be calling to get the value based on their return type, but inferred typing doesn't. Either way, if your productivity as a developer is based around three keypress differences in typing, then you're not doing enough thinking.

Oh, and I just remembered my IDE will autocomplete simple variable names, so actually <autocomplete> will give 'badger' as the top match when declaring a variable of type Badger. That's another five keypresses saved, for a completely irrelevant 8-keypress advantage to explicit typing.

I'll listen to people who find the inferred typing looks more elegant in certain cases, even though I disagree for a lot of real cases that I come across. But really, the number of keypresses it takes to write the two versions is utterly irrelevant and actually tends to come down on the side of explicit typing because it allows the IDE to be more intelligent more quickly.

Maybe I'll change my mind when I use a language in anger that supports inferred typing. But it won't be because of saved keypresses, I can promise you. It'll be because there are advantages in code maintenance and readability that I just don't see right now.



Which is fine. A lot of this stuff is entirely subjective, and a lot of it will depend on your coding background.



Explicit type declarations explicitly ensure that the type in question is what was intended. That's what they do. There's no false confidence there - just a real confidence that you aren't assigning the wrong type anywhere (unless you explicitly choose to do so), or accidentally referencing objects at the wrong level of bstraction. It's very limited, but very good at catching such problems early. I don't see where you get the idea that this can instil a false level of confidence in the code.

Unit tests, however, can to a point. There will be cases where the tests all pass, but there's still a horrible bug. That's nothing to do with the tests not being written correctly; it's a necessary part of developing unit tests. What you should then do is create a new test for that bug, which may be an edge condition that hadn't been tested for previously, or a new type of input that hadn't been expected or encountered before, which improves your test suite. But to think (as some people wrongly do) that 'the tests all pass' is the same as 'there are no bugs' is instilling a false sense of confidence - 'the tests all pass' means 'the tests all pass'. In fact, in some cases it means 'the tests all passed this time' - that's normally a sign of badly written tests, of course.

Edit: My above keypress estimates were based on the flawed assumption that 'autocomplete' is a single keypress - obviously in most cases it will be two or even three. This doesn't change the basic point, and is still utterly irrelevant. :p
Inferred variable types seem especially confusing if you are overloading a function. What if you need to make the same exact function but for different data types? It would be easiest to overload it so you don't have to memorize different names. Can you even overload without explicitly naming data types?
 
Inferred variable types seem especially confusing if you are overloading a function. What if you need to make the same exact function but for different data types? It would be easiest to overload it so you don't have to memorize different names. Can you even overload without explicitly naming data types?

You can't overload functions that way.
Code:
public List<Edge> getEdges(double[][] array) { return null; }
public Queue<Edge> getEdges(double[][] array) { return null; }
This won't compile (in Java) because 'getEdges(double[][]) is already defined'. The two overloaded functions must differ in the argument list, not just in the return value. Also, Java's type erasure can be really annoying when overloading functions/constructors. I have a class that draws a graph in a Swing window and I wanted to have two constructors like those:
Code:
    public GraphDrawFrame(Map<Integer, Location> v, List<Edge> e) {
        V = v;
        E = e;
    }

    public GraphDrawFrame(Map<Integer, Location> v, List<Location> tour) {
        V = v;
        T = makeTour(t);
    }
Doesn't work because both constructors have the same type erasure (List<Whatever> becomes List<Object> at runtime because the JVM doesn't handle generics that way).
 

hateradio

The Most Dangerous Yes Man
Inferred variable types seem especially confusing if you are overloading a function. What if you need to make the same exact function but for different data types? It would be easiest to overload it so you don't have to memorize different names. Can you even overload without explicitly naming data types?
Typically, you cannot declare methods without declaring the parameter types. Return types are also required, again, typically.

However, you can make closures without parameter types in certain contexts. Those don't get overloaded, so that's not an issue then.
 
What are your opinions on pair programming? I'm interviewing at a company that does pair programming tomorrow. Never really done it before.
 
What are your opinions on pair programming? I'm interviewing at a company that does pair programming tomorrow. Never really done it before.
It's at its maximum effectiveness when you have an inexperienced developer working with an experienced developer. It's a great way to get people up to speed.

It's also used in extreme programming as a substitute for proper code review, but I'm not the biggest fan of that methodology.
 

iapetus

Scary Euro Man
It's also used in extreme programming as a substitute for proper code review, but I'm not the biggest fan of that methodology.

Why not? The theory is that the sooner you catch a bug, the cheaper it is to fix. Catching the mistake before it's made is a lot more efficient than catching it after days of development and causing more days to rework it.
 

Magni

Member
What are your opinions on pair programming? I'm interviewing at a company that does pair programming tomorrow. Never really done it before.

I did a lot of pairing when I first started at my current job, it helped me get up to speed quickly. We also pair as part of the interview process (just paired with a candidate yesterday actually).

I still pair occasionally, especially for non-trivial jobs, but it definitely doesn't replace the code review part. Getting fresh eyes on some code is crucial before merging it in to master.
 

Makai

Member
I think I faceplanted my first technical interview. I was expecting something pretty tough, but the programming assignment turned out to be fairly trivial. That didn't stop me from taking about twice the recommended time to complete it, though. At least my solution had good Big-O complexity. :|

 

Kansoku

Member
So I'm making the chrome extension I mentioned some time ago. I'm using this as base.

Managed to get the sidebar the way I want, but there's one thing that I don't know how to do. I want the sidebar to be hidden* and when I hover the mouse at the edge of the window it would appear and would be there until a second or so after I remove the mouse from the sidebar (not the edge). I know how to make it listen to a hover, but not in a specific area. Can anybody help me?

*Question. If I hide an div element with a script which have links on it, does the links still work? (Like if its centered on the window and have a list of links, if I hide it an click the middle of the window, does it open the links?)
 

CrankyJay

Banned
C# problem that has me stumped, hopefully one of you guys will be able to help.

Here's the code that matters, with a description of what's wrong below.

Code:
...

The Like() and Unlike() methods are called by the code-behind of one of my XAML views. This view has bindings to the liked and likeText fields of an APIStory.

The expected behavior: calling Like() (or Unlike()) resets the likes property, which triggers the PropertyChanged events, which changes the XAML.

What happens: The first call to Like() (or Unlike()) triggers the PropertyChanged events, but the XAML view isn't updated the first time. On the second call to Like() (or Unlike()), the events are triggered again, but this time the XAML gets updated.

So: why is this only working every other time? Why does the XAML only get updated every other time even the PropertyChanged events get triggered every time?

Any pointers would be much appreciated :)

Also, there has to be a better way to write that code-behind event handler! Those casts make my eyes hurt.

This seems like an overly complicated way to handle this. Instead of binding your LikedText to MyFlyoutItem, why not bind Liked and then have a Converter that will read in Liked and return the Liked text?

Also, it might be helpful to know what MyFlyoutItem is inheriting from (a Button)?

Code:
<UserControl.Resources>
    <conv:LikedToLikedText x:Key="convLikedToLikedText"/>
</UserControl.Resources>



<MyFlyoutItem Text="{Binding Liked, Converter={StaticResource convLikedToLikedText}}"/>

.
.
.

public class LikedToLikeText : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool liked = parameter as bool;

        return liked == true ? "Liked" : "Not Liked";
    }
}

I don't even think you'll need APIStory to inherent from IPropertyNotifiedChanged...
 

Magni

Member
This seems like an overly complicated way to handle this. Instead of binding your LikedText to MyFlyoutItem, why not bind Liked and then have a Converter that will read in Liked and return the Liked text?

Also, it might be helpful to know what MyFlyoutItem is inheriting from (a Button)?

Code:
<UserControl.Resources>
    <conv:LikedToLikedText x:Key="convLikedToLikedText"/>
</UserControl.Resources>



<MyFlyoutItem Text="{Binding Liked, Converter={StaticResource convLikedToLikedText}}"/>

.
.
.

    public class LikeToLikeText : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool liked = value as bool;

            return liked ? "unlike" : "like";
        }
    }

I actually have a // TODO: move this to a Converter next to my likeText declaration haha. Fixed your code a bit (I've been bit before by thinking that you can bind to a ConverterParameter, it's the value that you bind to).

The MenuFlyoutItem is coming from a ListViewItem.

I'm thinking the problem is coming from the asynchronous nature of the API calls and not my app, so I decided to just hardcode the likes object I expect to get back after liking/unliking, and reload that object from the server if I get an error back from my liking/unliking API call.
 

CrankyJay

Banned
I actually have a // TODO: move this to a Converter next to my likeText declaration haha. Fixed your code a bit (I've been bit before by thinking that you can bind to a ConverterParameter, it's the value that you bind to).

The MenuFlyoutItem is coming from a ListViewItem.

I'm thinking the problem is coming from the asynchronous nature of the API calls and not my app, so I decided to just hardcode the likes object I expect to get back after liking/unliking, and reload that object from the server if I get an error back from my liking/unliking API call.

Yeah sorry it's value, not parameter and I got the text wrong. Was coding on my other screen simultaneously so I was distracted. Hehe.
 
Good luck!

Good luck! :)

Thanks! I was offered the job!

It was an interview for an internship for the rest of the summer. (I know it's late, but I had originally had a different one lined up that didn't work out.)

The interview went pretty well (besides a few dumb things I think I said). I feel like I nailed the programming problem. It started off as him having me implement and test a Fibonacci function. That was easy, and then we discussed the running time complexity of it on large values, and how it would literally never finish when n = 256. That led to him asking me to propose a solution. I've implemented several memoizers recently, so I was able to explain how you could cache the recursive Fibonacci calls. I implemented that, and then he asked me to abstract the memoizer so that it could be used for most functions.
 

Two Words

Member
So how similar are programming languages as far as syntax goes? So far I'm learning C++ and Java and a lot of what I've learned so far is basically identical. The reserved words like int, double, string, while, for, return, if, etc and the method which functions pass values or references is identical and so on. Is this something I'll be able to depend on being consistent with most programming languages or do a lot of them have very different syntaxes and I've just lucked out on Java and C++ having a lot of similarities? Or am I still at a low level in C++ and Java and have yet to hit where they really differ?
 

hateradio

The Most Dangerous Yes Man
So how similar are programming languages as far as syntax goes?
For procedural languages, there are two basic types: those that follow the C-style syntax and those that do not.

Java was meant to be like C++, but without all the complications, so that's why its structure is similar.

Popular languages under the C-style umbrella: C++, Java, PHP, JavaScript, C#, Rust, etc.

However, there are other languages that do very different things, but they usually have similar concepts.

Languages that are different: Python, Ruby, Scala, Objective-C, Swift, etc.

Non-procedural languages are usually very different.
 

tokkun

Member
Does anyone here use C++ regex's?

I have tried using both libstd and boost's regex libraries, and cannot even get the example code in the documentation to work in either clang or gcc.
 

Magni

Member
So how similar are programming languages as far as syntax goes? So far I'm learning C++ and Java and a lot of what I've learned so far is basically identical. The reserved words like int, double, string, while, for, return, if, etc and the method which functions pass values or references is identical and so on. Is this something I'll be able to depend on being consistent with most programming languages or do a lot of them have very different syntaxes and I've just lucked out on Java and C++ having a lot of similarities? Or am I still at a low level in C++ and Java and have yet to hit where they really differ?

Look at Lisp or Prolog for example. Also some esoteric languages (cool but pointless), like Brainfuck or Whitespace.
 

Atruvius

Member
Does anyone here use C++ regex's?

I have tried using both libstd and boost's regex libraries, and cannot even get the example code in the documentation to work in either clang or gcc.

I have had problems with boost's regex. I have only gotten it to work using CMake.

C++11 has regex stuff but I guess there's a reason you're using boost and other libraries instead of it.
 

Water

Member
Does anyone here use C++ regex's?

I have tried using both libstd and boost's regex libraries, and cannot even get the example code in the documentation to work in either clang or gcc.
I used the implementation shipping in VS2012 to do something small, that worked fine.
 
What are your opinions on pair programming? I'm interviewing at a company that does pair programming tomorrow. Never really done it before.

My favorite thing about pair programming is that for me it's a great productivity tool. Because there is another person with me it's not an option to get distracted and go off and do something else like check emails or tool around with an unimportant piece of code
or post on GAF
. A lot of the time it can be more efficient in that while the driver is implementing a method or class the navigator can be planning ahead for the next step which leaves less down time as once your implementation is finished they can start talking you through the plan for the next step and it's more developed. It's actually one of my favorite coding situations because it really makes the day fly by.
 

Stumpokapow

listen to the mad man
Quick Python sanity check:

I have a single-line string. I want to split the string using a delimiter. Say for example my delimiters are " - ", "; ", or ": " (ignoring quotation marks. So space dash space, semi-colin space, and colon space are my three delimiters; The delimiter needs to be a regexp, so I can't use the string split method. The string can contain one or more of the delimiters. I want the split to occur on the right-most delimiter, leaving the entire rest of the string intact.

In other words
"Test1 - test2 - test3 - test4" should split to "Test1 - test2 - test3" and "test4".
"Test1: test2 - test3; test4" should also split similarly; "Test1: test2 - test3" and "test4"
"Only one delimiter - in this one" should split to "Only one delimiter" and "in this one"

Code:
import re
myStr = "This is a test string: I am using it - as an example; end of my string"
if re.match("(.*)( - |; |: )(.*)",myStr):
	print "At least one match"
	myStr1, myStr2 = [b]??? python-fu goes here???[/b]
	print myStr1  # "This is a test string: I am using it - as an example"
	print myStr2	# "end of my string"
else:
	print "No matches, go away"

What is the most pythonic way to do this? The string split method has an rsplit analogue which does a rightmost split; this is elegant, but won't work here because I need to split on a regexp. If I just wanted to split on a space, that would be no problem at all. The re.match method finds the FIRST match, when I want it to find the last--so I could reverse the string and reverse the delimiters, find the first match, do the split, and reverse both results. But this is not elegant, it's an obvious hack. I could find all matches, bust the string apart, and munge it back together by looping over the results doing a join function. This is also not elegant. I could use a negative lookahead regexp to try to have the regexp capture do the heavy lifting, but that's disgusting looking.

Aesthetically (performance is not a significant factor here), what is the most beautiful way to do this?

So far my most elegant solution is:
m = list(re.finditer("( - |; |: )",myStr))[-1]
myStr1 = myStr[:m.start(0)]
myStr2 = myStr[m.end(0):]

Any preferable way?

Edit: Someone suggested:
myStr1, myStr2 = myStr.rsplit(re.findall("( - |; |: )",myStr)[-1])
Definitely pretty close to pythonic there.
 

Magni

Member
Quick Python sanity check:

I have a single-line string. I want to split the string using a delimiter. Say for example my delimiters are " - ", "; ", or ": " (ignoring quotation marks. So space dash space, semi-colin space, and colon space are my three delimiters; The delimiter needs to be a regexp, so I can't use the string split method. The string can contain one or more of the delimiters. I want the split to occur on the right-most delimiter, leaving the entire rest of the string intact.

Hmm, fun problem for sure.

Got this quickly, kinda ugly for sure.

Code:
import re
my_str = 'This is a test string: I am using it - as an example; end of my string'
my_str_1 = re.split(' - |: |; ', my_str)[-1]
my_str_2 = re.split('( - |: |; ){}$'.format(my_str_1), my_str)[0]

edit: that edit is definitely more Pythonic
 

BreakyBoy

o_O @_@ O_o
You Python people are cute. The edit is pretty much the solution I would have done in Ruby or Perl. I'd go with that one.

Edit: To be fair, I also chuckle at "Rubyists", who do much the same about "beautiful" code. And also to be fair, I do lean toward that stance versus TIMTOWTDI Perl-ers one-lining the most complicated of things.

It's just all amusing to me.
 
I've got an assignment for an algorithms class to implement a branch-and-bound algorithm for the Euclidean Travelling Salesman Problem with precedence constraints (the constraints say that in the TSP tour, a given node must come before another node. So, for the constraint "1 before 5", [4, 1, 3, 2, 5] would be a valid solution), I've been stuck with creating a tour that satisfies the constraints. I've implemented the Kruskal algorithm to create a minimum spanning tree and I can create a normal TSP tour from the MST (as described here) but I don't know how to work the constraints into it. I've thought about (and implemented) switching to a nearest neighbor heuristic, since that would simplify incorporating the constraints (until the tour contains every node, for each adjacent node to the current node, take the one with the lowest weight that doesn't violate the constraints).

It's a pretty mean assignment, especially since every test case needs to pass or I'll fail the whole class (and not all of the test cases are public, there's a few randomly generated ones that we don't get to see).
 

Two Words

Member
I'm pulling my hair out over this and I can't figure out this C++ problem. It has to be something stupidly simple I am missing. This code is part of a function that simply asks the user to enter numbers to fill into an array called list[ ]. The only way I know how to find a stopping point is to ask the user 'y' or 'n' between each number input. The problem is that the while loop does not end even wen the user selects 'n'. The if statement for always is validated and prints out "Enter your next number" and the whole while loop goes over again.


LENGTH is an int constant I am using for my array's length and is set equal to 100 at the beginning of the program.



Code:
void fillArray(int list[], const int LENGTH)
{ // Opening for void fillArray(int list[], const int LENGTH, char& ender)
	cout << "Enter no more than 100 integers into the array in any order. Hit enter after each number." << endl;
	int adder = 0;
	char ender;

	while (ender = 'y' || adder < LENGTH)
	{ // Opening for "while (ender = 'y' || adder < LENGTH)"
		cin >> (list[adder]);
		cout << endl << "Do you have another number to enter? Hit y for YES or N for No." << endl;
		cin >> ender;
		ender = static_cast<char>(tolower(ender));
		while (ender != 'y' && ender != 'n')
		{ // Opening for "while (ender != 'y' && ender != 'n')"
			cout << endl << "That was not a valid input. Please enter y or n." << endl;
			cin >> ender;
			ender = static_cast<char>(tolower(ender));
		
		} // Closing for "while (ender != 'y' && ender != 'n')"
		if (ender = 'y')
		{ 
			cout << "Enter your next number." << endl;
		} 

		adder++;
	} // Closing for for "while (ender = 'y' || adder < LENGTH)"

cout << "The array you entered was: " << endl;

	for (int printer = 0; printer < adder; printer++)
		cout << list[printer] << " ";

	cout << endl;

} // Closing for "void fillArray(int list[], const int LENGTH, char& ender)"
 
all of your while loops and if statements need to check for equality "x == y". Right now you're just assigning them "x = y" so it'll always evaluate to 'true'.

Code:
while (ender = 'y' || adder < LENGTH)
to
Code:
while (ender == 'y' || adder < LENGTH)
 

Two Words

Member
Uuuuugh, what's weird is that I noticed it almost immediately in the codeblock on neogaf after staring at it for 15 minutes on Visual Studios 13 and hoped I could edit out that I fixed it before I got any responses :p
 

arit

Member
Uuuuugh, what's weird is that I noticed it almost immediately in the codeblock on neogaf after staring at it for 15 minutes on Visual Studios 13 and hoped I could edit out that I fixed it before I got any responses :p

I'm surprised that the compiler didn't give you a warning, at least gcc does in that case (or maybe just because of -Wall).
 

poweld

Member
The ol' double = issue.

Just thought I'd mention while this is being brought up that this is the reason many swear by putting your constant first in equivalency checks.

If the code had been
Code:
'y' = ender
a compiler error would have been thrown (assignment to a constant).[

This is handy to avoid these sorts of issues, though it can read kinda funny (e.g. "If yes is the answer" sounds strange compare to "If the answer is yes")
 

phoenixyz

Member
I have a single-line string. I want to split the string using a delimiter. Say for example my delimiters are " - ", "; ", or ": " (ignoring quotation marks. So space dash space, semi-colin space, and colon space are my three delimiters; The delimiter needs to be a regexp, so I can't use the string split method. The string can contain one or more of the delimiters. I want the split to occur on the right-most delimiter, leaving the entire rest of the string intact.

I would do

Code:
import re

s = "Some string with de,limit;ers"
split = re.split("[-:;,]", s)
s1 = "".join(split[:-1])
s2 = split[-1]
 

Water

Member
Just thought I'd mention while this is being brought up that this is the reason many swear by putting your constant first in equivalency checks.

If the code had been
Code:
'y' = ender
a compiler error would have been thrown (assignment to a constant).[

This is handy to avoid these sorts of issues, though it can read kinda funny (e.g. "If yes is the answer" sounds strange compare to "If the answer is yes")
I used to do that for a while, but I now consider readability much more important, and do not seem to write that kind of bugs anyway. Like arit said, a compiler should be able to warn about that as long as a high enough warning level is set. Whenever possible (when working with new code, at least) I find one should start with every possible warning on, and only selectively disable some individual warnings if necessary.
Here's the MSVC setting you want to change.
 

Kansoku

Member
So my college made a partnership with Microsoft and I got a DreamSpark Premium account, which means Visual Studio Ultimate 2013 for free :)
So happy right now.
 

poweld

Member
I used to do that for a while, but I now consider readability much more important, and do not seem to write that kind of bugs anyway. Like arit said, a compiler should be able to warn about that as long as a high enough warning level is set. Whenever possible (when working with new code, at least) I find one should start with every possible warning on, and only selectively disable some individual warnings if necessary.
Here's the MSVC setting you want to change.

I don't do it either, but I thought it was worth mentioning :)

Seems like it might be more handy for people slightly newer to development just to avoid that annoying pitfall. Take it or leave it, y'know?
 

Water

Member
I don't do it either, but I thought it was worth mentioning :)

Seems like it might be more handy for people slightly newer to development just to avoid that annoying pitfall. Take it or leave it, y'know?

That is why I have recommended the reverse trick to my students even after I stopped using it myself - especially any student who actually comes to me with that particular bug - but now that any decent compiler with proper settings warns about it, I'd just tell them to set their compiler properly and not even mention the trick.
 

tokkun

Member
C++11 has regex stuff but I guess there's a reason you're using boost and other libraries instead of it.

I tried C++11 initially. When using ECMAScript, it would throw exceptions if I tried to use character groups in brackets. If I switched to Posix Extended, it would fail to correctly parse when using character groups.

This is with libstdc++4.8.1, which is the newest version I can install on that development machine. I suspect that the issue is the standard library, but upgrading to 4.9 or switching to libc++ are not current feasible.
 
Top Bottom