Having trouble understanding patterns
Hello, I`m a second year student and I'm reading about patterns like a factory pattern. I have trouble understanding why I should use patterns and when to use which pattern.
162 Replies
Patterns usage is learned by example. For example, Singletons. The purpose of Singletons is to have one instance of an object. The reason to use Singletons comes from the explicit choice to disallow other parts of the program tracking their own version of the object. For example, you want one single place for your theme configuration, instead of loading it from disk throughout the program.
Most of the ones you hear about originally come from a classic software engineering book called Design Patterns. If you really want the background on those, read that book.
I personally think design patterns are over-used as a fancy way of saying what should generally be simple concepts.
The whole point of patterns is that the same recurring patterns keep coming up in software design and it's an attempt to formalize and name what those patterns are.
Factories are a bit more complex where the object creation is abstracted away. The purpose of doing so is sometimes because people want a
Example ex = new ExampleBuilder().SetFieldA(1).SetFieldB(2).Build();
type of architecture. Which is bad design cuz we have Example ex = new Example { A = 1, B = 2 }
syntax. The true purpose of the Factory pattern is to alleviate downstream changes, in which if you change something it should be ABI compliant unless its a function sig change.
I would focus on terminology and implementation over the need to actually use these patterns, as mtreit is right in that patterns are overused for a mispurpose like corporate buzzwords.
I would assume modix has a
$factory
Nope?Would at least having a basic understanding of those patterns make me a better programmer because then I know how I should/could write code in a more "consistent" way?
$patterns
That's the general idea behind formalizing design patterns, yes.
Do you recommend reading the book in that case?
That said, I never read the design patterns book.
Design patterns come after learning algorithms tbh
And I don't generally think in terms of design patterns when I write software.
Although I probably use those patterns organically.
Does it come naturally then or is it not really something to keep in mind when programming?
Ah okay
It's like anything, some people find it really helpful to try and study the patterns in a formal way, other people don't.
Naturally most of the time. Like my themes example is an actual deployment of singleton I used.
That said, without things like the factory pattern we would not have the absolutely priceless work of art known as FizzBuzz Enterprise Edition...
https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition/tree/uinverse/src/main/java/com/seriouscompany/business/java/fizzbuzz/packagenamingpackage/impl/factories
brooo what
lmfao
Okok
Wtf
Reee line breaks
In case it's not obvious, that's a parody of how programming in the enterprise world works.
Going from reading C# to reading Java is so jarring
yeye i know
Did you ever look into them or did you just learn what is "wrong" and "right" after years of experience?
I've leafed through a colleagues copy of the book and if you work in software long enough you'll just see plenty of explanations of different patterns. But I couldn't tell you what most of the formal design patterns actually are.
I use singletons a lot. I know that's a design pattern.
Factory pattern, I use that sometimes.
Observer, Adapater, Bridge, Mediator, Decorator, Facade, Visitor <- I see these terms regularly and have no real idea what they are.
A lot of the classic design patterns are very much associated with "object oriented programming" and some programmers (myself, for instance) are not a fan of object oriented programming and thus don't really feel like these classic design patterns are all that important.
but you should read up on them and decide for yourself.
Reading the classic book certainly wouldn't hurt. It's a classic for a reason 🙂
Okay okay
Thanks for the advice
inb4 mtreit loses his job
You're more likely to get a job knowing OOP and Algorithms than Design patterns
Yeah I figured but I was just wondering if design patterns are like a golden standard
Definitely not, and if you see people pushing them they're often a corporate shill
What about principles? Does your code need to follow like every SOLID principle or is it the same story as design patterns?
Same thing
That's another thing that people who are way into OOP get all excited about.
What is the alternative to OOP then?
Procedural and functional approaches mostly
Composition using interfaces
Instead of inheritance
Procedural is usually for scripting purposes, functional is more for math and data science
Some of the more modern languages (Rust is a good example) don't really even have OOP support.
Composition using interfaces makes me shutter when I think about partial classes and code generation
In which you lug around a state object from method call to method call
I feel pretty lost hearing this
Does this mean that like rust has no classes?
Or is OOP not just classes, inheritance, encapsulation etc?
Rust has types. They can have state.
But it doesn't really support inheritance hierarchies
What is a state?
Data associated with a type.
OOP is mostly about stitching functions that work on state with the state itself (encapsulation)
the fields and properties in a class
Like if you have a file type, state associated with an instance of that type would be things like the file name, the file size, the security descriptor, etc.
So a state is just a type with it's properties?
new object();
<- stateoh okay
so functional is that you take the state and then adjust it and then OOP would be adjusting the state using methods within the class?
In reverse, stateless would be without data
I'm hearing a lot of big words
'adjust it' is typically said as mutate
Functional programming is where you take arrays of data and mutate it to a final result using functions
That's not a good definition of functional programming.
Functional programming is not a good definition of functional programming.
From what im understanding this is functional programming
Do you guys maybe have like any sources where I could find more about this
so i can see it visually in code or something
That's like the opposite of functional programming
Side effects REEE
😭
Calling that function has the side effect of mutating a property of the input.
Functional programming doesn't have (or generally avoids) side effects.
Functional revolves around 'pure' functions in which there is an input and an output
I mean this function has an input and output
Often data is immutable when you follow a functional approach.
its not pure, cuz it mutates state
something.property += 5; is a mutation
When you 'mutate' an object in a functional approach you return a copy (a new object) with the updated state.
So then you'd copy the "something", mutate it return the new thing or ?
ohh
yup
but why
Because
It eliminates entire classes of bugs.
Like you don't have thread safety issues when objects are immutable.
In some languages (Rust, F#) everything is immutable by default and you have to opt-in to mutability using things like the
mut
keyword.You still have thread safety issues, theyre just contained in a single area
I wish C# was immutable by default but it was designed before that feature of functional programming kind of became popular in the industry (i.e., outside of academic circles.)
immutable by default is a bad idea when youre oop
Immutability also allows for performance optimizations.
so
Is a better representation
void
yeah whatever you get the idea
Why is this better
missing semi colon
ok man
think ur so funny
but I just dont get
how this is better than just changing the object that gets passed in the input
you'd spend extra time cloning it then, no?
Typically you arent really lugging around state like that
change something to an integer
If you want to deep dive on why this kind of thing is useful, Eric Lippert wrote a great series of articles on his blog about immutability.
Fabulous adventures in coding
Immutability – Fabulous adventures in coding
You should actually preach haskell mtreit
Born to haskell, forced to C#
I'm too dumb for Haskell
its not better, its less efficient, as a trade off
so the trade off is immutability/less bugs for less efficient code
$itdepends
It's not necessarily less efficient.
In some cases immutability leads to performance improvements. Like if you know a type is immutable you can eliminate certain kinds of checks (bounds checks for instance.)
C# leverages spans in this style
Span is a good example
what is span
A view of an array
In a nutshell, a pointer and a length
Representing a slice (span) of some arbitrary memory.
Not necessarily an array.
They're very useful for doing high performance stuff when you're working with low level constructs like raw bytes.
I don't know what this means
They reduce the difficulty of passing around lengths as well
Where in a low level language like C, you supply the length EVERYWHERE, or its in its own state in a struct
To quote the article I linked:
System.Span<T> is a new value type at the heart of .NET. It enables the representation of contiguous regions of arbitrary memory, regardless of whether that memory is associated with a managed object, is provided by native code via interop, or is on the stack. And it does so while still providing safe access with performance characteristics like that of arrays.
Yeah I'm reading it and its just words man
I cant help it
Im reading it like now
but I don't get what it's for
Stephen gives a bunch of examples
'arbitrary memory' is technically true, but you will usually see span wrapping a subset of an array or list, more so ReadOnlySpans
I dont know what arbitrary memory and arbitrary pointers are
It's used with stackalloc quite a lot.
At least that's one of my main uses of it.
Think of memory as state
Or NativeMemory.Alloc
Do you know what a pointer is?
Not really
Pointers are indexes into memory
I just know that it points somewhere and thats how you know where something is stored
memory[n] where n is the pointer
I haven't really been taught or have read into low-level things like pointers
A pointer is a variable that holds an address to some type.
Okok
Every byte in your computer's memory has an address.
(There's a physical address and a virtual address but that's probably diving a bit too deep...)
(registers are not memory, registers are not memory)
Registers are memory. Just a really fast form of memory that is directly part of the CPU.
👍
Beware of non internal working ram
So
Then somewhere on my pc theres a pointer from my variable number to 9?
likely on the stack yes
In that case no, the memory location referenced by 'number' directly contains the value 9.
There is no pointer there.
A variable is a "named memory location". In this case the name is 'number'
mtreit you're confusing pointers with pointer variables
so memory[number] = 9 ?
no
9 isnt a pointer?
It's not, no.
9 can be a pointer if you want to handle a probable segfault
so memory[number] = pointer => 9
memory[address] = value
where memory is type of unsigned byte
and pointer is type of DWORD (64 bit number on a x64 machine)
I would say
memory[address] = value
true
okay
so value = 9
what is the address?
&value is the address
Nobody knows
Well I know
its greater than 0x800000
you'd have to
To find it out
Which changes every time you run the program
is that C# ??
yes
madness
My favorite feature
value = 9
is a tricky example because the compiler could decide not to store that value in the computer's main memory (RAM) at all. It could use a CPU register for instance.
Depending on what you then do with the value
variable.oo
What would be a better example
Nothing
The theory is there
The intrinsics of the compiler are not important
The result is the same irregardless
mtreit does C# have an unsafe everywhere option
It really helps to learn a little bit about how computers actually work down at the lower levels. You don't have to be writing code in assembly, but knowing the very basics of things like assembly language and computer memory and CPU registers and stack vs. heap and that kind of things goes a LONG way to understanding programming.
Not that I'm aware of.
ok thats enough of that
@mellowzippy I have a couple of books I'd recommend if you want to learn more:
https://codehiddenlanguage.com/
https://www.amazon.com/Secret-Life-Programs-Understand-Computers/dp/1593279701
“Code” by Charles Petzold
A few interactive circuits from “Code” 2nd edition
The Secret Life of Programs: Understand Computers -- Craft Better Code
The Secret Life of Programs: Understand Computers -- Craft Better Code
Where are resources to learn that? I'm not learning it anywhere in the near future at school
Oh okay
Thank you
The way I learned pointers is by suffering through coding the gameboy lol
I also have a few blog posts:
https://treit.github.io/programming,/interviewing/2019/03/12/BitAndBytesPart1.html
https://treit.github.io/programming,/interviewing/2019/03/17/BitAndBytesPart2.html
https://treit.github.io/powershell,/programming/2019/05/05/GettingComfortableWithBinary.html
Notes to self
Fundamentals I wish you knew: bits and bytes. Part 1.
The scene: a programming interview The interview candidate is staring at me, frowning. Behind them is the whiteboard, where they have tentatively sketched out a rudimentary function prototype. They are trying to understand more about what exactly they need to do to implement the function, and it’s going poorly.
Notes to self
Fundamentals I wish you knew: bits and bytes. Part 2.
Here’s a file. It contains a series of integer values, stored as binary. I’d like you to do some processing of each value. How would you do it?
Ah yes "the bits and the bytes" the coming of age tale
Getting comfortable with binary data (with help from PowerShell)
this scares me thoHow would I read these books? Do I read a chapter and then do an exercise with it? Do I make notes? How do I make reading this worth my time instead of forgetting it after a week?
read it twice
one for reading
one for comprehension
In my experience learning programming is being exposed, then understanding
I would just read through them and make notes on things you find interesting. Keep them on your bookshelf for reference.
Hey that blog post has my proudest (and practically only) UI achievement: figuring out how to write the HTML for this table 😄
My experience learning spans is "What the fuck is a span" followed by "oh I can pass an array or list thru it" ending with "damn this saves a headache"
Have you read them? Or do you recommend them because you've heard great things about them?
I've read them
okok
^ in this style
I'll read your blog posts too
If you have anything else I should learn before touching my computer again please tell me :) I want to learn but I just didn't really know about this stuff until now
No you should definitely touch your computer and study at the same time
Concepts are nothing without implementation
Don't try to learn everything at once. This stuff takes a lot of time to master. (And I use the term master very loosely, I've been doing this for many years and I am constantly learning new things every day)
Which is again why paradigms like Singletons often go misused
Sure but I would like to at least have a basic foundation of this so that I at least know about it
How are they misused?
Oh mtreit another thing, people will often try to learn singletons or factory patterns so they use it for the next thing they are working on until it works and that invariably gets pushed
Messing with memory and pointers is a realtively optional task, I wouldn't really waste life on it early in your learning career.
its a more advanced topic
Knowledge about them is good though
I'm entirely self taught. I read a lot of books. One of the most influential books I read was a somewhat obscure title called "The most complex machine" that taught how computers work from the ground up. The two books I linked earlier do much the same thing. Well worth reading to get sort of a foundation on what's going on under the hood.
And yeah most of the time you don't need that low level knowledge. But when you do need it, it's super helpful.
okok
head hurts
pointers bytes
mtreit convince ImageSharp to give image loading a reasonable interface
came for factory pattern
gonna finish that phrase lol
that was it
sorry to dissapoint
lol
But I learned a lot at least
What’s wrong with how it works now?
Images you load have to be flipped