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.
 
  • Locked thread
ljw1004
Jan 18, 2005

rum

Ender.uNF posted:

In my world, you can't define Func<int,var> outside a method anymore than you can declare public property var Fizzulator {get;set;}. Var is just a placeholder that the compiler fills in at compile time. If the type can't be deduced then that's a compilation error. Circular dependencies are a compilation error.

So when you see the VS tooltip for that var-returning method (or disassemble the IL), it is public { int x, string y } MethodName(). By definition, the compiler must be able to determine the shape of var or it won't compile. Having some slight CLR support for this (call it anonymous tuple or whatever) would make it easier for tooling to know what's up and to make it non-brittle by allowing addition of new members in the future, but isn't strictly required.

What holes are there in this scheme? You guys seem to see this as some kind of major problem that I just can't see, so I'm genuinely curious where the idea falls down, subject to the stated limits.

I'm considering the proposal where you use "var" as you described...


* What exactly is the type that's emitted for a method declared "var" (i.e. whose returned type should be figured out by the compiler)? Try it...
code:
static void f<T>(){Console.WriteLine(new { a = default(T), b = "tag" });}
[/coode]
The compiler currently emits a top-level sealed private type in your assembly called "<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>" in the root namespace.

If we allowed f to return that type, then the type obviously couldn't be sealed or private. It would still have to be generic though.

But now imagine if you have code in one assembly that returns one of these a/b anonymous types, and identical code in a different assembly. The result would be that each assembly ends up with DIFFERENT INCOMPATIBLE DEFINITIONS of its anonymous-type. That'd be terrible.

So you'd want some way to unify them. VB already does this kind of unification at runtime for anonymous delegates, but it's clunky and involves a thunk. The only clean solution would be to invent a new basic CLR mechanism for these nominal tuples, and make the CLR able to unify them, and get this change written into the ECMA CLI spec.




* What about fragility? Suppose I have code like this:
[code]
class C {static var f() { return D.f(); }}
class D {static var g() { return E.f(); }}
class E {static var h() { return 15; }}
It's clear that any change in the body of "E" could cause the signature of "C" to change. This is a pretty weird thing, especially if "C" is your library, and "E" is someone else's small under-the-hood library.

So just for good engineering sanity, to break these fragility chains, you should be able to name these types yourself. Maybe "{int x,string y}" is a good enough typename? in the same way that "int[]" is a good enough typename?

And well, once you've got the ability to name the types, then you can do this feature without allowing inferred "var" return types at all!

Adbot
ADBOT LOVES YOU

glompix
Jan 19, 2004

propane grill-pilled
Late and shallow on the discussion, but I really just wish that tuple components could be extracted like in Python, maybe like
code:
var(x, y) = ReturnTuple();
It's purely syntactic sugar, but it creates some nice use cases like that one. I rarely use tuples in C# anyway but it'd make sense if they're a supported data structure and not just a tacked-on BCL class.

Returning var (whatever that means) from a method or property seems pretty silly to me though in C#. It'd be interesting to see some code where that makes more sense than returning a named class, a dynamic, or even an object. Yes, the object type is still there and might be a better option than generic types sometimes. I've written code that could have benefited from just using an object instead of generics. (think ORMs)

edit for prediction: Duck typing will be an optional feature in .NET 7. :v:

glompix fucked around with this message at 22:52 on Jan 20, 2014

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

ljw1004 posted:

But now imagine if you have code in one assembly that returns one of these a/b anonymous types, and identical code in a different assembly. The result would be that each assembly ends up with DIFFERENT INCOMPATIBLE DEFINITIONS of its anonymous-type. That'd be terrible.

Is there some CLR feature that I don't know of that will let me use two named types from different assemblies interchangeably as long as they have the same signature?

ljw1004 posted:

It's clear that any change in the body of "E" could cause the signature of "C" to change. This is a pretty weird thing, especially if "C" is your library, and "E" is someone else's small under-the-hood library.

