• 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

Two Words

Member
Does Apple offer any discounts for students when it comes to developer licenses? This Swift announcement just got me pretty hyped to do some stuff for iOS.

Isn't it free to develop for iOS?


I'd be pretty pumped if you're looking into developing Apps. Seems like it streamlines the process, and Playground looks great.

BTW, the book for the language is up already on iBooks, Free of course.

https://itunes.apple.com/gb/book/swift-programming-language/id881256329?mt=11

Is there any language that has similar capabilities to compare it to in regards to Playground?
 

Tamanon

Banned
Does Apple offer any discounts for students when it comes to developer licenses? This Swift announcement just got me pretty hyped to do some stuff for iOS.

No. Only in their University Developer program, but that's through the university itself. Otherwise, no student discounts.
 

Mr.Mike

Member
Does anyone have a video of the swift demonstration. All I can find is the video introducing swift and some shitty video from someone sitting at the conference.

EDIT: This should have been in the presentation thread.
 

delirium

Member
Who at Apple thought this was a good idea?

Dgisdwq.jpg


This is going to give people a lot of headaches in the future.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
redacted

iOS devs here; What are you opinions on Swift so far compared to developing strictly with Obj-C?
 

oxrock

Gravity is a myth, the Earth SUCKS!
Swift doesn't look too bad, but there are a few things that are like why?

In any case, I'm all for languages that are curt and straight forward.

Here's the tour.

Thanks for posting that link, can't help but feel that swift looks a LOOOT like python with more static data types. Which of course automatically makes me think "hey, it can't be that bad!" :p
 

hateradio

The Most Dangerous Yes Man
redacted

iOS devs here; What are you opinions on Swift so far compared to developing strictly with Obj-C?
I don't develop with Objective-C, but I think it's definitely a move like C++ to Python, which some people will like and others will not.

In the end, I'm sure more people will learn Swift since it's easier to understand than O-C, which has confusing patterns at first glance.


Who at Apple thought this was a good idea?

Dgisdwq.jpg


This is going to give people a lot of headaches in the future.
I don't think anyone will create names using emoji intentionally . . . The point is that any character can be used, which is fine for international developers.

Code:
// however
var  🍎 = "apple"
 

D4Danger

Unconfirmed Member
If that is when a variable is declared, how is it's data type determined?

https://developer.apple.com/library...dTour.html#//apple_ref/doc/uid/TP40014097-CH2

Simple Values

Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.

Code:
var myVariable = 42
myVariable = 50
let myConstant = 42

A constant or variable must have the same type as the value you want to assign to it. However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above, the compiler infers that myVariable is an integer because its initial value is a integer.

If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.

Code:
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70

tl;dr: colon
 

Husker86

Member
So I am working on a mobile multiplayer game (turn-based) and am getting to the point of making the logic for finding other players who are currently seeking a game and creating a match.

My MySQL database has a value for each user, "isSeeking" (I made my database before researching syntax conventions...oops). If it is "1", then they are currently seeking a game.

Now, when a player hits the "Find Game" button in my game, it will update their "isSeeking" value to 1. I could make that php script also check for other players who have isSeeking == 1 and make the match from there, but if there aren't any at the time then I have to have a way to continually check the database without the user initiating the script.

Is this what I would use a cron job for? Or is there something else I'm completely overlooking?

On another note, regarding Swift, I'm kinda happy I have held off on learning native iOS development now (only made a Unity game for it so far), though I'm sure knowing Obj-C workflow will help in learning Swift.
 

r1chard

Member
Who at Apple thought this was a good idea?

Dgisdwq.jpg


This is going to give people a lot of headaches in the future.
The following code contains a backdoor:

debug = true

if environ['PRODUCTION_ENVIRONMENT']: dеbug = false

Note: the "е" in the second "dеbug" is cyrillic Ye. Depending on the font used, it can be indistinguishable.
 

leroidys

Member
The following code contains a backdoor:



Note: the "е" in the second "dеbug" is cyrillic Ye. Depending on the font used, it can be indistinguishable.

Not a problem, I'll just set my editor to display in hexadecimal instead of unicode.

