❔ Huffman Coding Tree returning BaseNode
I have the following Huffman tree implementation:
HuffTree.root() and HuffInternalNode both return BaseNode type. Is there a way to only return the specific type that it is? HuffLeafNode or HuffInternalNode?
Trying to traverse the tree is a nightmare of explicit type casting.
E.g.
HuffLeafNode node = (HuffLeafNode)((HuffInternalNode)htree.root()).left()
11 Replies
while traversing, you'll have to check whether it's a node or a value anyways, right?
also a bit off topic, you can replace your methods with read-only properties
so you don't need the
()
everywhereSo you're thinking something like:
That would make sense and wouldn't be as messy as I was thinking.
I'll look into read only properties, pretty new to c# but i worked with c++ a long time ago. I'm assuming thats like setting a getter on the property without a setter?
Something like:
public int weight { get; }
As long as you're using
HuffBaseNode
and having separate nodes for branching and leaf nodes, you're going to be pushing polymorphic handling onto the caller. Which is fine if you're doing this to conserve space, but you could handle this via logic instead of the type system, too.
If you switch to properties, you can do that. No need for IsLeaf()
as you're already hardcasting in the original. If you need multiple types of leaf nodes, then you can make a separate interface specifically for leaf nodes to implement.
Partially rewritten
That looks good. I'll try it out. Thanks!
Reformatted it using your changes + some more and its a lot cleaner. Prefix table generating and everything
I'd ditch the
this.
, but it's personal preference.
_name
is a popular convention for private fields and is sufficient to prevent naming conflicts.so is
this
just not needed in c#, i'm used to js and python where its needed.
i guess in python its self
but same thingIt's rarely required.
like only if there is ambiguity? say there was a public Traverse function, then i'd have to call
this.Traverse()
Only if you're trying to call an extension method on the current instance. Otherwise, smart use of capitalization conventions should supplant all other uses (some people do prefer
this
instead though).
That shouldn't be ambiguous, but yes.alright thanks a ton for your help. @Tvde1 SM PO LD PM , you too
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.