It's not like this problem doesn't exist today. If a library changes the class that it's returning, then you've broken all dependents regardless of whether the type you were returning had a name or not.

RICHUNCLEPENNYBAGS
Dec 21, 2010

Bognar posted:

I don't disagree that dynamics have their place, I just don't think that place is to deal with multiple return values when you could use tuples, anonymous types :smith:, or concrete classes instead.

Well, I probably wouldn't use them for your use case, but like I said, I have a philosophical objection to the idea of returning an anonymous object.

I just think it's unfortunate that there are so many folks in the C# community who have a pathological aversion to any technique requiring some care when being used.

ljw1004
Jan 18, 2005

rum

GrumpyDoctor posted:

Wait, what? I know F# but I can't think of any way to do this. What's the secret?

Sorry, I'm just referring to the current F# "records" feature, which gives you most of the niceness of returning a collection of named arguments:
code:
type Point2D = {x:float; y:float}

// Here's a "var-declared" function (which F# always allows).
// Moreover, the compiler guesses that it's returning the named type Point2D
let f () = {x=1.0; y=2.0}

// Here I'm invoking the "var-typed" function
let getx () = 
    let pt1 = f ()
    pt1.x
What's mysterious is that if I'd also defined "type Point3D = {x:float; y:float; z:float}" then the compiler's guess about the return-type of f as written above would be wrong.



Bognar posted:

Is there some CLR feature that I don't know of that will let me use two named types from different assemblies interchangeably as long as they have the same signature?

The No-PIA feature does this (enables CLR-unification of named types from two different assemblies so long as they have compatible signatures).

But not that this talk about returning anonymous types is NOT about "named types" - the anonymous types you write are unnamed, and so users would expect them to unify like other unnamed types...
code:
int[] x = new[] {1,2,3};
int[] y = new[] {1,2,3};
x = y;   // I expect that the unnamed types int[] and int[] can be unified since they share structure

var x = new {a=1, b="hello"};
var y = new {a=15, b="world"};
x = y;   // I expect that the two unnamed types for x and y can be unified since they share structure

Dim x = Function(a As Integer) a+1
Dim y = Function(b As Integer) b-1
x = y    ' I expect the two unnamed delegate types for x and y can be unified since they share structure


// ASSEMBLY1:
var f() { return new {a=1, b="hello"} }

// ASSEMBLY2:
var g() { return new {a=2, b="world"} }

// ASSEMBLY3:
var z = new[] {f(), g()};  // I expect two unnamed types returned by f() and g() to unify

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

ljw1004 posted:

The No-PIA feature does this (enables CLR-unification of named types from two different assemblies so long as they have compatible signatures).

Interesting, I've never heard about this... probably because I try to avoid Interop like the plague, but it's nice to know.

ljw1004 posted:

But not that this talk about returning anonymous types is NOT about "named types" - the anonymous types you write are unnamed, and so users would expect them to unify like other unnamed types...

That's a fair point, anonymous types are still nominal types but the expectation would be that they act like structural types.

Gul Banana
Nov 28, 2003

i feel like when someone installs visual studio 2012 it should pop up a .chm file explaining the use of ConfigureAwait.

zokie
Feb 13, 2006

Out of many, Sweden
I'm having trouble with using a DataGrid in WPF for the first time. What happens is that when you select the placeholder for a new item any further input adds a new row in the DataGrid but doesn't switch focus or anything. So if you click the bottom row and start typing you're gonna end up with as many new rows as keys you pressed... I hooked up some eventhandler and selected the item with index count -1, but this doesn't fix things because I still lose the first character that "initiated" the creation of the row. I hope this isn't intended behavior because it's stupid...

Does anyone have any tips or ideas for me to try?

Dr Monkeysee
Oct 11, 2002

just a fox like a hundred thousand others
Nap Ghost

glompix posted:

Late and shallow on the discussion, but I really just wish that tuple components could be extracted like in Python, maybe like
code:
var(x, y) = ReturnTuple();
It's purely syntactic sugar, but it creates some nice use cases like that one. I rarely use tuples in C# anyway but it'd make sense if they're a supported data structure and not just a tacked-on BCL class.