:(
 

usea

Member
I guess I don't understand the benefit of this.
Which part? Not specifying the types, or the unicode support for variable names?

Not having to list the type is because of local type inference. The compiler will insert the type for you, based on what type of expression is on the right hand side of the equals sign. C# does this with "var" and C++ does it with "auto". It's a popular feature in functional programming languages.

As for the unicode identifier support, there's plenty of other languages with that as well (scala, go, python 3?). It can be annoying if you're looking at code with characters in it that you can't easily type, but that's going to depend on your keyboard. It's a bit English-centric (and American-centric) to try and limit the characters to ascii or some other american-accessible set of characters.

I mean, I get the problems with it. I certainly wouldn't want to maintain code where a person named a function ♡, but naming has always been a style issue.
 

hateradio

The Most Dangerous Yes Man
Type inference is great. I also really like the division between constant values and variables and also that it avoids setting null values, unlike Java and Scala. :( (I wish Scala had gone that route, but I guess it had to be backwards compatible.)

Now, when a player hits the "Find Game" button in my game, it will update their "isSeeking" value to 1. I could make that php script also check for other players who have isSeeking == 1 and make the match from there, but if there aren't any at the time then I have to have a way to continually check the database without the user initiating the script.

Is this what I would use a cron job for? Or is there something else I'm completely overlooking?
You could setup a cron job, but that would still not be enough for a player who sees an empty waiting list.

Most likely, this issue would be resolved using several AJAX requests at an interval once a person hits the search button.

Code:
// Pseudo-JS

function checkForSeekingPlayers () {

   // a request to a page which returns users who are seeking to play
   var ajax = new ajax request
   var interval;

   ajax.onload = function () {
       // do some kind of listing update
       updatePlayerList(this.responseText)
   }

  ajax.onerror = function () {
      window.clearInterval(interval)
  }

   // send the request every five seconds
   // this will set the update to happen multiple times
   interval = window.setInterval(function () {
       ajax.send()
   }, 5000);
}

var checkingForPlayers = false
searchButton.onclick = function (e) {
    e.preventDefault()

    // set some global-type variable to true so that you
    // don't send more requests than needed

    // a better method would be to detach this event,
    // replacing it with a callback that just contains e.preventDefault()

    if (!checkingForPlayers ) {
        checkForSeekingPlayers()
    }

    checkingForPlayers = true;
};
 
It's also another neat way to accidentally introduce bugs. :)

Oh, sure. But the benefits far outweigh the negatives, at least for me. There are cases where explicit type is still very useful, but as someone who has to use Java 6 for an assignment for university right now, I miss Scala's type inference. It gets really old writing
Code:
private Map<Integer, List<Edge>> adjacentEdges = new HashMap<Integer, List<Edge>>();
when it could be
Code:
private val adjacentEdges = Map.empty[Int, List[Edge]]
Also, lack of list/map literals is really annoying in Java. Yeah, there is Arrays.asList, but for some reason, that returns a fixed-size list so I need to do
Code:
new ArrayList(Arrays.asList(...))
Java 8 seems to help a lot in a bunch of different areas, so I'm looking forward to being able to use it at University in about 10 years. Sigh.
 

iapetus

Scary Euro Man
Oh, sure. But the benefits far outweigh the negatives, at least for me. There are cases where explicit type is still very useful, but as someone who has to use Java 6 for an assignment for university right now, I miss Scala's type inference. It gets really old writing
Code:
private Map<Integer, List<Edge>> adjacentEdges = new HashMap<Integer, List<Edge>>();
when it could be
Code:
private val adjacentEdges = Map.empty[Int, List[Edge]]

That's why I just write:

private Map<In, Li<Ed adjacentEdges =

and let the IDE fill in the gaps. Complaints about how long it takes to type something like that are utterly irrelevant in the real world where IDEs provide highly intelligent auto-completion. Any benefit it brings in terms of avoiding bugs and clarity outweighs that tenfold.
 
Most likely, this issue would be resolved using several AJAX requests at an interval once a person hits the search button.

Save us, ES6 Promises!
http://www.html5rocks.com/en/tutorials/es6/promises/

Pseudo code
Code:
    You: Yo server, promise to tell me when there's another player searching.
    Server: OK! 

    Someone else: Hey, is anyone else looking
    Server: Oh yeah, I promised user: You to tell if someone was searching. Hey You, there's a game!

    You: Awesome.

Code:
    You: Yo server, promise to tell me when there's another player searching.
    Server: OK! 

    You: Exit game
    Someone else: Hey, is anyone else looking
    Server: Oh yeah, I promised user: You to tell if someone was searching. Hey You, there's a game!

    You: rejected
    Server: Well crap, I'll tell you someone else when there's another game.
 
That's why I just write:

private Map<In, Li<Ed adjacentEdges =

and let the IDE fill in the gaps. Complaints about how long it takes to type something like that are utterly irrelevant in the real world where IDEs provide highly intelligent auto-completion. Any benefit it brings in terms of avoiding bugs and clarity outweighs that tenfold.

I do use an IDE (IntelliJ IDEA) and it does make life a lot easier, but I still vastly prefer using C# for example, where the 'var' keyword exists. That said, I currently only work on projects where I know everyone involved and teams are <5 people big. I imagine if you have a lot of people working on a project this sort of thing changes.
 
Save us, ES6 Promises!
http://www.html5rocks.com/en/tutorials/es6/promises/

Pseudo code
Code:
    You: Yo server, promise to tell me when there's another player searching.
    Server: OK! 

    Someone else: Hey, is anyone else looking
    Server: Oh yeah, I promised user: You to tell if someone was searching. Hey You, there's a game!

    You: Awesome.

Code:
    You: Yo server, promise to tell me when there's another player searching.
    Server: OK! 

    You: Exit game
    Someone else: Hey, is anyone else looking
    Server: Oh yeah, I promised user: You to tell if someone was searching. Hey You, there's a game!

    You: rejected
    Server: Well crap, I'll tell you someone else when there's another game.

Promises don't really work like that nor do they solve the need for multiple ajax requests in this context. Polling (issuing multiple ajax requests) is necessary cause most http servers will force a timeout after a certain interval. Now, we do have web sockets to eliminate polling.

The scenario really plays out like this though if you want to be compatible with browsers pre-web sockets.

Code:
User clicks Button.
Button fires Event Callback
Event Callback calls a function which returns a Promise saying "If a match was found, it will be resolved; otherwise, It will say it was rejected and why. Rejections are typically due to fatal errors or something like the matching server is down for maintenance so this service is unavailable. The function may be Implemented as a continuous set of asynchronous XHR requests or via web sockets based on facilities available.

Now, Futures and Promises have been written in many back end languages so you could implement a web socket back end that functions like your scenario. However, it still requires the client library to implement functions that return promises which any web developer should attempt to do where possible so you can avoid scenarios where the client appears to hang.

Edit: and to finish off, the true purpose of promises is to have asynchronous actions follow in an order (timing issues have been the bane of many a web developer) without having to trace through lots of callbacks.
 
You are correct, I was going into edit the post ton after I noticed how I totally misintepreted what the user actually wanted but you beat me. I thought user was having issue with doing stuff while/after async things were happening in back end
 

Husker86

Member
Type inference is great. I also really like the division between constant values and variables and also that it avoids setting null values, unlike Java and Scala. :( (I wish Scala had gone that route, but I guess it had to be backwards compatible.)


You could setup a cron job, but that would still not be enough for a player who sees an empty waiting list.

Most likely, this issue would be resolved using several AJAX requests at an interval once a person hits the search button.

Before I look more into this, would this work for a mobile app or is this a browser-based game solution? I basically want the player to be able to start seeking and then immediately return to the home activity of the app and let the server do matchmaking.

I started making a php script that will basically check the database for all seeking players, then match two together in a for loop (matches array index 0 & 1, 2 & 3, 4 & 5, etc.); I just need a way for this script to run on its own. Which actually brings up another question...is using SQL database queries in a for loop a bad idea?

Thanks for the help!
 
Before I look more into this, would this work for a mobile app or is this a browser-based game solution? I basically want the player to be able to start seeking and then immediately return to the home activity of the app and let the server do matchmaking.

I started making a php script that will basically check the database for all seeking players, then match two together in a for loop (matches array index 0 & 1, 2 & 3, 4 & 5, etc.); I just need a way for this script to run on its own. Which actually brings up another question...is using SQL database queries in a for loop a bad idea?

Thanks for the help!

Better to execute the query then run through the result set and filter inside of the program as each database call has a cost. Where possible, you should eliminate database calls.
 

CrankyJay

Banned
Wouldn't call it that much of a shot in the arm; so far it's considerably less than it gets when someone poses an interesting coding question. :p

I've been thinking it might be useful if people kind of post their experience and level of experience in case someone might want to post some more targeted questions. Sort of like:

CrankyJay - C#/WPF/MVC/SQL

I guess not necessary, since people will just sort of jump in and answer as they can. Just thought it would be cool.
 

r1chard

Member
That's why I just write:

private Map<In, Li<Ed adjacentEdges =

and let the IDE fill in the gaps. Complaints about how long it takes to type something like that are utterly irrelevant in the real world where IDEs provide highly intelligent auto-completion. Any benefit it brings in terms of avoiding bugs and clarity outweighs that tenfold.
On the clarity front, I contend you significantly *lose* clarity - all that extra noise to parse to figure out what's going on - and impose unnecessary burdens on the writer.

As for errors, I believe explicit declared type systems are a crutch that maybe pick up on the occasional error but give far too many programmers false confidence that their code is correct. Much better to instead promote automated unit tests for that purpose.
 

hateradio

The Most Dangerous Yes Man
Before I look more into this, would this work for a mobile app or is this a browser-based game solution? I basically want the player to be able to start seeking and then immediately return to the home activity of the app and let the server do matchmaking.

I started making a php script that will basically check the database for all seeking players, then match two together in a for loop (matches array index 0 & 1, 2 & 3, 4 & 5, etc.); I just need a way for this script to run on its own. Which actually brings up another question...is using SQL database queries in a for loop a bad idea?

Thanks for the help!
To avoid race conditions and to lower the query loop, you could set up the cron job to run a script that searches the DB and stores parsed data into a JSON file (or something else) that all the players can then check.

cron -> check db at an interval, save results in JSON
player -> get updated JSON at an interval, inspect it for any matched players

I didn't know if you were using JS or not, but polling (asking the server for updated content on the client side at an interval) should be available to you through some kind of server request.
 

iapetus

Scary Euro Man
On the clarity front, I contend you significantly *lose* clarity - all that extra noise to parse to figure out what's going on - and impose unnecessary burdens on the writer.

Unnecessary burdens on the writer are massively overrated as an argument, as I've already pointed out. Yes, it imposes a burden on the writer of deciding what the correct level of abstraction for the variable type is - but that's not a bad burden to place on the writer anyway. The 'but all that typing!' argument is entirely moot with a smart IDE, and in any real-world system the cost of maintaining and continuously developing it is going to dwarf the initial writing cost anyway.

I disagree with the claim that you lose clarity too; nothing that's there in a explicitly typed variable declaration is noise. The more complex the type being declared, the less likely it is that the type being assigned to it will be exactly the same, in my experience, so where things look redundant you're more likely to be dealing with a very simple case where any 'noise' is minimal.

Against that, you've got the vast loss of clarity between:

var myThingummy = node.getThingummy();

and

Badger myThingummy = node.getThingummy();

In the first case you can't tell at a glance what the type of your variable is. In the second case you can. In the first case, in fact, you've got two levels of indirection to go through to find the type - first find your node, then find its getThingummy method. And there's pretty much no extra 'noise'.

As for errors, I believe explicit declared type systems are a crutch that maybe pick up on the occasional error but give far too many programmers false confidence that their code is correct. Much better to instead promote automated unit tests for that purpose.

Heh. Declared types give programmers false confidence that their code is correct and unit tests never do?
 

Chris R

Member
I've been thinking it might be useful if people kind of post their experience and level of experience in case someone might want to post some more targeted questions. Sort of like:

CrankyJay - C#/WPF/MVC/SQL

I guess not necessary, since people will just sort of jump in and answer as they can. Just thought it would be cool.

It would be good for questions over PMs though.
 

r1chard

Member
I disagree with the claim that you lose clarity too; nothing that's there in a explicitly typed variable declaration is noise.
We're just going to have to disagree in that respect :)

Heh. Declared types give programmers false confidence that their code is correct and unit tests never do?
Wait a second. Unit tests (when written correctly) explicitly test that the code in question does what was intended. How is that not instilling confidence?
 

Godslay

Banned
how do you get into the situation where you get contacts from an interviewer? I've never done an interview where I've seen such an opportunity unless it was a purely informational interview.

Also what should I expect for a programming interview? from the posts in here it seems quite a bit different from regular interviews. Asking problem solving questions and what not....seems even more stressful than a traditional interview.

Lastly do you know of any other good job search sites focused on tech/programming other than dice?

When I was first starting out I applied for an internship that was basically doing some database administration with some coding as a secondary role. Internships were slow at the time, and even though it wasn't the best fit (I wanted a role primarily as a developer), I figured why not?

I applied, got an interview. The guy that interviewed me saw that my resume was tailored to land a dev job, and less so for a db admin. We talked about what my goals were, and where I would like to end up. He happened to know a couple of companies that might be a better fit, and set me up with contact information which ultimately helped me complete an internship and get some real-world experience. Now I know not every interview will go this way, but for an internship position it doesn't hurt to be honest imo. Tell them straight up that you are looking to break into the industry how ever you can, and any help doing so would be appreciated. Might not work every time, but doesn't hurt to ask. Maybe some feel differently about doing this, and you might have to feel it out from interview to interview.

As far as the interviews themselves, I've had both. Coding interviews and informational interviews. If you do get an interview, just ask if there is going to be a coding test when they call you. Doesn't hurt to ask, and will let you prepare. My latest job was basically to see if I would fit in with the office culture, no coding because they saw that I had relevant experience. So that was nice. When I've had coding interviews, they come in two flavors, whiteboard and pencil and paper in a quiet room. Pseudocode has been fine in both cases. The whiteboard usually sucks because it does introduce a level of pressure the other interviews don't bring. I just try and talk through it and ask as many questions as I can. As you can see from the thread, what they may ask you varies widely. If you don't know the answer, say so. I will always say that I don't know, but I have some good ideas on to where I can start. Namely being Stackoverflow lol.

As far as finding jobs, I would start within your school. If they don't offer help, then look on local job boards, such as a state job service, Craigslist type sites, Indeed, as well as in the newspaper and on newspaper sites. Also scout out for job fairs, those are great places to meet people. If you are not having luck on those sites/areas, reach out to businesses in the area. The guy we hired as an intern, and eventually became fulltime reached out to my boss. Basically said he was looking for an internship, and even if we weren't hiring he'd like to come in and see how we did business. Shows some initiative, and if you don't get a job out of it you have at least another person that you know in the business.

The main thing I would take away from it all would just to put yourself out there, and cast as wide a net as possible, and be prepared when you interview. I hope that helps and good luck.
 

Massa

Member
We're just going to have to disagree in that respect :)


Wait a second. Unit tests (when written correctly) explicitly test that the code in question does what was intended. How is that not instilling confidence?

Unit tests can reveal bugs in your code but they can't guarantee that bugs don't exist, whether they were well written or not.
 

astraycat

Member
Unnecessary burdens on the writer are massively overrated as an argument, as I've already pointed out. Yes, it imposes a burden on the writer of deciding what the correct level of abstraction for the variable type is - but that's not a bad burden to place on the writer anyway. The 'but all that typing!' argument is entirely moot with a smart IDE, and in any real-world system the cost of maintaining and continuously developing it is going to dwarf the initial writing cost anyway.

I disagree with the claim that you lose clarity too; nothing that's there in a explicitly typed variable declaration is noise. The more complex the type being declared, the less likely it is that the type being assigned to it will be exactly the same, in my experience, so where things look redundant you're more likely to be dealing with a very simple case where any 'noise' is minimal.

Against that, you've got the vast loss of clarity between:

var myThingummy = node.getThingummy();

and

Badger myThingummy = node.getThingummy();

In the first case you can't tell at a glance what the type of your variable is. In the second case you can. In the first case, in fact, you've got two levels of indirection to go through to find the type - first find your node, then find its getThingummy method. And there's pretty much no extra 'noise'.

Well, I'd argue that your example suffers more from poorly naming things than anything else. If you've named your variable myThingummy, and your method is getThinggumy, I'd assume it's a Thingummy, and that you're just unimaginative at naming classes. Revealing it as a Badger only serves to confuse -- Thingummys can implicitly become Badgers?

If instead it was something like:

auto badger = node.getBadger();

then it wouldn't be terribly hard to imagine that badger's actually a Badger.

In fact, at that point

Badger badger = node.getBadger();

is rather redundant. The first explicit Badger just wastes 3 extra keypresses for no extra information.
 

r1chard

Member
Unit tests can reveal bugs in your code but they can't guarantee that bugs don't exist, whether they were well written or not.
I never said they guarantee bugs don't exist. I said they increase confidence in the code doing what it's intended to do, which is something that explicit typing statements won't do - all they do is ensure your code compiles, which guarantees your code compiles with the compiler.

Also, what astraycat said, in terms of that other thing.
 
I recall being staunchly opposed to type inference in C# when it first appeared. It reminded me too much of variant variables in VB, and that type of loose typing didn't strike me as particularly useful. It obviously wasn't the same thing, but the "var" keyword itself offended my sensibilities. I absolutely saw the value of it with Linq, and sometimes it was the only way to approach it when queries produced anonymous types, but I would avoid it otherwise.

It's now been a few years since I completely changed my stance to now being generally supportive of type inference, and I now forget precisely the impetus for that change in opinion beyond that obvious case of incredibly verbose generic types, but I will not argue with someone that prefers using explicit typing.

I do, however, love me some unit tests. Loves me some.
 

Two Words

Member
Which part? Not specifying the types, or the unicode support for variable names?

Not having to list the type is because of local type inference. The compiler will insert the type for you, based on what type of expression is on the right hand side of the equals sign. C# does this with "var" and C++ does it with "auto". It's a popular feature in functional programming languages.

As for the unicode identifier support, there's plenty of other languages with that as well (scala, go, python 3?). It can be annoying if you're looking at code with characters in it that you can't easily type, but that's going to depend on your keyboard. It's a bit English-centric (and American-centric) to try and limit the characters to ascii or some other american-accessible set of characters.

I mean, I get the problems with it. I certainly wouldn't want to maintain code where a person named a function &#9825;, but naming has always been a style issue.
Mainly the type inference stuff. I guess I never had a problem with declaring a variable with int or double or bool or whatever. Then again, I've only been making programs with no more than ~200 lines of code at most so far.
 
Mainly the type inference stuff. I guess I never had a problem with declaring a variable with in or double or bool or whatever. Then again, I've only been making programs with no more than ~200 lines of code at most so far.

I get that. While I've come to accept and use type inference, I will still explicitly type primitives and such.

Code:
int countOfApples = 0;
bool canHaveCoffee = true;

But when it gets to items where the type is already on the right side of the expression, I've come to accept that it's redundant on the left.

Code:
var myFoo = new Foo();

It's still just as strongly typed as before. myFoo is a Foo and will always be a Foo. This isn't dynamic or duck-typing. And then when you think about generics, it's especially verbose to repeat the type.

Code:
var myDictionary = new Dictionary<string, IEnumerable<long>>();

And once you start to accept those items, maybe that's as far as you go, but then you might also start accepting the usage of "var" for function results. Or you may not, or you may just stick with explicit typing everywhere. It's up to you (and your team). Just pick a style and stick with it.
 

usea

Member
In C# I always use var, except in the rare occasions where it's a huge readability gain, or when I'm intentionally making a different variable type, such as like IEnumerable<T> foo = new List<T>(); That's pretty rare, too.

The type doesn't actually matter most of the time. The variable name tells you whatever you need to know. If you need to know the exact type for some reason, you can just mouseover it.
 

Magni

Member
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:
class APIStory : INotifyPropertyChanged
    {
        public string id { get; set; }

        public APILikes likes { get; set; }

        private bool _liked { get; set; }
        public bool liked
        {
            get
            {
                this._liked = this.likes.data.Contains(APIClient.currentUser);
                return this._liked;
            }
            set
            {
                if (this._liked != value)
                {
                    this._liked = value;
                    NotifyPropertyChanged("liked");
                    NotifyPropertyChanged("likeText");
                }
            }
        }

        public string likeText
        {
            get
            {
                return this.liked ? "unlike" : "like";
            }
        }

        public void Like()
        {
            APIClient.Like(this.id);
            this.Refresh();
            this.liked = true;
        }

        public void Unlike()
        {
            APIClient.Unlike(this.id);
            this.Refresh();
            this.liked = false;
        }

        public async void Refresh()
        {
            var story = await APIClient.GetStory(this.id);
            this.likes = story.likes;
            // todo reload other stuff
        

        // events

        public event PropertyChangedEventHandler PropertyChanged;
        
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

Relevant XAML code:
Code:
<MenuFlyoutItem Text="{Binding likeText}" Click="FeedStoryLike_Click" />

Relevant code-behind:
Code:
private void FeedStoryLike_Click(object sender, RoutedEventArgs e)
{
    var menuFlyoutItem = sender as MenuFlyoutItem;
    var story = menuFlyoutItem.DataContext as APIStory;
    if (story.liked)
    {
        story.Unlike();
    }
    else
    {
        story.Like();
    }
}

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.
 
redacted

iOS devs here; What are you opinions on Swift so far compared to developing strictly with Obj-C?

Its a way to get people who would never otherwise develop for iOS to develop for the platform, and its a way to capture the market share of things like Corona and Game Maker.

I honestly don't see myself moving to it as anything more than a rapid prototyping tool at best. I'll be sticking to Obj-C/C++ for now.

What are the best sources (books, videos, etc.) to learn about iOS programming?

I honestly haven't found many sites other than the official Apple developer portal that were that useful originally. I guess the Ray Wenderlich site is okay but super outdated. In general that's the problem with almost every tutorial site for iOS out there that isn't Apple. They're pretty much all grossly outdated within a few months.

My first in depth exposure to Obj-C was using Cocos for a project I contracted on, and before that I had primarily been a C++/C# guy. Nowadays I do a mix of Obj-C and C++ depending on the target platform(s). I will say that I think the current state of Obj-C is a LOT easier to understand than older ones. Not really having to worry about Retain/Release or Synthesizing etc is pretty nice.
 

iapetus

Scary Euro Man
Well, I'd argue that your example suffers more from poorly naming things than anything else.

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

If instead it was something like:

auto badger = node.getBadger();

then it wouldn't be terribly hard to imagine that badger's actually a Badger.

In fact, at that point

Badger badger = node.getBadger();

is rather redundant. The first explicit Badger just wastes 3 extra keypresses for no extra information.

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.

We're just going to have to disagree in that respect :)

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

Wait a second. Unit tests (when written correctly) explicitly test that the code in question does what was intended. How is that not instilling confidence?

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
 

hateradio

The Most Dangerous Yes Man
Key presses are irrelevant to me, too. But I'm on the side of inference.

I don't think autocomplete is even an issue. Regardless if you have that, using inference is a visually neater way of declaring variables most of the time. And there's nothing anyone can say that would contradict that. :p

It's also especially helpful in doing quick scripts on the console, where typing types would be redundant or unnecessary.

Well, I'd argue that your example suffers more from poorly naming things than anything else. If you've named your variable myThingummy, and your method is getThinggumy, I'd assume it's a Thingummy, and that you're just unimaginative at naming classes.
I agree that when there is ambiguity, that the type should be declared, otherwise no. However, naming is an issue of praxis, which you may not be able to avoid or control.

Eg, in .NET there's an image class, and it has a drawing context, but the context's type is not clearly defined by the method name, GetDrawingContext(). If we expected a DrawingContext, we'd be wrong, so in that case using the type on the variable makes sense.

Therefore, I prefer to declare the type explicitly when the variable's type may be ambiguous, unless I named the variable after the class (eg: var somethingClass), which is itself an issue: What if I later use a different class? (Rhetorical question, no need to answer.)

Using auto/var/val/let is a great option, and we can always use the older notation, so to me there's no issue in the end.
 

iapetus

Scary Euro Man
Key presses are irrelevant to me, too. But I'm on the side of inference.

And that's fine. My objection isn't to preferring inference - I suspect that's subjective - just to using irrelevant and inaccurate claims to support that preference. :D

I don't think autocomplete is even an issue. Regardless if you have that, using inference is a visually neater way of declaring variables most of the time. And there's nothing anyone can say that would contradict that. :p

Because it's subjective. :p The same claim could be made the other way round, and there's nothing anyone can say that would contradict that either.

It's also especially helpful in doing quick scripts on the console, where typing types would be redundant or unnecessary.

Possibly true. I deal more in big apps than quick scripts, and my concern is more for how well those apps stand up than how many keystrokes it takes me to do some quick tests on the console. Different roles may lead to different preferences here.

I agree that when there is ambiguity, that the type should be declared, otherwise no.

I can see this point, but I like consistency and have a nagging suspicion that it's possible to introduce ambiguity indirectly through refactoring.

Using auto/var/val/let is a great option, and we can always use the older notation, so to me there's no issue in the end.

Agreed. Though in Swift specifically, I don't particularly like the notation for explicit typing.
 
Top Bottom