This is exactly what I was imagining. Just wrap some syntactic sugar around returning a Tuple and call it a day. As has been pointed out elsewhere it's not like Tuples are *all* that useful in hand-written code anyway.

Bareback Werewolf
Oct 5, 2013
~*blessed by the algorithm*~
Is there any reason I shouldn't learn VB as my first .NET language? C# seems to be the more popular language at the moment and it makes me wonder if I should learn it instead of VB since there will be more learning resources. Frankly my only reason for learning VB is that I'm burnt out on C-style syntax.

crashdome
Jun 28, 2011

SweetKarma posted:

Is there any reason I shouldn't learn VB as my first .NET language?

Not if your familiar with C-style. I'd say C# would be easier to someone already coding in C but, if it's bugging you then don't. The types and such are pretty much identical except in more advanced areas. You learn one, you are learning most of the other.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

SweetKarma posted:

Is there any reason I shouldn't learn VB as my first .NET language? C# seems to be the more popular language at the moment and it makes me wonder if I should learn it instead of VB since there will be more learning resources. Frankly my only reason for learning VB is that I'm burnt out on C-style syntax.

The languages basically have feature parity (there are some exceptions, but generally speaking it's true). It boils down to preference. Lots of folks prefer C#, but if I'm hiring for a .NET job and someone says they know VB, that's fine with me.

I generally find C# to be syntactically "nicer" and easier to read, although that's 100% subjective. In general, VB means more typing for the same results.

Dietrich
Sep 11, 2001

SweetKarma posted:

Is there any reason I shouldn't learn VB as my first .NET language? C# seems to be the more popular language at the moment and it makes me wonder if I should learn it instead of VB since there will be more learning resources. Frankly my only reason for learning VB is that I'm burnt out on C-style syntax.

Depends, which of these two things makes you want to claw your eyes out:

code:
Dim findCustomer As Func(Of String, Dictionary(Of Integer, Customer))
findCustomer = Function(s) 
                  Dim matches = CustomerRepository.FindCustomersWithName(s)
                  Return matches.ToDictionary(Function(c) c.CustomerId)
               End Function
code:
Func<string, Dictionary<int, customer>> findCustomer;
findCustomer = s => {
    var matches = CustomerRepository.FindCustomersWithName(s);
    return matches.ToDictionary(c => c.customerId);              
  }
I know which one is my preference.

Bareback Werewolf
Oct 5, 2013
~*blessed by the algorithm*~
Alright, thanks guys. I'll just stop being picky and go with C#. I'd like to start writing windows store apps and it seems like most information about that focuses on C# or HTML/JavaScript so C# is probably the path of least resistance. Unless someone knows of some awesome VB windows store app learning resources.


e: ^^^^ The C# syntax is definitely more familiar, but honestly neither one really bugs me.

Bareback Werewolf fucked around with this message at 01:52 on Jan 22, 2014

RICHUNCLEPENNYBAGS
Dec 21, 2010

SweetKarma posted:

Is there any reason I shouldn't learn VB as my first .NET language? C# seems to be the more popular language at the moment and it makes me wonder if I should learn it instead of VB since there will be more learning resources. Frankly my only reason for learning VB is that I'm burnt out on C-style syntax.

There is close to zero difference in capabilities but C# developers tend to earn more on average if that is important to you.

ljw1004
Jan 18, 2005

rum

Dietrich posted:

Depends, which of these two things makes you want to claw your eyes out: [...]

Hey, the VB version should be shorter because the language has inference for function types!

code:
Dim findCustomer = Function(s As String) 
                       Dim matches = CustomerRepository.FindCustomersWithName(s)
                       Return matches.ToDictionary(Function(c) c.CustomerId)
                   End Function

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Well, the shortest C# could be without losing (too much) readability is:

C# code:
Func<string, Dictionary<int, Customer>> findCustomer = s => CustomerRepository.FindCustomersWithName(s).ToDictionary(c => c.CustomerId);

Dietrich
Sep 11, 2001

My intention was to demonstrate the difference in verbosity between VB and C# when using generics and lambda expressions, not to write the shortest code in either language.

Personally, (Of T, T2, T3) bugs the poo poo out of me, especially with nested generics, and a lot of fluent language APIs look especially bad in VB compared to C#. (Map<Class>.To("TableName") versus Map(Of Class).To("TableName");)

Function(x)/Sub(x) is much more annoying to write than x =>

And End Sub / End Function is much more annoying to write than }

Not that I don't have a great deal of respect for what you've accomplished in VB.Net, ljw1004

Gul Banana
Nov 28, 2003

i agree with all of the above :(
the vb *editor*, though, that's amazing. its background compilation seems to be totally perfect, and you never have to think about indentation. i don't think i make any more actual keypresses when writingvb code than c# - it just ends up taking up more room on the screen.

you know what would be cool: an per-user option to change your casing display. so i could see this:

pre:
class Foo
    sub Bar()
        dim x = 50
        for each baz in Enumerable.Range(x)
            baz.Frob()
        next
    end sub
end class

which vbc.exe handles just fine, without having to resort to vim, and without inflicting it on others.

Gul Banana fucked around with this message at 14:59 on Jan 22, 2014

Dietrich
Sep 11, 2001

Did you know that this thread has been around since 2007? Good lord. This very thread contains the post I made the day I had to learn C# because VB.Net didn't have support for virtual events, way back in 2009. Now me wants to slap then me in the face for using NHibernate to hydrate business layer objects, which made my program all sorts of stupid complicated.

wwb
Aug 17, 2004

That is the thing about a library -- you really are taking on a relationship. Things can be huny dory today but how do you know that you won't want to end up killing the bastard who foisted that shite upon you in 4 years.

Also nuget is like the pill -- makes sleeping with everyone way too easy. Discuss.

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice

wwb posted:

That is the thing about a library -- you really are taking on a relationship. Things can be huny dory today but how do you know that you won't want to end up killing the bastard who foisted that shite upon you in 4 years.

Also nuget is like the pill -- makes sleeping with everyone way too easy. Discuss.

Not to get too SJW or anything, but I doubt most women would classify the pill as "makes sleeping with everyone way too easy".

But I do appreciate the sentiment... And agree that an external library really is a relationship. You depend on it and it grows to intertwine itself with your code to a greater (lover like NHibernate) or lesser (lets just be friends log4net) degree. You must often compromise when you both have differing ideas about how to accomplish something.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Dietrich posted:

My intention was to demonstrate the difference in verbosity between VB and C# when using generics and lambda expressions, not to write the shortest code in either language.

Personally, (Of T, T2, T3) bugs the poo poo out of me

I really like the way that reads because of the 'Of'

Unrelated, but the one thing I don't like about generic type syntax is that there's nothing to indicate that one (or I guess some pretty soon) of them is a return type other than convention. If if the language just mandated <ReturnT; InputT1, InputT2,...> (semicolon or something separating return type(s) from input) that'd make me happier.

glompix
Jan 19, 2004

propane grill-pilled
That's one of the things I hate the most about the MSFT dev community. I worked in relative isolation for a few years coming out of college, but now we've hired these people who are really adamant about never writing any code in the name of "not reinventing the wheel" apparently. I get that sentiment, but there's a time and a place for that. They just take everything they read on the internet to heart, I guess. Last time I looked over this one devs shoulder I saw a ACME.ViewModels project that just had like 2 classes in it in the solution. The other projects in the solution are pretty massive and the viewmodels wouldn't be reused so it was pretty weird. When I asked about it she said she read it as a best practice on the internet.

Most importantly, I don't want to have to learn some gigantic beast like WCF or Workflow Foundation to do a simple task that would take less time to implement by hand. It's really too easy to misuse a library and find yourself debugging someone else's more general-purpose (and therefore more complicated) code.

Dietrich
Sep 11, 2001

Munkeymon posted:

I really like the way that reads because of the 'Of'

Unrelated, but the one thing I don't like about generic type syntax is that there's nothing to indicate that one (or I guess some pretty soon) of them is a return type other than convention. If if the language just mandated <ReturnT; InputT1, InputT2,...> (semicolon or something separating return type(s) from input) that'd make me happier.

I see what you're saying, but mentally I just substitute "of" when appropriate in reading code. Like List<Int> I read as "list of integers" while For<ICustomerRepository>.CreateMock() I read as "For ICustomerRepository, create a mock". I guess it's easier for me to add missing information into a sentence than to remove superfluous information.

Which makes sense to me, I mean spoken English is built upon inference and noun substitution, but seldom does it include words that are intended to be ignored. So that's probably why I find it easier to insert "of" where necessary than to remove "of" when not needed.

RICHUNCLEPENNYBAGS
Dec 21, 2010

Dietrich posted:

My intention was to demonstrate the difference in verbosity between VB and C# when using generics and lambda expressions, not to write the shortest code in either language.

Personally, (Of T, T2, T3) bugs the poo poo out of me, especially with nested generics, and a lot of fluent language APIs look especially bad in VB compared to C#. (Map<Class>.To("TableName") versus Map(Of Class).To("TableName");)

Function(x)/Sub(x) is much more annoying to write than x =>

And End Sub / End Function is much more annoying to write than }

Not that I don't have a great deal of respect for what you've accomplished in VB.Net, ljw1004

I don't think verbosity si a big deal with .NET languages because of Intellisense. Certainly C# itself is quite verbose compared to some other popular languages and typical style also uses variable names that are, comparatively, long.

ManoliIsFat
Oct 4, 2002

RICHUNCLEPENNYBAGS posted:

I don't think verbosity si a big deal with .NET languages because of Intellisense. Certainly C# itself is quite verbose compared to some other popular languages and typical style also uses variable names that are, comparatively, long.
Well writing it, no, but reading VB can be a huge pain if you're not in it every day. And there's for sure a difference between coding style and syntax. There's some old adage about this, code taking minutes to write, hours to debug, and will be with you for years.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

EDIT-Figured out, leaving in for proof of stupidity/posterity

Got a weird one. Another developer has handed me a vb.Net 4.5 web forms project that I have to basically export/customize. However, the project won't run, even though it claims to build successfully (VS2012). When running I get this:
code:
Could not load type '_(projectname).Global_asax'.

Line 1:  <%@ Application Codebehind="Global.asax.vb" Inherits="_(projectname).Global_asax" Language="vb" %>
Googling around led to me to some weird ideas and solutions, most of them claiming that there's a disconnect between the codebehind and the dll. Lots of cleans, rebuilds, re-git-gets, path checking and so on later and I've made exactly zero progress. Looking at the references, I see these references aren't linking properly:
code:
Antlr3.Runtime
AspNet.ScriptManager.jQuery
AspNet.ScriptManager.jQuery.UI.Combined
EntityFramework
EntityFramework.SqlServer
Microsoft.AspNet.Web.Optimization.WebForms
Microsoft.ScriptManager.MSAjax
Microsoft.ScriptManager.WebForms
System.Web.Optimization
System.Web.Providers
So I think oh, ok let's get all nu-get up on this piece son. Things were going fine, in that I was nu-getting and the reference warnings were going away for each package. But then, during EntityFramework install, VS2012 crashes, hard. No recovery options, just submit error report or restart. So I restart the project and sure enough, all my references are broken again. And I can't find them in the installed references. And I can't reinstall them, because VS thinks they are already installed.

So I mess around a bit with this info:
http://stackoverflow.com/questions/18630332/cant-uninstall-reinstall-nuget-package

Edit packages.config, delete it, etc. but still no go, stuck in that indeterminate "it's installed but you can't reference it" state. Anybody here run into something similar?

Scaramouche fucked around with this message at 23:56 on Jan 23, 2014

Mr Shiny Pants
Nov 12, 2012
Anyone have any experience with UPNP in .Net?

I want my program to open a port on a router so that it can accept incoming traffic on a random port.
I've looked for a good library and found Mono.nat. After turning on Upnp on my router it finds it but I can't get my external ip.

I've turned off the Windows firewall and during debugging I can see it communicating with the router but i have no clue how to interpret the returned data. Everything looks ok.

ljw1004
Jan 18, 2005

rum

Mr Shiny Pants posted:

Anyone have any experience with UPNP in .Net?

I want my program to open a port on a router so that it can accept incoming traffic on a random port.
I've looked for a good library and found Mono.nat. After turning on Upnp on my router it finds it but I can't get my external ip.

I've turned off the Windows firewall and during debugging I can see it communicating with the router but i have no clue how to interpret the returned data. Everything looks ok.

I wrote a detailed article on UPnP (for both .NET45 and WinRT) here:
http://www.codeproject.com/Articles/458807/UPnP-code-for-Windows-8

But I was focused just on explaining at a low level what the protocol actually is, and how it works. I don't know if it'll help you.


Incidentally, Apple programs (e.g. iTunes) use a UPnP discovery library called "Bonjour" on Windows. Bonjour fails to discover the Airport Express speakers on my home network. However, my own implementation of SSDP is able to discover them! Take that, Apple :)

Mr Shiny Pants
Nov 12, 2012
Thanks, i'll take a look.

Would this code by any chance also work on Mono? I need to run this on Linux also :)

Edit: drat, that looks complicated.....

I have a bit of a dilemma, one the one hand it would be awesome that it would autoconfigure, on the other hand there are some completely broken UPNP servers making the event of it working as it should a bit of a crapshoot.

Maybe some old fashioned port forwarding would be enough. :)

Mr Shiny Pants fucked around with this message at 22:40 on Jan 23, 2014

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Scaramouche posted:

A bunch of crap

Found it. Was a combination of things, with the references being red herrings. When the guy who handed this off copied over the names spaces/inherits he somehow forgot that CaSe SeNsItIvE is important, which makes me wonder how he ever ran it on his machine in the first place. So many different causes for that error (could not load type line 1) things got pretty wacky in the troubleshooting stage.

Che Delilas
Nov 23, 2009
FREE TIBET WEED
I have a best practices/oop design question. It's not specific to .Net but that's what I'm working with, so here goes.

I'm working on an MVC4 web application. In its domain model, it has an entity which I will call "Item". Each Item has a unique Sku number that is used to locate the item in a physical inventory (so Sku 1 is the first in the drawer, Sku 5 is farther back in the drawer, etc). When a particular Item is dispensed, its slot, and therefore its Sku number becomes available for use. When a new Item is added, we want to assign the first available Sku number to that Item.

I also have an ItemRepository interface that defines all the CRUD for Items.

My question is, where do I perform the calculation that finds the next available Sku? It's clearly a business rule, so it doesn't belong in any Controllers, but I feel like putting it in the ItemRepository is inappropriate; if I change the repository, I would have to re-create the Sku calculation. So where does the calculation go?

This is a personal project for learning purposes with no deadline, so I'd like to do it right and learn a good habit.

Mr Shiny Pants
Nov 12, 2012
I would put it in something like an Item factory. When a new item is created the factory is responsible for setting the right SKU number.

Dietrich
Sep 11, 2001

Mr Shiny Pants posted:

I would put it in something like an Item factory. When a new item is created the factory is responsible for setting the right SKU number.

This is the ticket.

Your ItemFactory should be passed an implementation of your IItemRepository, perform whatever query is necessary to gather the information needed to assign the next SKU, then spit out a new item with the SKU.

ninjeff
Jan 19, 2004

Che Delilas posted:

I feel like putting it in the ItemRepository is inappropriate; if I change the repository, I would have to re-create the Sku calculation.

Forgive me if I'm wrong, but this seems like what you actually want. The calculation should be different for different data stores, so that it doesn't take forever to run. Even in Mr Shiny Pants'/Dietrich's solution, you still need to write the IItemRepository query that the ItemFactory calls.

Mr Shiny Pants
Nov 12, 2012

ninjeff posted:

Forgive me if I'm wrong, but this seems like what you actually want. The calculation should be different for different data stores, so that it doesn't take forever to run. Even in Mr Shiny Pants'/Dietrich's solution, you still need to write the IItemRepository query that the ItemFactory calls.

That also sounds plausible, if the SKU number is something that is dependent on the type of repository and not just a number for tracking/identification.

Mr Shiny Pants fucked around with this message at 17:52 on Jan 24, 2014

Dietrich
Sep 11, 2001

ninjeff posted:

Forgive me if I'm wrong, but this seems like what you actually want. The calculation should be different for different data stores, so that it doesn't take forever to run. Even in Mr Shiny Pants'/Dietrich's solution, you still need to write the IItemRepository query that the ItemFactory calls.

I don't know. The Repository should know how to ferry data to and from a database, and that's pretty much it.

At the very least, you should put the new SKU calculation code into it's own class where you can mock the data coming from the database, then set up test cases where you pass it data that should lead to various scenarios and validate that the result is what you expect.

Dietrich fucked around with this message at 18:21 on Jan 24, 2014

Che Delilas
Nov 23, 2009
FREE TIBET WEED

Dietrich posted:

This is the ticket.

Your ItemFactory should be passed an implementation of your IItemRepository, perform whatever query is necessary to gather the information needed to assign the next SKU, then spit out a new item with the SKU.

A factory sounds like it could be a good solution, except for one problem. Right now the new Items are being created by the ASP.NET MVC model binder (i.e. behind the scenes when the user posts the form). Is it possible to modify or replace the model binder with something that could use an ItemFactory? And if so, can I do so via dependency injection so that I don't introduce a tight dependency onto wherever the model binder is?

quote:

At the very least, you should put the new SKU calculation code into it's own class where you can mock the data coming from the database, then set up test cases where you pass it data that should lead to various scenarios and validate that the result is what you expect.

Hmm, could I pop this class behind an interface and slide it between the controller and the repository? This would have the calculation being performed as an extra step post-instantiation, rather than during it, so it kind of seems like a hack, but at least it would sort of force the calculation to be performed if that interface was the only way the controller could get at Items.

So instead of Controller --> IItemRepository the relationship would go Controller --> IItemManager --> IItemRepository.

The factory sounds like the ticket, I'm just not sure how to work it into the MVC framework. If it's possible, I'm sure I can find out how.

Thanks for the ideas guys.

Adbot
ADBOT LOVES YOU

epswing
Nov 4, 2003

Soiled Meat

Che Delilas posted:

Hmm, could I pop this class behind an interface and slide it between the controller and the repository? This would have the calculation being performed as an extra step post-instantiation, rather than during it, so it kind of seems like a hack, but at least it would sort of force the calculation to be performed if that interface was the only way the controller could get at Items.

So instead of Controller --> IItemRepository the relationship would go Controller --> IItemManager --> IItemRepository.

This is how I do it. I have Services (what you just referred to as Managers) which represent The App (which is its own VS class lib) and sits in between the UI (an ASP.NET controller, a WPF viewmodel, etc) and a datastore (SQL Server, WhateverNoSql, InMemoryMock, etc). I end up with app.dll which contains all the services and business logic and has no references to anything but does define repository interfaces, data.dll has a reference to app.dll and implements the interfaces in whichever way it needs to (entity framework, for example), and at that point you can tack on an ASP/Console/WPF/Test project which has a reference to app.dll (and probably to data.dll if you're doing IoC just to specify which datastore your app wants to use) and start poking it to get work done.

Think about where Your Application actually lives, and if you'd be able to swap your UI (WPF to ASP.NET) and swap your datastore (EntityFramework to NHibernate) without losing any business logic.

epswing fucked around with this message at 20:31 on Jan 24, 2014

  • Locked thread